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