btrfs-progs: add command group info strings
[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)
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(device->total_bytes),
397                        pretty_size(device->bytes_used), device->name);
398
399                 (*devs_found)++;
400         }
401 }
402
403 static void print_one_uuid(struct btrfs_fs_devices *fs_devices)
404 {
405         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
406         struct btrfs_device *device;
407         u64 devs_found = 0;
408         u64 total;
409
410         if (add_seen_fsid(fs_devices->fsid))
411                 return;
412
413         uuid_unparse(fs_devices->fsid, uuidbuf);
414         device = list_entry(fs_devices->devices.next, struct btrfs_device,
415                             dev_list);
416         if (device->label && device->label[0])
417                 printf("Label: '%s' ", device->label);
418         else
419                 printf("Label: none ");
420
421         total = device->total_devs;
422         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
423                (unsigned long long)total,
424                pretty_size(device->super_bytes_used));
425
426         print_devices(fs_devices, &devs_found);
427
428         if (devs_found < total) {
429                 printf("\t*** Some devices missing\n");
430         }
431         printf("\n");
432 }
433
434 /* adds up all the used spaces as reported by the space info ioctl
435  */
436 static u64 calc_used_bytes(struct btrfs_ioctl_space_args *si)
437 {
438         u64 ret = 0;
439         int i;
440         for (i = 0; i < si->total_spaces; i++)
441                 ret += si->spaces[i].used_bytes;
442         return ret;
443 }
444
445 static int print_one_fs(struct btrfs_ioctl_fs_info_args *fs_info,
446                 struct btrfs_ioctl_dev_info_args *dev_info,
447                 struct btrfs_ioctl_space_args *space_info,
448                 char *label, char *path)
449 {
450         int i;
451         int fd;
452         int missing = 0;
453         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
454         struct btrfs_ioctl_dev_info_args *tmp_dev_info;
455         int ret;
456
457         ret = add_seen_fsid(fs_info->fsid);
458         if (ret == -EEXIST)
459                 return 0;
460         else if (ret)
461                 return ret;
462
463         uuid_unparse(fs_info->fsid, uuidbuf);
464         if (label && strlen(label))
465                 printf("Label: '%s' ", label);
466         else
467                 printf("Label: none ");
468
469         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
470                         fs_info->num_devices,
471                         pretty_size(calc_used_bytes(space_info)));
472
473         for (i = 0; i < fs_info->num_devices; i++) {
474                 char *canonical_path;
475
476                 tmp_dev_info = (struct btrfs_ioctl_dev_info_args *)&dev_info[i];
477
478                 /* Add check for missing devices even mounted */
479                 fd = open((char *)tmp_dev_info->path, O_RDONLY);
480                 if (fd < 0) {
481                         missing = 1;
482                         continue;
483                 }
484                 close(fd);
485                 canonical_path = canonicalize_path((char *)tmp_dev_info->path);
486                 printf("\tdevid %4llu size %s used %s path %s\n",
487                         tmp_dev_info->devid,
488                         pretty_size(tmp_dev_info->total_bytes),
489                         pretty_size(tmp_dev_info->bytes_used),
490                         canonical_path);
491
492                 free(canonical_path);
493         }
494
495         if (missing)
496                 printf("\t*** Some devices missing\n");
497         printf("\n");
498         return 0;
499 }
500
501 static int btrfs_scan_kernel(void *search)
502 {
503         int ret = 0, fd;
504         int found = 0;
505         FILE *f;
506         struct mntent *mnt;
507         struct btrfs_ioctl_fs_info_args fs_info_arg;
508         struct btrfs_ioctl_dev_info_args *dev_info_arg = NULL;
509         struct btrfs_ioctl_space_args *space_info_arg = NULL;
510         char label[BTRFS_LABEL_SIZE];
511
512         f = setmntent("/proc/self/mounts", "r");
513         if (f == NULL)
514                 return 1;
515
516         memset(label, 0, sizeof(label));
517         while ((mnt = getmntent(f)) != NULL) {
518                 if (strcmp(mnt->mnt_type, "btrfs"))
519                         continue;
520                 ret = get_fs_info(mnt->mnt_dir, &fs_info_arg,
521                                 &dev_info_arg);
522                 if (ret) {
523                         kfree(dev_info_arg);
524                         goto out;
525                 }
526
527                 if (get_label_mounted(mnt->mnt_dir, label)) {
528                         kfree(dev_info_arg);
529                         goto out;
530                 }
531                 if (search && !match_search_item_kernel(fs_info_arg.fsid,
532                                         mnt->mnt_dir, label, search)) {
533                         kfree(dev_info_arg);
534                         continue;
535                 }
536
537                 fd = open(mnt->mnt_dir, O_RDONLY);
538                 if ((fd != -1) && !get_df(fd, &space_info_arg)) {
539                         print_one_fs(&fs_info_arg, dev_info_arg,
540                                         space_info_arg, label, mnt->mnt_dir);
541                         kfree(space_info_arg);
542                         memset(label, 0, sizeof(label));
543                         found = 1;
544                 }
545                 if (fd != -1)
546                         close(fd);
547                 kfree(dev_info_arg);
548         }
549
550 out:
551         endmntent(f);
552         return !found;
553 }
554
555 static int dev_to_fsid(char *dev, __u8 *fsid)
556 {
557         struct btrfs_super_block *disk_super;
558         char *buf;
559         int ret;
560         int fd;
561
562         buf = malloc(4096);
563         if (!buf)
564                 return -ENOMEM;
565
566         fd = open(dev, O_RDONLY);
567         if (fd < 0) {
568                 ret = -errno;
569                 free(buf);
570                 return ret;
571         }
572
573         disk_super = (struct btrfs_super_block *)buf;
574         ret = btrfs_read_dev_super(fd, disk_super,
575                                    BTRFS_SUPER_INFO_OFFSET, 0);
576         if (ret)
577                 goto out;
578
579         memcpy(fsid, disk_super->fsid, BTRFS_FSID_SIZE);
580         ret = 0;
581
582 out:
583         close(fd);
584         free(buf);
585         return ret;
586 }
587
588 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
589 {
590         struct btrfs_fs_devices *cur_seed, *next_seed;
591         struct btrfs_device *device;
592
593         while (!list_empty(&fs_devices->devices)) {
594                 device = list_entry(fs_devices->devices.next,
595                                         struct btrfs_device, dev_list);
596                 list_del(&device->dev_list);
597
598                 free(device->name);
599                 free(device->label);
600                 free(device);
601         }
602
603         /* free seed fs chain */
604         cur_seed = fs_devices->seed;
605         fs_devices->seed = NULL;
606         while (cur_seed) {
607                 next_seed = cur_seed->seed;
608                 free(cur_seed);
609
610                 cur_seed = next_seed;
611         }
612
613         list_del(&fs_devices->list);
614         free(fs_devices);
615 }
616
617 static int copy_device(struct btrfs_device *dst,
618                        struct btrfs_device *src)
619 {
620         dst->devid = src->devid;
621         memcpy(dst->uuid, src->uuid, BTRFS_UUID_SIZE);
622         if (src->name == NULL)
623                 dst->name = NULL;
624         else {
625                 dst->name = strdup(src->name);
626                 if (!dst->name)
627                         return -ENOMEM;
628         }
629         if (src->label == NULL)
630                 dst->label = NULL;
631         else {
632                 dst->label = strdup(src->label);
633                 if (!dst->label) {
634                         free(dst->name);
635                         return -ENOMEM;
636                 }
637         }
638         dst->total_devs = src->total_devs;
639         dst->super_bytes_used = src->super_bytes_used;
640         dst->total_bytes = src->total_bytes;
641         dst->bytes_used = src->bytes_used;
642         dst->generation = src->generation;
643
644         return 0;
645 }
646
647 static int copy_fs_devices(struct btrfs_fs_devices *dst,
648                            struct btrfs_fs_devices *src)
649 {
650         struct btrfs_device *cur_dev, *dev_copy;
651         int ret = 0;
652
653         memcpy(dst->fsid, src->fsid, BTRFS_FSID_SIZE);
654         INIT_LIST_HEAD(&dst->devices);
655         dst->seed = NULL;
656
657         list_for_each_entry(cur_dev, &src->devices, dev_list) {
658                 dev_copy = malloc(sizeof(*dev_copy));
659                 if (!dev_copy) {
660                         ret = -ENOMEM;
661                         break;
662                 }
663
664                 ret = copy_device(dev_copy, cur_dev);
665                 if (ret) {
666                         free(dev_copy);
667                         break;
668                 }
669
670                 list_add(&dev_copy->dev_list, &dst->devices);
671                 dev_copy->fs_devices = dst;
672         }
673
674         return ret;
675 }
676
677 static int find_and_copy_seed(struct btrfs_fs_devices *seed,
678                               struct btrfs_fs_devices *copy,
679                               struct list_head *fs_uuids) {
680         struct btrfs_fs_devices *cur_fs;
681
682         list_for_each_entry(cur_fs, fs_uuids, list)
683                 if (!memcmp(seed->fsid, cur_fs->fsid, BTRFS_FSID_SIZE))
684                         return copy_fs_devices(copy, cur_fs);
685
686         return 1;
687 }
688
689 static int has_seed_devices(struct btrfs_fs_devices *fs_devices)
690 {
691         struct btrfs_device *device;
692         int dev_cnt_total, dev_cnt = 0;
693
694         device = list_first_entry(&fs_devices->devices, struct btrfs_device,
695                                   dev_list);
696
697         dev_cnt_total = device->total_devs;
698
699         list_for_each_entry(device, &fs_devices->devices, dev_list)
700                 dev_cnt++;
701
702         return dev_cnt_total != dev_cnt;
703 }
704
705 static int search_umounted_fs_uuids(struct list_head *all_uuids,
706                                     char *search, int *found)
707 {
708         struct btrfs_fs_devices *cur_fs, *fs_copy;
709         struct list_head *fs_uuids;
710         int ret = 0;
711
712         fs_uuids = btrfs_scanned_uuids();
713
714         /*
715          * The fs_uuids list is global, and open_ctree_* will
716          * modify it, make a private copy here
717          */
718         list_for_each_entry(cur_fs, fs_uuids, list) {
719                 /* don't bother handle all fs, if search target specified */
720                 if (search) {
721                         if (uuid_search(cur_fs, search) == 0)
722                                 continue;
723                         if (found)
724                                 *found = 1;
725                 }
726
727                 /* skip all fs already shown as mounted fs */
728                 if (is_seen_fsid(cur_fs->fsid))
729                         continue;
730
731                 fs_copy = malloc(sizeof(*fs_copy));
732                 if (!fs_copy) {
733                         ret = -ENOMEM;
734                         goto out;
735                 }
736
737                 ret = copy_fs_devices(fs_copy, cur_fs);
738                 if (ret) {
739                         free(fs_copy);
740                         goto out;
741                 }
742
743                 list_add(&fs_copy->list, all_uuids);
744         }
745
746 out:
747         return ret;
748 }
749
750 static int map_seed_devices(struct list_head *all_uuids)
751 {
752         struct btrfs_fs_devices *cur_fs, *cur_seed;
753         struct btrfs_fs_devices *seed_copy;
754         struct btrfs_fs_devices *opened_fs;
755         struct btrfs_device *device;
756         struct btrfs_fs_info *fs_info;
757         struct list_head *fs_uuids;
758         int ret = 0;
759
760         fs_uuids = btrfs_scanned_uuids();
761
762         list_for_each_entry(cur_fs, all_uuids, list) {
763                 device = list_first_entry(&cur_fs->devices,
764                                                 struct btrfs_device, dev_list);
765                 if (!device)
766                         continue;
767
768                 /* skip fs without seeds */
769                 if (!has_seed_devices(cur_fs))
770                         continue;
771
772                 /*
773                  * open_ctree_* detects seed/sprout mapping
774                  */
775                 fs_info = open_ctree_fs_info(device->name, 0, 0,
776                                                 OPEN_CTREE_PARTIAL);
777                 if (!fs_info)
778                         continue;
779
780                 /*
781                  * copy the seed chain under the opened fs
782                  */
783                 opened_fs = fs_info->fs_devices;
784                 cur_seed = cur_fs;
785                 while (opened_fs->seed) {
786                         seed_copy = malloc(sizeof(*seed_copy));
787                         if (!seed_copy) {
788                                 ret = -ENOMEM;
789                                 goto fail_out;
790                         }
791                         ret = find_and_copy_seed(opened_fs->seed, seed_copy,
792                                                  fs_uuids);
793                         if (ret) {
794                                 free(seed_copy);
795                                 goto fail_out;
796                         }
797
798                         cur_seed->seed = seed_copy;
799
800                         opened_fs = opened_fs->seed;
801                         cur_seed = cur_seed->seed;
802                 }
803
804                 close_ctree(fs_info->chunk_root);
805         }
806
807 out:
808         return ret;
809 fail_out:
810         close_ctree(fs_info->chunk_root);
811         goto out;
812 }
813
814 static const char * const cmd_show_usage[] = {
815         "btrfs filesystem show [options] [<path>|<uuid>|<device>|label]",
816         "Show the structure of a filesystem",
817         "-d|--all-devices   show only disks under /dev containing btrfs filesystem",
818         "-m|--mounted       show only mounted btrfs",
819         "If no argument is given, structure of all present filesystems is shown.",
820         NULL
821 };
822
823 static int cmd_show(int argc, char **argv)
824 {
825         LIST_HEAD(all_uuids);
826         struct btrfs_fs_devices *fs_devices;
827         char *search = NULL;
828         int ret;
829         /* default, search both kernel and udev */
830         int where = -1;
831         int type = 0;
832         char mp[BTRFS_PATH_NAME_MAX + 1];
833         char path[PATH_MAX];
834         __u8 fsid[BTRFS_FSID_SIZE];
835         char uuid_buf[BTRFS_UUID_UNPARSED_SIZE];
836         int found = 0;
837
838         while (1) {
839                 int c;
840                 static const struct option long_options[] = {
841                         { "all-devices", no_argument, NULL, 'd'},
842                         { "mounted", no_argument, NULL, 'm'},
843                         { NULL, 0, NULL, 0 }
844                 };
845
846                 c = getopt_long(argc, argv, "dm", long_options, NULL);
847                 if (c < 0)
848                         break;
849                 switch (c) {
850                 case 'd':
851                         where = BTRFS_SCAN_LBLKID;
852                         break;
853                 case 'm':
854                         where = BTRFS_SCAN_MOUNTED;
855                         break;
856                 default:
857                         usage(cmd_show_usage);
858                 }
859         }
860
861         if (check_argc_max(argc, optind + 1))
862                 usage(cmd_show_usage);
863
864         if (argc > optind) {
865                 search = argv[optind];
866                 if (strlen(search) == 0)
867                         usage(cmd_show_usage);
868                 type = check_arg_type(search);
869
870                 /*
871                  * For search is a device:
872                  *     realpath do /dev/mapper/XX => /dev/dm-X
873                  *     which is required by BTRFS_SCAN_DEV
874                  * For search is a mountpoint:
875                  *     realpath do  /mnt/btrfs/  => /mnt/btrfs
876                  *     which shall be recognized by btrfs_scan_kernel()
877                  */
878                 if (realpath(search, path))
879                         search = path;
880
881                 /*
882                  * Needs special handling if input arg is block dev And if
883                  * input arg is mount-point just print it right away
884                  */
885                 if (type == BTRFS_ARG_BLKDEV && where != BTRFS_SCAN_LBLKID) {
886                         ret = get_btrfs_mount(search, mp, sizeof(mp));
887                         if (!ret) {
888                                 /* given block dev is mounted */
889                                 search = mp;
890                                 type = BTRFS_ARG_MNTPOINT;
891                         } else {
892                                 ret = dev_to_fsid(search, fsid);
893                                 if (ret) {
894                                         fprintf(stderr,
895                                                 "ERROR: No btrfs on %s\n",
896                                                 search);
897                                         return 1;
898                                 }
899                                 uuid_unparse(fsid, uuid_buf);
900                                 search = uuid_buf;
901                                 type = BTRFS_ARG_UUID;
902                                 goto devs_only;
903                         }
904                 }
905         }
906
907         if (where == BTRFS_SCAN_LBLKID)
908                 goto devs_only;
909
910         /* show mounted btrfs */
911         ret = btrfs_scan_kernel(search);
912         if (search && !ret) {
913                 /* since search is found we are done */
914                 goto out;
915         }
916
917         /* shows mounted only */
918         if (where == BTRFS_SCAN_MOUNTED)
919                 goto out;
920
921 devs_only:
922         ret = btrfs_scan_lblkid();
923
924         if (ret) {
925                 fprintf(stderr, "ERROR: %d while scanning\n", ret);
926                 return 1;
927         }
928
929         ret = search_umounted_fs_uuids(&all_uuids, search, &found);
930         if (ret < 0) {
931                 fprintf(stderr,
932                         "ERROR: %d while searching target device\n", ret);
933                 return 1;
934         }
935
936         /*
937          * The seed/sprout mapping are not detected yet,
938          * do mapping build for all umounted fs
939          */
940         ret = map_seed_devices(&all_uuids);
941         if (ret) {
942                 fprintf(stderr,
943                         "ERROR: %d while mapping seed devices\n", ret);
944                 return 1;
945         }
946
947         list_for_each_entry(fs_devices, &all_uuids, list)
948                 print_one_uuid(fs_devices);
949
950         if (search && !found)
951                 ret = 1;
952
953         while (!list_empty(&all_uuids)) {
954                 fs_devices = list_entry(all_uuids.next,
955                                         struct btrfs_fs_devices, list);
956                 free_fs_devices(fs_devices);
957         }
958 out:
959         printf("%s\n", PACKAGE_STRING);
960         free_seen_fsid();
961         return ret;
962 }
963
964 static const char * const cmd_sync_usage[] = {
965         "btrfs filesystem sync <path>",
966         "Force a sync on a filesystem",
967         NULL
968 };
969
970 static int cmd_sync(int argc, char **argv)
971 {
972         int     fd, res, e;
973         char    *path;
974         DIR     *dirstream = NULL;
975
976         if (check_argc_exact(argc, 2))
977                 usage(cmd_sync_usage);
978
979         path = argv[1];
980
981         fd = open_file_or_dir(path, &dirstream);
982         if (fd < 0) {
983                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
984                 return 1;
985         }
986
987         printf("FSSync '%s'\n", path);
988         res = ioctl(fd, BTRFS_IOC_SYNC);
989         e = errno;
990         close_file_or_dir(fd, dirstream);
991         if( res < 0 ){
992                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
993                         path, strerror(e));
994                 return 1;
995         }
996
997         return 0;
998 }
999
1000 static int parse_compress_type(char *s)
1001 {
1002         if (strcmp(optarg, "zlib") == 0)
1003                 return BTRFS_COMPRESS_ZLIB;
1004         else if (strcmp(optarg, "lzo") == 0)
1005                 return BTRFS_COMPRESS_LZO;
1006         else {
1007                 fprintf(stderr, "Unknown compress type %s\n", s);
1008                 exit(1);
1009         };
1010 }
1011
1012 static const char * const cmd_defrag_usage[] = {
1013         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
1014         "Defragment a file or a directory",
1015         "",
1016         "-v             be verbose",
1017         "-r             defragment files recursively",
1018         "-c[zlib,lzo]   compress the file while defragmenting",
1019         "-f             flush data to disk immediately after defragmenting",
1020         "-s start       defragment only from byte onward",
1021         "-l len         defragment only up to len bytes",
1022         "-t size        minimal size of file to be considered for defragmenting",
1023         NULL
1024 };
1025
1026 static int do_defrag(int fd, int fancy_ioctl,
1027                 struct btrfs_ioctl_defrag_range_args *range)
1028 {
1029         int ret;
1030
1031         if (!fancy_ioctl)
1032                 ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
1033         else
1034                 ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, range);
1035
1036         return ret;
1037 }
1038
1039 static int defrag_global_fancy_ioctl;
1040 static struct btrfs_ioctl_defrag_range_args defrag_global_range;
1041 static int defrag_global_verbose;
1042 static int defrag_global_errors;
1043 static int defrag_callback(const char *fpath, const struct stat *sb,
1044                 int typeflag, struct FTW *ftwbuf)
1045 {
1046         int ret = 0;
1047         int e = 0;
1048         int fd = 0;
1049
1050         if ((typeflag == FTW_F) && S_ISREG(sb->st_mode)) {
1051                 if (defrag_global_verbose)
1052                         printf("%s\n", fpath);
1053                 fd = open(fpath, O_RDWR);
1054                 e = errno;
1055                 if (fd < 0)
1056                         goto error;
1057                 ret = do_defrag(fd, defrag_global_fancy_ioctl, &defrag_global_range);
1058                 e = errno;
1059                 close(fd);
1060                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1061                         fprintf(stderr, "ERROR: defrag range ioctl not "
1062                                 "supported in this kernel, please try "
1063                                 "without any options.\n");
1064                         defrag_global_errors++;
1065                         return ENOTTY;
1066                 }
1067                 if (ret)
1068                         goto error;
1069         }
1070         return 0;
1071
1072 error:
1073         fprintf(stderr, "ERROR: defrag failed on %s - %s\n", fpath, strerror(e));
1074         defrag_global_errors++;
1075         return 0;
1076 }
1077
1078 static int cmd_defrag(int argc, char **argv)
1079 {
1080         int fd;
1081         int flush = 0;
1082         u64 start = 0;
1083         u64 len = (u64)-1;
1084         u32 thresh = 0;
1085         int i;
1086         int recursive = 0;
1087         int ret = 0;
1088         struct btrfs_ioctl_defrag_range_args range;
1089         int e = 0;
1090         int compress_type = BTRFS_COMPRESS_NONE;
1091         DIR *dirstream;
1092
1093         defrag_global_errors = 0;
1094         defrag_global_verbose = 0;
1095         defrag_global_errors = 0;
1096         defrag_global_fancy_ioctl = 0;
1097         optind = 1;
1098         while(1) {
1099                 int c = getopt(argc, argv, "vrc::fs:l:t:");
1100                 if (c < 0)
1101                         break;
1102
1103                 switch(c) {
1104                 case 'c':
1105                         compress_type = BTRFS_COMPRESS_ZLIB;
1106                         if (optarg)
1107                                 compress_type = parse_compress_type(optarg);
1108                         defrag_global_fancy_ioctl = 1;
1109                         break;
1110                 case 'f':
1111                         flush = 1;
1112                         defrag_global_fancy_ioctl = 1;
1113                         break;
1114                 case 'v':
1115                         defrag_global_verbose = 1;
1116                         break;
1117                 case 's':
1118                         start = parse_size(optarg);
1119                         defrag_global_fancy_ioctl = 1;
1120                         break;
1121                 case 'l':
1122                         len = parse_size(optarg);
1123                         defrag_global_fancy_ioctl = 1;
1124                         break;
1125                 case 't':
1126                         thresh = parse_size(optarg);
1127                         defrag_global_fancy_ioctl = 1;
1128                         break;
1129                 case 'r':
1130                         recursive = 1;
1131                         break;
1132                 default:
1133                         usage(cmd_defrag_usage);
1134                 }
1135         }
1136
1137         if (check_argc_min(argc - optind, 1))
1138                 usage(cmd_defrag_usage);
1139
1140         memset(&defrag_global_range, 0, sizeof(range));
1141         defrag_global_range.start = start;
1142         defrag_global_range.len = len;
1143         defrag_global_range.extent_thresh = thresh;
1144         if (compress_type) {
1145                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
1146                 defrag_global_range.compress_type = compress_type;
1147         }
1148         if (flush)
1149                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
1150
1151         for (i = optind; i < argc; i++) {
1152                 struct stat st;
1153
1154                 dirstream = NULL;
1155                 fd = open_file_or_dir(argv[i], &dirstream);
1156                 if (fd < 0) {
1157                         fprintf(stderr, "ERROR: failed to open %s - %s\n", argv[i],
1158                                         strerror(errno));
1159                         defrag_global_errors++;
1160                         close_file_or_dir(fd, dirstream);
1161                         continue;
1162                 }
1163                 if (fstat(fd, &st)) {
1164                         fprintf(stderr, "ERROR: failed to stat %s - %s\n",
1165                                         argv[i], strerror(errno));
1166                         defrag_global_errors++;
1167                         close_file_or_dir(fd, dirstream);
1168                         continue;
1169                 }
1170                 if (!(S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))) {
1171                         fprintf(stderr,
1172                             "ERROR: %s is not a directory or a regular file\n",
1173                             argv[i]);
1174                         defrag_global_errors++;
1175                         close_file_or_dir(fd, dirstream);
1176                         continue;
1177                 }
1178                 if (recursive) {
1179                         if (S_ISDIR(st.st_mode)) {
1180                                 ret = nftw(argv[i], defrag_callback, 10,
1181                                                 FTW_MOUNT | FTW_PHYS);
1182                                 if (ret == ENOTTY)
1183                                         exit(1);
1184                                 /* errors are handled in the callback */
1185                                 ret = 0;
1186                         } else {
1187                                 if (defrag_global_verbose)
1188                                         printf("%s\n", argv[i]);
1189                                 ret = do_defrag(fd, defrag_global_fancy_ioctl,
1190                                                 &defrag_global_range);
1191                                 e = errno;
1192                         }
1193                 } else {
1194                         if (defrag_global_verbose)
1195                                 printf("%s\n", argv[i]);
1196                         ret = do_defrag(fd, defrag_global_fancy_ioctl,
1197                                         &defrag_global_range);
1198                         e = errno;
1199                 }
1200                 close_file_or_dir(fd, dirstream);
1201                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1202                         fprintf(stderr, "ERROR: defrag range ioctl not "
1203                                 "supported in this kernel, please try "
1204                                 "without any options.\n");
1205                         defrag_global_errors++;
1206                         break;
1207                 }
1208                 if (ret) {
1209                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
1210                                 argv[i], strerror(e));
1211                         defrag_global_errors++;
1212                 }
1213         }
1214         if (defrag_global_verbose)
1215                 printf("%s\n", PACKAGE_STRING);
1216         if (defrag_global_errors)
1217                 fprintf(stderr, "total %d failures\n", defrag_global_errors);
1218
1219         return !!defrag_global_errors;
1220 }
1221
1222 static const char * const cmd_resize_usage[] = {
1223         "btrfs filesystem resize [devid:][+/-]<newsize>[kKmMgGtTpPeE]|[devid:]max <path>",
1224         "Resize a filesystem",
1225         "If 'max' is passed, the filesystem will occupy all available space",
1226         "on the device 'devid'.",
1227         "[kK] means KiB, which denotes 1KiB = 1024B, 1MiB = 1024KiB, etc.",
1228         NULL
1229 };
1230
1231 static int cmd_resize(int argc, char **argv)
1232 {
1233         struct btrfs_ioctl_vol_args     args;
1234         int     fd, res, len, e;
1235         char    *amount, *path;
1236         DIR     *dirstream = NULL;
1237         struct stat st;
1238
1239         if (check_argc_exact(argc, 3))
1240                 usage(cmd_resize_usage);
1241
1242         amount = argv[1];
1243         path = argv[2];
1244
1245         len = strlen(amount);
1246         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
1247                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
1248                         amount);
1249                 return 1;
1250         }
1251
1252         res = stat(path, &st);
1253         if (res < 0) {
1254                 fprintf(stderr, "ERROR: resize: cannot stat %s: %s\n",
1255                                 path, strerror(errno));
1256                 return 1;
1257         }
1258         if (!S_ISDIR(st.st_mode)) {
1259                 fprintf(stderr,
1260                         "ERROR: resize works on mounted filesystems and accepts only\n"
1261                         "directories as argument. Passing file containing a btrfs image\n"
1262                         "would resize the underlying filesystem instead of the image.\n");
1263                 return 1;
1264         }
1265
1266         fd = open_file_or_dir(path, &dirstream);
1267         if (fd < 0) {
1268                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
1269                 return 1;
1270         }
1271
1272         printf("Resize '%s' of '%s'\n", path, amount);
1273         strncpy_null(args.name, amount);
1274         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
1275         e = errno;
1276         close_file_or_dir(fd, dirstream);
1277         if( res < 0 ){
1278                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
1279                         path, strerror(e));
1280                 return 1;
1281         } else if (res > 0) {
1282                 const char *err_str = btrfs_err_str(res);
1283
1284                 if (err_str) {
1285                         fprintf(stderr, "ERROR: btrfs error resizing '%s' - %s\n",
1286                                 path, err_str);
1287                 } else {
1288                         fprintf(stderr,
1289                         "ERROR: btrfs error resizing '%s' - unknown btrfs_err_code %d\n",
1290                                 path, res);
1291                 }
1292                 return 1;
1293         }
1294         return 0;
1295 }
1296
1297 static const char * const cmd_label_usage[] = {
1298         "btrfs filesystem label [<device>|<mount_point>] [<newlabel>]",
1299         "Get or change the label of a filesystem",
1300         "With one argument, get the label of filesystem on <device>.",
1301         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
1302         NULL
1303 };
1304
1305 static int cmd_label(int argc, char **argv)
1306 {
1307         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
1308                 usage(cmd_label_usage);
1309
1310         if (argc > 2) {
1311                 return set_label(argv[1], argv[2]);
1312         } else {
1313                 char label[BTRFS_LABEL_SIZE];
1314                 int ret;
1315
1316                 ret = get_label(argv[1], label);
1317                 if (!ret)
1318                         fprintf(stdout, "%s\n", label);
1319
1320                 return ret;
1321         }
1322 }
1323
1324 static const char filesystem_cmd_group_info[] =
1325 "overall filesystem tasks and information";
1326
1327 const struct cmd_group filesystem_cmd_group = {
1328         filesystem_cmd_group_usage, filesystem_cmd_group_info, {
1329                 { "df", cmd_filesystem_df, cmd_filesystem_df_usage, NULL, 0 },
1330                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
1331                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
1332                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
1333                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
1334                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
1335                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
1336                 { "usage", cmd_filesystem_usage,
1337                         cmd_filesystem_usage_usage, NULL, 0 },
1338
1339                 NULL_CMD_STRUCT
1340         }
1341 };
1342
1343 int cmd_filesystem(int argc, char **argv)
1344 {
1345         return handle_command_group(&filesystem_cmd_group, argc, argv);
1346 }