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