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