btrfs-progs: fix device missing of btrfs fi show with seed devices
[platform/upstream/btrfs-progs.git] / cmds-filesystem.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #define _XOPEN_SOURCE 500
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <sys/ioctl.h>
23 #include <errno.h>
24 #include <uuid/uuid.h>
25 #include <ctype.h>
26 #include <fcntl.h>
27 #include <ftw.h>
28 #include <mntent.h>
29 #include <linux/limits.h>
30 #include <getopt.h>
31
32 #include "kerncompat.h"
33 #include "ctree.h"
34 #include "ioctl.h"
35 #include "utils.h"
36 #include "volumes.h"
37 #include "version.h"
38 #include "commands.h"
39 #include "list_sort.h"
40 #include "disk-io.h"
41
42
43 /*
44  * for btrfs fi show, we maintain a hash of fsids we've already printed.
45  * This way we don't print dups if a given FS is mounted more than once.
46  */
47 #define SEEN_FSID_HASH_SIZE 256
48
49 struct seen_fsid {
50         u8 fsid[BTRFS_FSID_SIZE];
51         struct seen_fsid *next;
52 };
53
54 static struct seen_fsid *seen_fsid_hash[SEEN_FSID_HASH_SIZE] = {NULL,};
55
56 static int add_seen_fsid(u8 *fsid)
57 {
58         u8 hash = fsid[0];
59         int slot = hash % SEEN_FSID_HASH_SIZE;
60         struct seen_fsid *seen = seen_fsid_hash[slot];
61         struct seen_fsid *alloc;
62
63         if (!seen)
64                 goto insert;
65
66         while (1) {
67                 if (memcmp(seen->fsid, fsid, BTRFS_FSID_SIZE) == 0)
68                         return -EEXIST;
69
70                 if (!seen->next)
71                         break;
72
73                 seen = seen->next;
74         }
75
76 insert:
77
78         alloc = malloc(sizeof(*alloc));
79         if (!alloc)
80                 return -ENOMEM;
81
82         alloc->next = NULL;
83         memcpy(alloc->fsid, fsid, BTRFS_FSID_SIZE);
84
85         if (seen)
86                 seen->next = alloc;
87         else
88                 seen_fsid_hash[slot] = alloc;
89
90         return 0;
91 }
92
93 static void free_seen_fsid(void)
94 {
95         int slot;
96         struct seen_fsid *seen;
97         struct seen_fsid *next;
98
99         for (slot = 0; slot < SEEN_FSID_HASH_SIZE; slot++) {
100                 seen = seen_fsid_hash[slot];
101                 while (seen) {
102                         next = seen->next;
103                         free(seen);
104                         seen = next;
105                 }
106                 seen_fsid_hash[slot] = NULL;
107         }
108 }
109
110 static const char * const filesystem_cmd_group_usage[] = {
111         "btrfs filesystem [<group>] <command> [<args>]",
112         NULL
113 };
114
115 static const char * const cmd_df_usage[] = {
116         "btrfs filesystem df <path>",
117         "Show space usage information for a mount point",
118         NULL
119 };
120
121 static char *group_type_str(u64 flag)
122 {
123         u64 mask = BTRFS_BLOCK_GROUP_TYPE_MASK |
124                 BTRFS_SPACE_INFO_GLOBAL_RSV;
125
126         switch (flag & mask) {
127         case BTRFS_BLOCK_GROUP_DATA:
128                 return "Data";
129         case BTRFS_BLOCK_GROUP_SYSTEM:
130                 return "System";
131         case BTRFS_BLOCK_GROUP_METADATA:
132                 return "Metadata";
133         case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
134                 return "Data+Metadata";
135         case BTRFS_SPACE_INFO_GLOBAL_RSV:
136                 return "GlobalReserve";
137         default:
138                 return "unknown";
139         }
140 }
141
142 static char *group_profile_str(u64 flag)
143 {
144         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
145         case 0:
146                 return "single";
147         case BTRFS_BLOCK_GROUP_RAID0:
148                 return "RAID0";
149         case BTRFS_BLOCK_GROUP_RAID1:
150                 return "RAID1";
151         case BTRFS_BLOCK_GROUP_RAID5:
152                 return "RAID5";
153         case BTRFS_BLOCK_GROUP_RAID6:
154                 return "RAID6";
155         case BTRFS_BLOCK_GROUP_DUP:
156                 return "DUP";
157         case BTRFS_BLOCK_GROUP_RAID10:
158                 return "RAID10";
159         default:
160                 return "unknown";
161         }
162 }
163
164 static int get_df(int fd, struct btrfs_ioctl_space_args **sargs_ret)
165 {
166         u64 count = 0;
167         int ret, e;
168         struct btrfs_ioctl_space_args *sargs;
169
170         sargs = malloc(sizeof(struct btrfs_ioctl_space_args));
171         if (!sargs)
172                 return -ENOMEM;
173
174         sargs->space_slots = 0;
175         sargs->total_spaces = 0;
176
177         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
178         e = errno;
179         if (ret) {
180                 fprintf(stderr, "ERROR: couldn't get space info - %s\n",
181                         strerror(e));
182                 free(sargs);
183                 return -e;
184         }
185         /* This really should never happen */
186         if (!sargs->total_spaces) {
187                 free(sargs);
188                 return -ENOENT;
189         }
190         count = sargs->total_spaces;
191         free(sargs);
192
193         sargs = malloc(sizeof(struct btrfs_ioctl_space_args) +
194                         (count * sizeof(struct btrfs_ioctl_space_info)));
195         if (!sargs)
196                 return -ENOMEM;
197
198         sargs->space_slots = count;
199         sargs->total_spaces = 0;
200         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
201         e = errno;
202         if (ret) {
203                 fprintf(stderr, "ERROR: get space info count %llu - %s\n",
204                                 count, strerror(e));
205                 free(sargs);
206                 return -e;
207         }
208         *sargs_ret = sargs;
209         return 0;
210 }
211
212 static void print_df(struct btrfs_ioctl_space_args *sargs)
213 {
214         u64 i;
215         struct btrfs_ioctl_space_info *sp = sargs->spaces;
216
217         for (i = 0; i < sargs->total_spaces; i++, sp++) {
218                 printf("%s, %s: total=%s, used=%s\n",
219                         group_type_str(sp->flags),
220                         group_profile_str(sp->flags),
221                         pretty_size(sp->total_bytes),
222                         pretty_size(sp->used_bytes));
223         }
224 }
225
226 static int cmd_df(int argc, char **argv)
227 {
228         struct btrfs_ioctl_space_args *sargs = NULL;
229         int ret;
230         int fd;
231         char *path;
232         DIR  *dirstream = NULL;
233
234         if (check_argc_exact(argc, 2))
235                 usage(cmd_df_usage);
236
237         path = argv[1];
238
239         fd = open_file_or_dir(path, &dirstream);
240         if (fd < 0) {
241                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
242                 return 1;
243         }
244         ret = get_df(fd, &sargs);
245
246         if (ret == 0) {
247                 print_df(sargs);
248                 free(sargs);
249         } else {
250                 fprintf(stderr, "ERROR: get_df failed %s\n", strerror(-ret));
251         }
252
253         close_file_or_dir(fd, dirstream);
254         return !!ret;
255 }
256
257 static int match_search_item_kernel(__u8 *fsid, char *mnt, char *label,
258                                         char *search)
259 {
260         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
261         int search_len = strlen(search);
262
263         search_len = min(search_len, BTRFS_UUID_UNPARSED_SIZE);
264         uuid_unparse(fsid, uuidbuf);
265         if (!strncmp(uuidbuf, search, search_len))
266                 return 1;
267
268         if (strlen(label) && strcmp(label, search) == 0)
269                 return 1;
270
271         if (strcmp(mnt, search) == 0)
272                 return 1;
273
274         return 0;
275 }
276
277 static int uuid_search(struct btrfs_fs_devices *fs_devices, char *search)
278 {
279         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
280         struct list_head *cur;
281         struct btrfs_device *device;
282         int search_len = strlen(search);
283
284         search_len = min(search_len, BTRFS_UUID_UNPARSED_SIZE);
285         uuid_unparse(fs_devices->fsid, uuidbuf);
286         if (!strncmp(uuidbuf, search, search_len))
287                 return 1;
288
289         list_for_each(cur, &fs_devices->devices) {
290                 device = list_entry(cur, struct btrfs_device, dev_list);
291                 if ((device->label && strcmp(device->label, search) == 0) ||
292                     strcmp(device->name, search) == 0)
293                         return 1;
294         }
295         return 0;
296 }
297
298 /*
299  * Sort devices by devid, ascending
300  */
301 static int cmp_device_id(void *priv, struct list_head *a,
302                 struct list_head *b)
303 {
304         const struct btrfs_device *da = list_entry(a, struct btrfs_device,
305                         dev_list);
306         const struct btrfs_device *db = list_entry(b, struct btrfs_device,
307                         dev_list);
308
309         return da->devid < db->devid ? -1 :
310                 da->devid > db->devid ? 1 : 0;
311 }
312
313 static void splice_device_list(struct list_head *seed_devices,
314                                struct list_head *all_devices)
315 {
316         struct btrfs_device *in_all, *next_all;
317         struct btrfs_device *in_seed, *next_seed;
318
319         list_for_each_entry_safe(in_all, next_all, all_devices, dev_list) {
320                 list_for_each_entry_safe(in_seed, next_seed, seed_devices,
321                                                                 dev_list) {
322                         if (in_all->devid == in_seed->devid) {
323                                 /*
324                                  * When do dev replace in a sprout fs
325                                  * to a dev in its seed fs, the replacing
326                                  * dev will reside in the sprout fs and
327                                  * the replaced dev will still exist
328                                  * in the seed fs.
329                                  * So pick the latest one when showing
330                                  * the sprout fs.
331                                  */
332                                 if (in_all->generation
333                                                 < in_seed->generation) {
334                                         list_del(&in_all->dev_list);
335                                         free(in_all);
336                                 } else if (in_all->generation
337                                                 > in_seed->generation) {
338                                         list_del(&in_seed->dev_list);
339                                         free(in_seed);
340                                 }
341                                 break;
342                         }
343                 }
344         }
345
346         list_splice(seed_devices, all_devices);
347 }
348
349 static void print_devices(struct btrfs_fs_devices *fs_devices,
350                           u64 *devs_found)
351 {
352         struct btrfs_device *device;
353         struct btrfs_fs_devices *cur_fs;
354         struct list_head *all_devices;
355
356         all_devices = &fs_devices->devices;
357         cur_fs = fs_devices->seed;
358         /* add all devices of seed fs to the fs to be printed */
359         while (cur_fs) {
360                 splice_device_list(&cur_fs->devices, all_devices);
361                 cur_fs = cur_fs->seed;
362         }
363
364         list_sort(NULL, all_devices, cmp_device_id);
365         list_for_each_entry(device, all_devices, dev_list) {
366                 printf("\tdevid %4llu size %s used %s path %s\n",
367                        (unsigned long long)device->devid,
368                        pretty_size(device->total_bytes),
369                        pretty_size(device->bytes_used), device->name);
370
371                 (*devs_found)++;
372         }
373 }
374
375 static void print_one_uuid(struct btrfs_fs_devices *fs_devices)
376 {
377         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
378         struct btrfs_device *device;
379         u64 devs_found = 0;
380         u64 total;
381
382         if (add_seen_fsid(fs_devices->fsid))
383                 return;
384
385         uuid_unparse(fs_devices->fsid, uuidbuf);
386         device = list_entry(fs_devices->devices.next, struct btrfs_device,
387                             dev_list);
388         if (device->label && device->label[0])
389                 printf("Label: '%s' ", device->label);
390         else
391                 printf("Label: none ");
392
393         total = device->total_devs;
394         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
395                (unsigned long long)total,
396                pretty_size(device->super_bytes_used));
397
398         print_devices(fs_devices, &devs_found);
399
400         if (devs_found < total) {
401                 printf("\t*** Some devices missing\n");
402         }
403         printf("\n");
404 }
405
406 /* adds up all the used spaces as reported by the space info ioctl
407  */
408 static u64 calc_used_bytes(struct btrfs_ioctl_space_args *si)
409 {
410         u64 ret = 0;
411         int i;
412         for (i = 0; i < si->total_spaces; i++)
413                 ret += si->spaces[i].used_bytes;
414         return ret;
415 }
416
417 static int print_one_fs(struct btrfs_ioctl_fs_info_args *fs_info,
418                 struct btrfs_ioctl_dev_info_args *dev_info,
419                 struct btrfs_ioctl_space_args *space_info,
420                 char *label, char *path)
421 {
422         int i;
423         int fd;
424         int missing = 0;
425         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
426         struct btrfs_ioctl_dev_info_args *tmp_dev_info;
427         int ret;
428
429         ret = add_seen_fsid(fs_info->fsid);
430         if (ret == -EEXIST)
431                 return 0;
432         else if (ret)
433                 return ret;
434
435         uuid_unparse(fs_info->fsid, uuidbuf);
436         if (label && strlen(label))
437                 printf("Label: '%s' ", label);
438         else
439                 printf("Label: none ");
440
441         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
442                         fs_info->num_devices,
443                         pretty_size(calc_used_bytes(space_info)));
444
445         for (i = 0; i < fs_info->num_devices; i++) {
446                 tmp_dev_info = (struct btrfs_ioctl_dev_info_args *)&dev_info[i];
447
448                 /* Add check for missing devices even mounted */
449                 fd = open((char *)tmp_dev_info->path, O_RDONLY);
450                 if (fd < 0) {
451                         missing = 1;
452                         continue;
453                 }
454                 close(fd);
455                 printf("\tdevid %4llu size %s used %s path %s\n",
456                         tmp_dev_info->devid,
457                         pretty_size(tmp_dev_info->total_bytes),
458                         pretty_size(tmp_dev_info->bytes_used),
459                         tmp_dev_info->path);
460         }
461
462         if (missing)
463                 printf("\t*** Some devices missing\n");
464         printf("\n");
465         return 0;
466 }
467
468 /* This function checks if the given input parameter is
469  * an uuid or a path
470  * return -1: some error in the given input
471  * return 0: unknow input
472  * return 1: given input is uuid
473  * return 2: given input is path
474  */
475 static int check_arg_type(char *input)
476 {
477         uuid_t  out;
478         char path[PATH_MAX];
479
480         if (!input)
481                 return -EINVAL;
482
483         if (realpath(input, path)) {
484                 if (is_block_device(path) == 1)
485                         return BTRFS_ARG_BLKDEV;
486
487                 if (is_mount_point(path) == 1)
488                         return BTRFS_ARG_MNTPOINT;
489
490                 return BTRFS_ARG_UNKNOWN;
491         }
492
493         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
494                 !uuid_parse(input, out))
495                 return BTRFS_ARG_UUID;
496
497         return BTRFS_ARG_UNKNOWN;
498 }
499
500 static int btrfs_scan_kernel(void *search)
501 {
502         int ret = 0, fd;
503         int found = 0;
504         FILE *f;
505         struct mntent *mnt;
506         struct btrfs_ioctl_fs_info_args fs_info_arg;
507         struct btrfs_ioctl_dev_info_args *dev_info_arg = NULL;
508         struct btrfs_ioctl_space_args *space_info_arg = NULL;
509         char label[BTRFS_LABEL_SIZE];
510
511         f = setmntent("/proc/self/mounts", "r");
512         if (f == NULL)
513                 return 1;
514
515         memset(label, 0, sizeof(label));
516         while ((mnt = getmntent(f)) != NULL) {
517                 if (strcmp(mnt->mnt_type, "btrfs"))
518                         continue;
519                 ret = get_fs_info(mnt->mnt_dir, &fs_info_arg,
520                                 &dev_info_arg);
521                 if (ret)
522                         goto out;
523
524                 if (get_label_mounted(mnt->mnt_dir, label)) {
525                         kfree(dev_info_arg);
526                         goto out;
527                 }
528                 if (search && !match_search_item_kernel(fs_info_arg.fsid,
529                                         mnt->mnt_dir, label, search)) {
530                         kfree(dev_info_arg);
531                         continue;
532                 }
533
534                 fd = open(mnt->mnt_dir, O_RDONLY);
535                 if ((fd != -1) && !get_df(fd, &space_info_arg)) {
536                         print_one_fs(&fs_info_arg, dev_info_arg,
537                                         space_info_arg, label, mnt->mnt_dir);
538                         kfree(space_info_arg);
539                         memset(label, 0, sizeof(label));
540                         found = 1;
541                 }
542                 if (fd != -1)
543                         close(fd);
544                 kfree(dev_info_arg);
545         }
546
547 out:
548         endmntent(f);
549         return !found;
550 }
551
552 static int dev_to_fsid(char *dev, __u8 *fsid)
553 {
554         struct btrfs_super_block *disk_super;
555         char *buf;
556         int ret;
557         int fd;
558
559         buf = malloc(4096);
560         if (!buf)
561                 return -ENOMEM;
562
563         fd = open(dev, O_RDONLY);
564         if (fd < 0) {
565                 ret = -errno;
566                 free(buf);
567                 return ret;
568         }
569
570         disk_super = (struct btrfs_super_block *)buf;
571         ret = btrfs_read_dev_super(fd, disk_super,
572                                    BTRFS_SUPER_INFO_OFFSET, 0);
573         if (ret)
574                 goto out;
575
576         memcpy(fsid, disk_super->fsid, BTRFS_FSID_SIZE);
577         ret = 0;
578
579 out:
580         close(fd);
581         free(buf);
582         return ret;
583 }
584
585 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
586 {
587         struct btrfs_fs_devices *cur_seed, *next_seed;
588         struct btrfs_device *device;
589
590         while (!list_empty(&fs_devices->devices)) {
591                 device = list_entry(fs_devices->devices.next,
592                                         struct btrfs_device, dev_list);
593                 list_del(&device->dev_list);
594
595                 free(device->name);
596                 free(device->label);
597                 free(device);
598         }
599
600         /* free seed fs chain */
601         cur_seed = fs_devices->seed;
602         fs_devices->seed = NULL;
603         while (cur_seed) {
604                 next_seed = cur_seed->seed;
605                 free(cur_seed);
606
607                 cur_seed = next_seed;
608         }
609
610         list_del(&fs_devices->list);
611         free(fs_devices);
612 }
613
614 static int copy_device(struct btrfs_device *dst,
615                        struct btrfs_device *src)
616 {
617         dst->devid = src->devid;
618         memcpy(dst->uuid, src->uuid, BTRFS_UUID_SIZE);
619         if (src->name == NULL)
620                 dst->name = NULL;
621         else {
622                 dst->name = strdup(src->name);
623                 if (!dst->name)
624                         return -ENOMEM;
625         }
626         if (src->label == NULL)
627                 dst->label = NULL;
628         else {
629                 dst->label = strdup(src->label);
630                 if (!dst->label) {
631                         free(dst->name);
632                         return -ENOMEM;
633                 }
634         }
635         dst->total_devs = src->total_devs;
636         dst->super_bytes_used = src->super_bytes_used;
637         dst->total_bytes = src->total_bytes;
638         dst->bytes_used = src->bytes_used;
639         dst->generation = src->generation;
640
641         return 0;
642 }
643
644 static int copy_fs_devices(struct btrfs_fs_devices *dst,
645                            struct btrfs_fs_devices *src)
646 {
647         struct btrfs_device *cur_dev, *dev_copy;
648         int ret = 0;
649
650         memcpy(dst->fsid, src->fsid, BTRFS_FSID_SIZE);
651         INIT_LIST_HEAD(&dst->devices);
652         dst->seed = NULL;
653
654         list_for_each_entry(cur_dev, &src->devices, dev_list) {
655                 dev_copy = malloc(sizeof(*dev_copy));
656                 if (!dev_copy) {
657                         ret = -ENOMEM;
658                         break;
659                 }
660
661                 ret = copy_device(dev_copy, cur_dev);
662                 if (ret) {
663                         free(dev_copy);
664                         break;
665                 }
666
667                 list_add(&dev_copy->dev_list, &dst->devices);
668                 dev_copy->fs_devices = dst;
669         }
670
671         return ret;
672 }
673
674 static int find_and_copy_seed(struct btrfs_fs_devices *seed,
675                               struct btrfs_fs_devices *copy,
676                               struct list_head *fs_uuids) {
677         struct btrfs_fs_devices *cur_fs;
678
679         list_for_each_entry(cur_fs, fs_uuids, list)
680                 if (!memcmp(seed->fsid, cur_fs->fsid, BTRFS_FSID_SIZE))
681                         return copy_fs_devices(copy, cur_fs);
682
683         return 1;
684 }
685
686 static int map_seed_devices(struct list_head *all_uuids,
687                             char *search, int *found)
688 {
689         struct btrfs_fs_devices *cur_fs, *cur_seed;
690         struct btrfs_fs_devices *fs_copy, *seed_copy;
691         struct btrfs_fs_devices *opened_fs;
692         struct btrfs_device *device;
693         struct btrfs_fs_info *fs_info;
694         struct list_head *fs_uuids;
695         int ret = 0;
696
697         fs_uuids = btrfs_scanned_uuids();
698
699         /*
700          * The fs_uuids list is global, and open_ctree_* will
701          * modify it, make a private copy here
702          */
703         list_for_each_entry(cur_fs, fs_uuids, list) {
704                 /* don't bother handle all fs, if search target specified */
705                 if (search) {
706                         if (uuid_search(cur_fs, search) == 0)
707                                 continue;
708                         *found = 1;
709                 }
710
711                 fs_copy = malloc(sizeof(*fs_copy));
712                 if (!fs_copy) {
713                         ret = -ENOMEM;
714                         goto out;
715                 }
716
717                 ret = copy_fs_devices(fs_copy, cur_fs);
718                 if (ret) {
719                         free(fs_copy);
720                         goto out;
721                 }
722
723                 list_add(&fs_copy->list, all_uuids);
724         }
725
726         list_for_each_entry(cur_fs, all_uuids, list) {
727                 device = list_first_entry(&cur_fs->devices,
728                                                 struct btrfs_device, dev_list);
729                 if (!device)
730                         continue;
731                 /*
732                  * open_ctree_* detects seed/sprout mapping
733                  */
734                 fs_info = open_ctree_fs_info(device->name, 0, 0,
735                                                 OPEN_CTREE_PARTIAL);
736                 if (!fs_info)
737                         continue;
738
739                 /*
740                  * copy the seed chain under the opened fs
741                  */
742                 opened_fs = fs_info->fs_devices;
743                 cur_seed = cur_fs;
744                 while (opened_fs->seed) {
745                         seed_copy = malloc(sizeof(*seed_copy));
746                         if (!seed_copy) {
747                                 ret = -ENOMEM;
748                                 goto fail_out;
749                         }
750                         ret = find_and_copy_seed(opened_fs->seed, seed_copy,
751                                                  fs_uuids);
752                         if (ret) {
753                                 free(seed_copy);
754                                 goto fail_out;
755                         }
756
757                         cur_seed->seed = seed_copy;
758
759                         opened_fs = opened_fs->seed;
760                         cur_seed = cur_seed->seed;
761                 }
762
763                 close_ctree(fs_info->chunk_root);
764         }
765
766 out:
767         return ret;
768 fail_out:
769         close_ctree(fs_info->chunk_root);
770         goto out;
771 }
772
773 static const char * const cmd_show_usage[] = {
774         "btrfs filesystem show [options] [<path>|<uuid>|<device>|label]",
775         "Show the structure of a filesystem",
776         "-d|--all-devices   show only disks under /dev containing btrfs filesystem",
777         "-m|--mounted       show only mounted btrfs",
778         "If no argument is given, structure of all present filesystems is shown.",
779         NULL
780 };
781
782 static int cmd_show(int argc, char **argv)
783 {
784         LIST_HEAD(all_uuids);
785         struct btrfs_fs_devices *fs_devices;
786         char *search = NULL;
787         int ret;
788         /* default, search both kernel and udev */
789         int where = -1;
790         int type = 0;
791         char mp[BTRFS_PATH_NAME_MAX + 1];
792         char path[PATH_MAX];
793         __u8 fsid[BTRFS_FSID_SIZE];
794         char uuid_buf[BTRFS_UUID_UNPARSED_SIZE];
795         int found = 0;
796
797         while (1) {
798                 int long_index;
799                 static struct option long_options[] = {
800                         { "all-devices", no_argument, NULL, 'd'},
801                         { "mounted", no_argument, NULL, 'm'},
802                         { NULL, no_argument, NULL, 0 },
803                 };
804                 int c = getopt_long(argc, argv, "dm", long_options,
805                                         &long_index);
806                 if (c < 0)
807                         break;
808                 switch (c) {
809                 case 'd':
810                         where = BTRFS_SCAN_LBLKID;
811                         break;
812                 case 'm':
813                         where = BTRFS_SCAN_MOUNTED;
814                         break;
815                 default:
816                         usage(cmd_show_usage);
817                 }
818         }
819
820         if (check_argc_max(argc, optind + 1))
821                 usage(cmd_show_usage);
822
823         if (argc > optind) {
824                 search = argv[optind];
825                 if (strlen(search) == 0)
826                         usage(cmd_show_usage);
827                 type = check_arg_type(search);
828                 /*
829                  * needs spl handling if input arg is block dev
830                  * And if input arg is mount-point just print it
831                  * right away
832                  */
833                 if (type == BTRFS_ARG_BLKDEV) {
834                         if (where == BTRFS_SCAN_LBLKID) {
835                                 /* we need to do this because
836                                  * legacy BTRFS_SCAN_DEV
837                                  * provides /dev/dm-x paths
838                                  */
839                                 if (realpath(search, path))
840                                         search = path;
841                         } else {
842                                 ret = get_btrfs_mount(search,
843                                                 mp, sizeof(mp));
844                                 if (!ret) {
845                                         /* given block dev is mounted*/
846                                         search = mp;
847                                         type = BTRFS_ARG_MNTPOINT;
848                                 } else {
849                                         ret = dev_to_fsid(search, fsid);
850                                         if (ret) {
851                                                 fprintf(stderr,
852                                                         "ERROR: No btrfs on %s\n",
853                                                         search);
854                                                 return 1;
855                                         }
856                                         uuid_unparse(fsid, uuid_buf);
857                                         search = uuid_buf;
858                                         type = BTRFS_ARG_UUID;
859                                         goto devs_only;
860                                 }
861                         }
862                 }
863         }
864
865         if (where == BTRFS_SCAN_LBLKID)
866                 goto devs_only;
867
868         /* show mounted btrfs */
869         ret = btrfs_scan_kernel(search);
870         if (search && !ret) {
871                 /* since search is found we are done */
872                 goto out;
873         }
874
875         /* shows mounted only */
876         if (where == BTRFS_SCAN_MOUNTED)
877                 goto out;
878
879 devs_only:
880         ret = btrfs_scan_lblkid(!BTRFS_UPDATE_KERNEL);
881
882         if (ret) {
883                 fprintf(stderr, "ERROR: %d while scanning\n", ret);
884                 return 1;
885         }
886
887         /*
888          * scan_for_btrfs() don't build seed/sprout mapping,
889          * do mapping build for each scanned fs here
890          */
891         ret = map_seed_devices(&all_uuids, search, &found);
892         if (ret) {
893                 fprintf(stderr,
894                         "ERROR: %d while mapping seed devices\n", ret);
895                 return 1;
896         }
897
898         list_for_each_entry(fs_devices, &all_uuids, list)
899                 print_one_uuid(fs_devices);
900
901         if (search && !found)
902                 ret = 1;
903
904         while (!list_empty(&all_uuids)) {
905                 fs_devices = list_entry(all_uuids.next,
906                                         struct btrfs_fs_devices, list);
907                 free_fs_devices(fs_devices);
908         }
909 out:
910         printf("%s\n", BTRFS_BUILD_VERSION);
911         free_seen_fsid();
912         return ret;
913 }
914
915 static const char * const cmd_sync_usage[] = {
916         "btrfs filesystem sync <path>",
917         "Force a sync on a filesystem",
918         NULL
919 };
920
921 static int cmd_sync(int argc, char **argv)
922 {
923         int     fd, res, e;
924         char    *path;
925         DIR     *dirstream = NULL;
926
927         if (check_argc_exact(argc, 2))
928                 usage(cmd_sync_usage);
929
930         path = argv[1];
931
932         fd = open_file_or_dir(path, &dirstream);
933         if (fd < 0) {
934                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
935                 return 1;
936         }
937
938         printf("FSSync '%s'\n", path);
939         res = ioctl(fd, BTRFS_IOC_SYNC);
940         e = errno;
941         close_file_or_dir(fd, dirstream);
942         if( res < 0 ){
943                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
944                         path, strerror(e));
945                 return 1;
946         }
947
948         return 0;
949 }
950
951 static int parse_compress_type(char *s)
952 {
953         if (strcmp(optarg, "zlib") == 0)
954                 return BTRFS_COMPRESS_ZLIB;
955         else if (strcmp(optarg, "lzo") == 0)
956                 return BTRFS_COMPRESS_LZO;
957         else {
958                 fprintf(stderr, "Unknown compress type %s\n", s);
959                 exit(1);
960         };
961 }
962
963 static const char * const cmd_defrag_usage[] = {
964         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
965         "Defragment a file or a directory",
966         "",
967         "-v             be verbose",
968         "-r             defragment files recursively",
969         "-c[zlib,lzo]   compress the file while defragmenting",
970         "-f             flush data to disk immediately after defragmenting",
971         "-s start       defragment only from byte onward",
972         "-l len         defragment only up to len bytes",
973         "-t size        minimal size of file to be considered for defragmenting",
974         NULL
975 };
976
977 static int do_defrag(int fd, int fancy_ioctl,
978                 struct btrfs_ioctl_defrag_range_args *range)
979 {
980         int ret;
981
982         if (!fancy_ioctl)
983                 ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
984         else
985                 ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, range);
986
987         return ret;
988 }
989
990 static int defrag_global_fancy_ioctl;
991 static struct btrfs_ioctl_defrag_range_args defrag_global_range;
992 static int defrag_global_verbose;
993 static int defrag_global_errors;
994 static int defrag_callback(const char *fpath, const struct stat *sb,
995                 int typeflag, struct FTW *ftwbuf)
996 {
997         int ret = 0;
998         int e = 0;
999         int fd = 0;
1000
1001         if ((typeflag == FTW_F) && S_ISREG(sb->st_mode)) {
1002                 if (defrag_global_verbose)
1003                         printf("%s\n", fpath);
1004                 fd = open(fpath, O_RDWR);
1005                 e = errno;
1006                 if (fd < 0)
1007                         goto error;
1008                 ret = do_defrag(fd, defrag_global_fancy_ioctl, &defrag_global_range);
1009                 e = errno;
1010                 close(fd);
1011                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1012                         fprintf(stderr, "ERROR: defrag range ioctl not "
1013                                 "supported in this kernel, please try "
1014                                 "without any options.\n");
1015                         defrag_global_errors++;
1016                         return ENOTTY;
1017                 }
1018                 if (ret)
1019                         goto error;
1020         }
1021         return 0;
1022
1023 error:
1024         fprintf(stderr, "ERROR: defrag failed on %s - %s\n", fpath, strerror(e));
1025         defrag_global_errors++;
1026         return 0;
1027 }
1028
1029 static int cmd_defrag(int argc, char **argv)
1030 {
1031         int fd;
1032         int flush = 0;
1033         u64 start = 0;
1034         u64 len = (u64)-1;
1035         u32 thresh = 0;
1036         int i;
1037         int recursive = 0;
1038         int ret = 0;
1039         struct btrfs_ioctl_defrag_range_args range;
1040         int e = 0;
1041         int compress_type = BTRFS_COMPRESS_NONE;
1042         DIR *dirstream;
1043
1044         defrag_global_errors = 0;
1045         defrag_global_verbose = 0;
1046         defrag_global_errors = 0;
1047         defrag_global_fancy_ioctl = 0;
1048         optind = 1;
1049         while(1) {
1050                 int c = getopt(argc, argv, "vrc::fs:l:t:");
1051                 if (c < 0)
1052                         break;
1053
1054                 switch(c) {
1055                 case 'c':
1056                         compress_type = BTRFS_COMPRESS_ZLIB;
1057                         if (optarg)
1058                                 compress_type = parse_compress_type(optarg);
1059                         defrag_global_fancy_ioctl = 1;
1060                         break;
1061                 case 'f':
1062                         flush = 1;
1063                         defrag_global_fancy_ioctl = 1;
1064                         break;
1065                 case 'v':
1066                         defrag_global_verbose = 1;
1067                         break;
1068                 case 's':
1069                         start = parse_size(optarg);
1070                         defrag_global_fancy_ioctl = 1;
1071                         break;
1072                 case 'l':
1073                         len = parse_size(optarg);
1074                         defrag_global_fancy_ioctl = 1;
1075                         break;
1076                 case 't':
1077                         thresh = parse_size(optarg);
1078                         defrag_global_fancy_ioctl = 1;
1079                         break;
1080                 case 'r':
1081                         recursive = 1;
1082                         break;
1083                 default:
1084                         usage(cmd_defrag_usage);
1085                 }
1086         }
1087
1088         if (check_argc_min(argc - optind, 1))
1089                 usage(cmd_defrag_usage);
1090
1091         memset(&defrag_global_range, 0, sizeof(range));
1092         defrag_global_range.start = start;
1093         defrag_global_range.len = len;
1094         defrag_global_range.extent_thresh = thresh;
1095         if (compress_type) {
1096                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
1097                 defrag_global_range.compress_type = compress_type;
1098         }
1099         if (flush)
1100                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
1101
1102         for (i = optind; i < argc; i++) {
1103                 struct stat st;
1104
1105                 dirstream = NULL;
1106                 fd = open_file_or_dir(argv[i], &dirstream);
1107                 if (fd < 0) {
1108                         fprintf(stderr, "ERROR: failed to open %s - %s\n", argv[i],
1109                                         strerror(errno));
1110                         defrag_global_errors++;
1111                         close_file_or_dir(fd, dirstream);
1112                         continue;
1113                 }
1114                 if (fstat(fd, &st)) {
1115                         fprintf(stderr, "ERROR: failed to stat %s - %s\n",
1116                                         argv[i], strerror(errno));
1117                         defrag_global_errors++;
1118                         close_file_or_dir(fd, dirstream);
1119                         continue;
1120                 }
1121                 if (!(S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))) {
1122                         fprintf(stderr,
1123                             "ERROR: %s is not a directory or a regular file\n",
1124                             argv[i]);
1125                         defrag_global_errors++;
1126                         close_file_or_dir(fd, dirstream);
1127                         continue;
1128                 }
1129                 if (recursive) {
1130                         if (S_ISDIR(st.st_mode)) {
1131                                 ret = nftw(argv[i], defrag_callback, 10,
1132                                                 FTW_MOUNT | FTW_PHYS);
1133                                 if (ret == ENOTTY)
1134                                         exit(1);
1135                                 /* errors are handled in the callback */
1136                                 ret = 0;
1137                         } else {
1138                                 if (defrag_global_verbose)
1139                                         printf("%s\n", argv[i]);
1140                                 ret = do_defrag(fd, defrag_global_fancy_ioctl,
1141                                                 &defrag_global_range);
1142                                 e = errno;
1143                         }
1144                 } else {
1145                         if (defrag_global_verbose)
1146                                 printf("%s\n", argv[i]);
1147                         ret = do_defrag(fd, defrag_global_fancy_ioctl,
1148                                         &defrag_global_range);
1149                         e = errno;
1150                 }
1151                 close_file_or_dir(fd, dirstream);
1152                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1153                         fprintf(stderr, "ERROR: defrag range ioctl not "
1154                                 "supported in this kernel, please try "
1155                                 "without any options.\n");
1156                         defrag_global_errors++;
1157                         break;
1158                 }
1159                 if (ret) {
1160                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
1161                                 argv[i], strerror(e));
1162                         defrag_global_errors++;
1163                 }
1164         }
1165         if (defrag_global_verbose)
1166                 printf("%s\n", BTRFS_BUILD_VERSION);
1167         if (defrag_global_errors)
1168                 fprintf(stderr, "total %d failures\n", defrag_global_errors);
1169
1170         return !!defrag_global_errors;
1171 }
1172
1173 static const char * const cmd_resize_usage[] = {
1174         "btrfs filesystem resize [devid:][+/-]<newsize>[kKmMgGtTpPeE]|[devid:]max <path>",
1175         "Resize a filesystem",
1176         "If 'max' is passed, the filesystem will occupy all available space",
1177         "on the device 'devid'.",
1178         "[kK] means KiB, which denotes 1KiB = 1024B, 1MiB = 1024KiB, etc.",
1179         NULL
1180 };
1181
1182 static int cmd_resize(int argc, char **argv)
1183 {
1184         struct btrfs_ioctl_vol_args     args;
1185         int     fd, res, len, e;
1186         char    *amount, *path;
1187         DIR     *dirstream = NULL;
1188
1189         if (check_argc_exact(argc, 3))
1190                 usage(cmd_resize_usage);
1191
1192         amount = argv[1];
1193         path = argv[2];
1194
1195         len = strlen(amount);
1196         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
1197                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
1198                         amount);
1199                 return 1;
1200         }
1201
1202         fd = open_file_or_dir(path, &dirstream);
1203         if (fd < 0) {
1204                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
1205                 return 1;
1206         }
1207
1208         printf("Resize '%s' of '%s'\n", path, amount);
1209         strncpy_null(args.name, amount);
1210         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
1211         e = errno;
1212         close_file_or_dir(fd, dirstream);
1213         if( res < 0 ){
1214                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
1215                         path, strerror(e));
1216                 return 1;
1217         }
1218         return 0;
1219 }
1220
1221 static const char * const cmd_label_usage[] = {
1222         "btrfs filesystem label [<device>|<mount_point>] [<newlabel>]",
1223         "Get or change the label of a filesystem",
1224         "With one argument, get the label of filesystem on <device>.",
1225         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
1226         NULL
1227 };
1228
1229 static int cmd_label(int argc, char **argv)
1230 {
1231         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
1232                 usage(cmd_label_usage);
1233
1234         if (argc > 2) {
1235                 return set_label(argv[1], argv[2]);
1236         } else {
1237                 char label[BTRFS_LABEL_SIZE];
1238                 int ret;
1239
1240                 ret = get_label(argv[1], label);
1241                 if (!ret)
1242                         fprintf(stdout, "%s\n", label);
1243
1244                 return ret;
1245         }
1246 }
1247
1248 const struct cmd_group filesystem_cmd_group = {
1249         filesystem_cmd_group_usage, NULL, {
1250                 { "df", cmd_df, cmd_df_usage, NULL, 0 },
1251                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
1252                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
1253                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
1254                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
1255                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
1256                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
1257                 NULL_CMD_STRUCT
1258         }
1259 };
1260
1261 int cmd_filesystem(int argc, char **argv)
1262 {
1263         return handle_command_group(&filesystem_cmd_group, argc, argv);
1264 }