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