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