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