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