btrfs-progs: drop feature defines from C files, in favour of CFLAGS defines
[platform/upstream/btrfs-progs.git] / cmds-filesystem.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/ioctl.h>
22 #include <errno.h>
23 #include <uuid/uuid.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26 #include <ftw.h>
27 #include <mntent.h>
28 #include <linux/limits.h>
29 #include <getopt.h>
30
31 #include "kerncompat.h"
32 #include "ctree.h"
33 #include "ioctl.h"
34 #include "utils.h"
35 #include "volumes.h"
36 #include "version.h"
37 #include "commands.h"
38 #include "cmds-fi-disk_usage.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 is_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
62         return seen ? 1 : 0;
63 }
64
65 static int add_seen_fsid(u8 *fsid)
66 {
67         u8 hash = fsid[0];
68         int slot = hash % SEEN_FSID_HASH_SIZE;
69         struct seen_fsid *seen = seen_fsid_hash[slot];
70         struct seen_fsid *alloc;
71
72         if (!seen)
73                 goto insert;
74
75         while (1) {
76                 if (memcmp(seen->fsid, fsid, BTRFS_FSID_SIZE) == 0)
77                         return -EEXIST;
78
79                 if (!seen->next)
80                         break;
81
82                 seen = seen->next;
83         }
84
85 insert:
86
87         alloc = malloc(sizeof(*alloc));
88         if (!alloc)
89                 return -ENOMEM;
90
91         alloc->next = NULL;
92         memcpy(alloc->fsid, fsid, BTRFS_FSID_SIZE);
93
94         if (seen)
95                 seen->next = alloc;
96         else
97                 seen_fsid_hash[slot] = alloc;
98
99         return 0;
100 }
101
102 static void free_seen_fsid(void)
103 {
104         int slot;
105         struct seen_fsid *seen;
106         struct seen_fsid *next;
107
108         for (slot = 0; slot < SEEN_FSID_HASH_SIZE; slot++) {
109                 seen = seen_fsid_hash[slot];
110                 while (seen) {
111                         next = seen->next;
112                         free(seen);
113                         seen = next;
114                 }
115                 seen_fsid_hash[slot] = NULL;
116         }
117 }
118
119 static const char * const filesystem_cmd_group_usage[] = {
120         "btrfs filesystem [<group>] <command> [<args>]",
121         NULL
122 };
123
124 static const char * const cmd_filesystem_df_usage[] = {
125        "btrfs filesystem df [options] <path>",
126        "Show space usage information for a mount point",
127         "-b|--raw           raw numbers in bytes",
128         "-h|--human-readable",
129         "                   human friendly numbers, base 1024 (default)",
130         "-H                 human friendly numbers, base 1000",
131         "--iec              use 1024 as a base (KiB, MiB, GiB, TiB)",
132         "--si               use 1000 as a base (kB, MB, GB, TB)",
133         "-k|--kbytes        show sizes in KiB, or kB with --si",
134         "-m|--mbytes        show sizes in MiB, or MB with --si",
135         "-g|--gbytes        show sizes in GiB, or GB with --si",
136         "-t|--tbytes        show sizes in TiB, or TB with --si",
137        NULL
138 };
139
140 static int get_df(int fd, struct btrfs_ioctl_space_args **sargs_ret)
141 {
142         u64 count = 0;
143         int ret, e;
144         struct btrfs_ioctl_space_args *sargs;
145
146         sargs = malloc(sizeof(struct btrfs_ioctl_space_args));
147         if (!sargs)
148                 return -ENOMEM;
149
150         sargs->space_slots = 0;
151         sargs->total_spaces = 0;
152
153         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
154         e = errno;
155         if (ret) {
156                 fprintf(stderr, "ERROR: couldn't get space info - %s\n",
157                         strerror(e));
158                 free(sargs);
159                 return -e;
160         }
161         /* This really should never happen */
162         if (!sargs->total_spaces) {
163                 free(sargs);
164                 return -ENOENT;
165         }
166         count = sargs->total_spaces;
167         free(sargs);
168
169         sargs = malloc(sizeof(struct btrfs_ioctl_space_args) +
170                         (count * sizeof(struct btrfs_ioctl_space_info)));
171         if (!sargs)
172                 return -ENOMEM;
173
174         sargs->space_slots = count;
175         sargs->total_spaces = 0;
176         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
177         e = errno;
178         if (ret) {
179                 fprintf(stderr, "ERROR: get space info count %llu - %s\n",
180                                 count, strerror(e));
181                 free(sargs);
182                 return -e;
183         }
184         *sargs_ret = sargs;
185         return 0;
186 }
187
188 static void print_df(struct btrfs_ioctl_space_args *sargs, unsigned unit_mode)
189 {
190         u64 i;
191         struct btrfs_ioctl_space_info *sp = sargs->spaces;
192
193         for (i = 0; i < sargs->total_spaces; i++, sp++) {
194                 printf("%s, %s: total=%s, used=%s\n",
195                         btrfs_group_type_str(sp->flags),
196                         btrfs_group_profile_str(sp->flags),
197                         pretty_size_mode(sp->total_bytes, unit_mode),
198                         pretty_size_mode(sp->used_bytes, unit_mode));
199         }
200 }
201
202 static int cmd_filesystem_df(int argc, char **argv)
203 {
204         struct btrfs_ioctl_space_args *sargs = NULL;
205         int ret;
206         int fd;
207         char *path;
208         DIR *dirstream = NULL;
209         unsigned unit_mode = UNITS_DEFAULT;
210
211         while (1) {
212                 int long_index;
213                 static const struct option long_options[] = {
214                         { "raw", no_argument, NULL, 'b'},
215                         { "kbytes", no_argument, NULL, 'k'},
216                         { "mbytes", no_argument, NULL, 'm'},
217                         { "gbytes", no_argument, NULL, 'g'},
218                         { "tbytes", no_argument, NULL, 't'},
219                         { "si", no_argument, NULL, GETOPT_VAL_SI},
220                         { "iec", no_argument, NULL, GETOPT_VAL_IEC},
221                         { "human-readable", no_argument, NULL,
222                                 GETOPT_VAL_HUMAN_READABLE},
223                         { NULL, 0, NULL, 0 }
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 GETOPT_VAL_HUMAN_READABLE:
246                 case 'h':
247                         unit_mode = UNITS_HUMAN_BINARY;
248                         break;
249                 case 'H':
250                         unit_mode = UNITS_HUMAN_DECIMAL;
251                         break;
252                 case GETOPT_VAL_SI:
253                         units_set_mode(&unit_mode, UNITS_DECIMAL);
254                         break;
255                 case GETOPT_VAL_IEC:
256                         units_set_mode(&unit_mode, UNITS_BINARY);
257                         break;
258                 default:
259                         usage(cmd_filesystem_df_usage);
260                 }
261         }
262
263         if (check_argc_exact(argc, optind + 1))
264                 usage(cmd_filesystem_df_usage);
265
266         path = argv[optind];
267
268         fd = open_file_or_dir(path, &dirstream);
269         if (fd < 0) {
270                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
271                 return 1;
272         }
273         ret = get_df(fd, &sargs);
274
275         if (ret == 0) {
276                 print_df(sargs, unit_mode);
277                 free(sargs);
278         } else {
279                 fprintf(stderr, "ERROR: get_df failed %s\n", strerror(-ret));
280         }
281
282         close_file_or_dir(fd, dirstream);
283         return !!ret;
284 }
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
479                 /* Add check for missing devices even mounted */
480                 fd = open((char *)tmp_dev_info->path, O_RDONLY);
481                 if (fd < 0) {
482                         missing = 1;
483                         continue;
484                 }
485                 close(fd);
486                 canonical_path = canonicalize_path((char *)tmp_dev_info->path);
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 static int btrfs_scan_kernel(void *search)
503 {
504         int ret = 0, fd;
505         int found = 0;
506         FILE *f;
507         struct mntent *mnt;
508         struct btrfs_ioctl_fs_info_args fs_info_arg;
509         struct btrfs_ioctl_dev_info_args *dev_info_arg = NULL;
510         struct btrfs_ioctl_space_args *space_info_arg = NULL;
511         char label[BTRFS_LABEL_SIZE];
512
513         f = setmntent("/proc/self/mounts", "r");
514         if (f == NULL)
515                 return 1;
516
517         memset(label, 0, sizeof(label));
518         while ((mnt = getmntent(f)) != NULL) {
519                 if (strcmp(mnt->mnt_type, "btrfs"))
520                         continue;
521                 ret = get_fs_info(mnt->mnt_dir, &fs_info_arg,
522                                 &dev_info_arg);
523                 if (ret) {
524                         kfree(dev_info_arg);
525                         goto out;
526                 }
527
528                 if (get_label_mounted(mnt->mnt_dir, label)) {
529                         kfree(dev_info_arg);
530                         goto out;
531                 }
532                 if (search && !match_search_item_kernel(fs_info_arg.fsid,
533                                         mnt->mnt_dir, label, search)) {
534                         kfree(dev_info_arg);
535                         continue;
536                 }
537
538                 fd = open(mnt->mnt_dir, O_RDONLY);
539                 if ((fd != -1) && !get_df(fd, &space_info_arg)) {
540                         print_one_fs(&fs_info_arg, dev_info_arg,
541                                         space_info_arg, label, mnt->mnt_dir);
542                         kfree(space_info_arg);
543                         memset(label, 0, sizeof(label));
544                         found = 1;
545                 }
546                 if (fd != -1)
547                         close(fd);
548                 kfree(dev_info_arg);
549         }
550
551 out:
552         endmntent(f);
553         return !found;
554 }
555
556 static int dev_to_fsid(char *dev, __u8 *fsid)
557 {
558         struct btrfs_super_block *disk_super;
559         char *buf;
560         int ret;
561         int fd;
562
563         buf = malloc(4096);
564         if (!buf)
565                 return -ENOMEM;
566
567         fd = open(dev, O_RDONLY);
568         if (fd < 0) {
569                 ret = -errno;
570                 free(buf);
571                 return ret;
572         }
573
574         disk_super = (struct btrfs_super_block *)buf;
575         ret = btrfs_read_dev_super(fd, disk_super,
576                                    BTRFS_SUPER_INFO_OFFSET, 0);
577         if (ret)
578                 goto out;
579
580         memcpy(fsid, disk_super->fsid, BTRFS_FSID_SIZE);
581         ret = 0;
582
583 out:
584         close(fd);
585         free(buf);
586         return ret;
587 }
588
589 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
590 {
591         struct btrfs_fs_devices *cur_seed, *next_seed;
592         struct btrfs_device *device;
593
594         while (!list_empty(&fs_devices->devices)) {
595                 device = list_entry(fs_devices->devices.next,
596                                         struct btrfs_device, dev_list);
597                 list_del(&device->dev_list);
598
599                 free(device->name);
600                 free(device->label);
601                 free(device);
602         }
603
604         /* free seed fs chain */
605         cur_seed = fs_devices->seed;
606         fs_devices->seed = NULL;
607         while (cur_seed) {
608                 next_seed = cur_seed->seed;
609                 free(cur_seed);
610
611                 cur_seed = next_seed;
612         }
613
614         list_del(&fs_devices->list);
615         free(fs_devices);
616 }
617
618 static int copy_device(struct btrfs_device *dst,
619                        struct btrfs_device *src)
620 {
621         dst->devid = src->devid;
622         memcpy(dst->uuid, src->uuid, BTRFS_UUID_SIZE);
623         if (src->name == NULL)
624                 dst->name = NULL;
625         else {
626                 dst->name = strdup(src->name);
627                 if (!dst->name)
628                         return -ENOMEM;
629         }
630         if (src->label == NULL)
631                 dst->label = NULL;
632         else {
633                 dst->label = strdup(src->label);
634                 if (!dst->label) {
635                         free(dst->name);
636                         return -ENOMEM;
637                 }
638         }
639         dst->total_devs = src->total_devs;
640         dst->super_bytes_used = src->super_bytes_used;
641         dst->total_bytes = src->total_bytes;
642         dst->bytes_used = src->bytes_used;
643         dst->generation = src->generation;
644
645         return 0;
646 }
647
648 static int copy_fs_devices(struct btrfs_fs_devices *dst,
649                            struct btrfs_fs_devices *src)
650 {
651         struct btrfs_device *cur_dev, *dev_copy;
652         int ret = 0;
653
654         memcpy(dst->fsid, src->fsid, BTRFS_FSID_SIZE);
655         INIT_LIST_HEAD(&dst->devices);
656         dst->seed = NULL;
657
658         list_for_each_entry(cur_dev, &src->devices, dev_list) {
659                 dev_copy = malloc(sizeof(*dev_copy));
660                 if (!dev_copy) {
661                         ret = -ENOMEM;
662                         break;
663                 }
664
665                 ret = copy_device(dev_copy, cur_dev);
666                 if (ret) {
667                         free(dev_copy);
668                         break;
669                 }
670
671                 list_add(&dev_copy->dev_list, &dst->devices);
672                 dev_copy->fs_devices = dst;
673         }
674
675         return ret;
676 }
677
678 static int find_and_copy_seed(struct btrfs_fs_devices *seed,
679                               struct btrfs_fs_devices *copy,
680                               struct list_head *fs_uuids) {
681         struct btrfs_fs_devices *cur_fs;
682
683         list_for_each_entry(cur_fs, fs_uuids, list)
684                 if (!memcmp(seed->fsid, cur_fs->fsid, BTRFS_FSID_SIZE))
685                         return copy_fs_devices(copy, cur_fs);
686
687         return 1;
688 }
689
690 static int has_seed_devices(struct btrfs_fs_devices *fs_devices)
691 {
692         struct btrfs_device *device;
693         int dev_cnt_total, dev_cnt = 0;
694
695         device = list_first_entry(&fs_devices->devices, struct btrfs_device,
696                                   dev_list);
697
698         dev_cnt_total = device->total_devs;
699
700         list_for_each_entry(device, &fs_devices->devices, dev_list)
701                 dev_cnt++;
702
703         return dev_cnt_total != dev_cnt;
704 }
705
706 static int search_umounted_fs_uuids(struct list_head *all_uuids,
707                                     char *search, int *found)
708 {
709         struct btrfs_fs_devices *cur_fs, *fs_copy;
710         struct list_head *fs_uuids;
711         int ret = 0;
712
713         fs_uuids = btrfs_scanned_uuids();
714
715         /*
716          * The fs_uuids list is global, and open_ctree_* will
717          * modify it, make a private copy here
718          */
719         list_for_each_entry(cur_fs, fs_uuids, list) {
720                 /* don't bother handle all fs, if search target specified */
721                 if (search) {
722                         if (uuid_search(cur_fs, search) == 0)
723                                 continue;
724                         if (found)
725                                 *found = 1;
726                 }
727
728                 /* skip all fs already shown as mounted fs */
729                 if (is_seen_fsid(cur_fs->fsid))
730                         continue;
731
732                 fs_copy = malloc(sizeof(*fs_copy));
733                 if (!fs_copy) {
734                         ret = -ENOMEM;
735                         goto out;
736                 }
737
738                 ret = copy_fs_devices(fs_copy, cur_fs);
739                 if (ret) {
740                         free(fs_copy);
741                         goto out;
742                 }
743
744                 list_add(&fs_copy->list, all_uuids);
745         }
746
747 out:
748         return ret;
749 }
750
751 static int map_seed_devices(struct list_head *all_uuids)
752 {
753         struct btrfs_fs_devices *cur_fs, *cur_seed;
754         struct btrfs_fs_devices *seed_copy;
755         struct btrfs_fs_devices *opened_fs;
756         struct btrfs_device *device;
757         struct btrfs_fs_info *fs_info;
758         struct list_head *fs_uuids;
759         int ret = 0;
760
761         fs_uuids = btrfs_scanned_uuids();
762
763         list_for_each_entry(cur_fs, all_uuids, list) {
764                 device = list_first_entry(&cur_fs->devices,
765                                                 struct btrfs_device, dev_list);
766                 if (!device)
767                         continue;
768
769                 /* skip fs without seeds */
770                 if (!has_seed_devices(cur_fs))
771                         continue;
772
773                 /*
774                  * open_ctree_* detects seed/sprout mapping
775                  */
776                 fs_info = open_ctree_fs_info(device->name, 0, 0,
777                                                 OPEN_CTREE_PARTIAL);
778                 if (!fs_info)
779                         continue;
780
781                 /*
782                  * copy the seed chain under the opened fs
783                  */
784                 opened_fs = fs_info->fs_devices;
785                 cur_seed = cur_fs;
786                 while (opened_fs->seed) {
787                         seed_copy = malloc(sizeof(*seed_copy));
788                         if (!seed_copy) {
789                                 ret = -ENOMEM;
790                                 goto fail_out;
791                         }
792                         ret = find_and_copy_seed(opened_fs->seed, seed_copy,
793                                                  fs_uuids);
794                         if (ret) {
795                                 free(seed_copy);
796                                 goto fail_out;
797                         }
798
799                         cur_seed->seed = seed_copy;
800
801                         opened_fs = opened_fs->seed;
802                         cur_seed = cur_seed->seed;
803                 }
804
805                 close_ctree(fs_info->chunk_root);
806         }
807
808 out:
809         return ret;
810 fail_out:
811         close_ctree(fs_info->chunk_root);
812         goto out;
813 }
814
815 static const char * const cmd_show_usage[] = {
816         "btrfs filesystem show [options] [<path>|<uuid>|<device>|label]",
817         "Show the structure of a filesystem",
818         "-d|--all-devices   show only disks under /dev containing btrfs filesystem",
819         "-m|--mounted       show only mounted btrfs",
820         "If no argument is given, structure of all present filesystems is shown.",
821         NULL
822 };
823
824 static int cmd_show(int argc, char **argv)
825 {
826         LIST_HEAD(all_uuids);
827         struct btrfs_fs_devices *fs_devices;
828         char *search = NULL;
829         int ret;
830         /* default, search both kernel and udev */
831         int where = -1;
832         int type = 0;
833         char mp[BTRFS_PATH_NAME_MAX + 1];
834         char path[PATH_MAX];
835         __u8 fsid[BTRFS_FSID_SIZE];
836         char uuid_buf[BTRFS_UUID_UNPARSED_SIZE];
837         int found = 0;
838
839         while (1) {
840                 int long_index;
841                 static const struct option long_options[] = {
842                         { "all-devices", no_argument, NULL, 'd'},
843                         { "mounted", no_argument, NULL, 'm'},
844                         { NULL, 0, NULL, 0 }
845                 };
846                 int c = getopt_long(argc, argv, "dm", long_options,
847                                         &long_index);
848                 if (c < 0)
849                         break;
850                 switch (c) {
851                 case 'd':
852                         where = BTRFS_SCAN_LBLKID;
853                         break;
854                 case 'm':
855                         where = BTRFS_SCAN_MOUNTED;
856                         break;
857                 default:
858                         usage(cmd_show_usage);
859                 }
860         }
861
862         if (check_argc_max(argc, optind + 1))
863                 usage(cmd_show_usage);
864
865         if (argc > optind) {
866                 search = argv[optind];
867                 if (strlen(search) == 0)
868                         usage(cmd_show_usage);
869                 type = check_arg_type(search);
870
871                 /*
872                  * For search is a device:
873                  *     realpath do /dev/mapper/XX => /dev/dm-X
874                  *     which is required by BTRFS_SCAN_DEV
875                  * For search is a mountpoint:
876                  *     realpath do  /mnt/btrfs/  => /mnt/btrfs
877                  *     which shall be recognized by btrfs_scan_kernel()
878                  */
879                 if (realpath(search, path))
880                         search = path;
881
882                 /*
883                  * Needs special handling if input arg is block dev And if
884                  * input arg is mount-point just print it right away
885                  */
886                 if (type == BTRFS_ARG_BLKDEV && where != BTRFS_SCAN_LBLKID) {
887                         ret = get_btrfs_mount(search, mp, sizeof(mp));
888                         if (!ret) {
889                                 /* given block dev is mounted */
890                                 search = mp;
891                                 type = BTRFS_ARG_MNTPOINT;
892                         } else {
893                                 ret = dev_to_fsid(search, fsid);
894                                 if (ret) {
895                                         fprintf(stderr,
896                                                 "ERROR: No btrfs on %s\n",
897                                                 search);
898                                         return 1;
899                                 }
900                                 uuid_unparse(fsid, uuid_buf);
901                                 search = uuid_buf;
902                                 type = BTRFS_ARG_UUID;
903                                 goto devs_only;
904                         }
905                 }
906         }
907
908         if (where == BTRFS_SCAN_LBLKID)
909                 goto devs_only;
910
911         /* show mounted btrfs */
912         ret = btrfs_scan_kernel(search);
913         if (search && !ret) {
914                 /* since search is found we are done */
915                 goto out;
916         }
917
918         /* shows mounted only */
919         if (where == BTRFS_SCAN_MOUNTED)
920                 goto out;
921
922 devs_only:
923         ret = btrfs_scan_lblkid();
924
925         if (ret) {
926                 fprintf(stderr, "ERROR: %d while scanning\n", ret);
927                 return 1;
928         }
929
930         ret = search_umounted_fs_uuids(&all_uuids, search, &found);
931         if (ret < 0) {
932                 fprintf(stderr,
933                         "ERROR: %d while searching target device\n", ret);
934                 return 1;
935         }
936
937         /*
938          * The seed/sprout mapping are not detected yet,
939          * do mapping build for all umounted fs
940          */
941         ret = map_seed_devices(&all_uuids);
942         if (ret) {
943                 fprintf(stderr,
944                         "ERROR: %d while mapping seed devices\n", ret);
945                 return 1;
946         }
947
948         list_for_each_entry(fs_devices, &all_uuids, list)
949                 print_one_uuid(fs_devices);
950
951         if (search && !found)
952                 ret = 1;
953
954         while (!list_empty(&all_uuids)) {
955                 fs_devices = list_entry(all_uuids.next,
956                                         struct btrfs_fs_devices, list);
957                 free_fs_devices(fs_devices);
958         }
959 out:
960         printf("%s\n", BTRFS_BUILD_VERSION);
961         free_seen_fsid();
962         return ret;
963 }
964
965 static const char * const cmd_sync_usage[] = {
966         "btrfs filesystem sync <path>",
967         "Force a sync on a filesystem",
968         NULL
969 };
970
971 static int cmd_sync(int argc, char **argv)
972 {
973         int     fd, res, e;
974         char    *path;
975         DIR     *dirstream = NULL;
976
977         if (check_argc_exact(argc, 2))
978                 usage(cmd_sync_usage);
979
980         path = argv[1];
981
982         fd = open_file_or_dir(path, &dirstream);
983         if (fd < 0) {
984                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
985                 return 1;
986         }
987
988         printf("FSSync '%s'\n", path);
989         res = ioctl(fd, BTRFS_IOC_SYNC);
990         e = errno;
991         close_file_or_dir(fd, dirstream);
992         if( res < 0 ){
993                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
994                         path, strerror(e));
995                 return 1;
996         }
997
998         return 0;
999 }
1000
1001 static int parse_compress_type(char *s)
1002 {
1003         if (strcmp(optarg, "zlib") == 0)
1004                 return BTRFS_COMPRESS_ZLIB;
1005         else if (strcmp(optarg, "lzo") == 0)
1006                 return BTRFS_COMPRESS_LZO;
1007         else {
1008                 fprintf(stderr, "Unknown compress type %s\n", s);
1009                 exit(1);
1010         };
1011 }
1012
1013 static const char * const cmd_defrag_usage[] = {
1014         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
1015         "Defragment a file or a directory",
1016         "",
1017         "-v             be verbose",
1018         "-r             defragment files recursively",
1019         "-c[zlib,lzo]   compress the file while defragmenting",
1020         "-f             flush data to disk immediately after defragmenting",
1021         "-s start       defragment only from byte onward",
1022         "-l len         defragment only up to len bytes",
1023         "-t size        minimal size of file to be considered for defragmenting",
1024         NULL
1025 };
1026
1027 static int do_defrag(int fd, int fancy_ioctl,
1028                 struct btrfs_ioctl_defrag_range_args *range)
1029 {
1030         int ret;
1031
1032         if (!fancy_ioctl)
1033                 ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
1034         else
1035                 ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, range);
1036
1037         return ret;
1038 }
1039
1040 static int defrag_global_fancy_ioctl;
1041 static struct btrfs_ioctl_defrag_range_args defrag_global_range;
1042 static int defrag_global_verbose;
1043 static int defrag_global_errors;
1044 static int defrag_callback(const char *fpath, const struct stat *sb,
1045                 int typeflag, struct FTW *ftwbuf)
1046 {
1047         int ret = 0;
1048         int e = 0;
1049         int fd = 0;
1050
1051         if ((typeflag == FTW_F) && S_ISREG(sb->st_mode)) {
1052                 if (defrag_global_verbose)
1053                         printf("%s\n", fpath);
1054                 fd = open(fpath, O_RDWR);
1055                 e = errno;
1056                 if (fd < 0)
1057                         goto error;
1058                 ret = do_defrag(fd, defrag_global_fancy_ioctl, &defrag_global_range);
1059                 e = errno;
1060                 close(fd);
1061                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1062                         fprintf(stderr, "ERROR: defrag range ioctl not "
1063                                 "supported in this kernel, please try "
1064                                 "without any options.\n");
1065                         defrag_global_errors++;
1066                         return ENOTTY;
1067                 }
1068                 if (ret)
1069                         goto error;
1070         }
1071         return 0;
1072
1073 error:
1074         fprintf(stderr, "ERROR: defrag failed on %s - %s\n", fpath, strerror(e));
1075         defrag_global_errors++;
1076         return 0;
1077 }
1078
1079 static int cmd_defrag(int argc, char **argv)
1080 {
1081         int fd;
1082         int flush = 0;
1083         u64 start = 0;
1084         u64 len = (u64)-1;
1085         u32 thresh = 0;
1086         int i;
1087         int recursive = 0;
1088         int ret = 0;
1089         struct btrfs_ioctl_defrag_range_args range;
1090         int e = 0;
1091         int compress_type = BTRFS_COMPRESS_NONE;
1092         DIR *dirstream;
1093
1094         defrag_global_errors = 0;
1095         defrag_global_verbose = 0;
1096         defrag_global_errors = 0;
1097         defrag_global_fancy_ioctl = 0;
1098         optind = 1;
1099         while(1) {
1100                 int c = getopt(argc, argv, "vrc::fs:l:t:");
1101                 if (c < 0)
1102                         break;
1103
1104                 switch(c) {
1105                 case 'c':
1106                         compress_type = BTRFS_COMPRESS_ZLIB;
1107                         if (optarg)
1108                                 compress_type = parse_compress_type(optarg);
1109                         defrag_global_fancy_ioctl = 1;
1110                         break;
1111                 case 'f':
1112                         flush = 1;
1113                         defrag_global_fancy_ioctl = 1;
1114                         break;
1115                 case 'v':
1116                         defrag_global_verbose = 1;
1117                         break;
1118                 case 's':
1119                         start = parse_size(optarg);
1120                         defrag_global_fancy_ioctl = 1;
1121                         break;
1122                 case 'l':
1123                         len = parse_size(optarg);
1124                         defrag_global_fancy_ioctl = 1;
1125                         break;
1126                 case 't':
1127                         thresh = parse_size(optarg);
1128                         defrag_global_fancy_ioctl = 1;
1129                         break;
1130                 case 'r':
1131                         recursive = 1;
1132                         break;
1133                 default:
1134                         usage(cmd_defrag_usage);
1135                 }
1136         }
1137
1138         if (check_argc_min(argc - optind, 1))
1139                 usage(cmd_defrag_usage);
1140
1141         memset(&defrag_global_range, 0, sizeof(range));
1142         defrag_global_range.start = start;
1143         defrag_global_range.len = len;
1144         defrag_global_range.extent_thresh = thresh;
1145         if (compress_type) {
1146                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
1147                 defrag_global_range.compress_type = compress_type;
1148         }
1149         if (flush)
1150                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
1151
1152         for (i = optind; i < argc; i++) {
1153                 struct stat st;
1154
1155                 dirstream = NULL;
1156                 fd = open_file_or_dir(argv[i], &dirstream);
1157                 if (fd < 0) {
1158                         fprintf(stderr, "ERROR: failed to open %s - %s\n", argv[i],
1159                                         strerror(errno));
1160                         defrag_global_errors++;
1161                         close_file_or_dir(fd, dirstream);
1162                         continue;
1163                 }
1164                 if (fstat(fd, &st)) {
1165                         fprintf(stderr, "ERROR: failed to stat %s - %s\n",
1166                                         argv[i], strerror(errno));
1167                         defrag_global_errors++;
1168                         close_file_or_dir(fd, dirstream);
1169                         continue;
1170                 }
1171                 if (!(S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))) {
1172                         fprintf(stderr,
1173                             "ERROR: %s is not a directory or a regular file\n",
1174                             argv[i]);
1175                         defrag_global_errors++;
1176                         close_file_or_dir(fd, dirstream);
1177                         continue;
1178                 }
1179                 if (recursive) {
1180                         if (S_ISDIR(st.st_mode)) {
1181                                 ret = nftw(argv[i], defrag_callback, 10,
1182                                                 FTW_MOUNT | FTW_PHYS);
1183                                 if (ret == ENOTTY)
1184                                         exit(1);
1185                                 /* errors are handled in the callback */
1186                                 ret = 0;
1187                         } else {
1188                                 if (defrag_global_verbose)
1189                                         printf("%s\n", argv[i]);
1190                                 ret = do_defrag(fd, defrag_global_fancy_ioctl,
1191                                                 &defrag_global_range);
1192                                 e = errno;
1193                         }
1194                 } else {
1195                         if (defrag_global_verbose)
1196                                 printf("%s\n", argv[i]);
1197                         ret = do_defrag(fd, defrag_global_fancy_ioctl,
1198                                         &defrag_global_range);
1199                         e = errno;
1200                 }
1201                 close_file_or_dir(fd, dirstream);
1202                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
1203                         fprintf(stderr, "ERROR: defrag range ioctl not "
1204                                 "supported in this kernel, please try "
1205                                 "without any options.\n");
1206                         defrag_global_errors++;
1207                         break;
1208                 }
1209                 if (ret) {
1210                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
1211                                 argv[i], strerror(e));
1212                         defrag_global_errors++;
1213                 }
1214         }
1215         if (defrag_global_verbose)
1216                 printf("%s\n", BTRFS_BUILD_VERSION);
1217         if (defrag_global_errors)
1218                 fprintf(stderr, "total %d failures\n", defrag_global_errors);
1219
1220         return !!defrag_global_errors;
1221 }
1222
1223 static const char * const cmd_resize_usage[] = {
1224         "btrfs filesystem resize [devid:][+/-]<newsize>[kKmMgGtTpPeE]|[devid:]max <path>",
1225         "Resize a filesystem",
1226         "If 'max' is passed, the filesystem will occupy all available space",
1227         "on the device 'devid'.",
1228         "[kK] means KiB, which denotes 1KiB = 1024B, 1MiB = 1024KiB, etc.",
1229         NULL
1230 };
1231
1232 static int cmd_resize(int argc, char **argv)
1233 {
1234         struct btrfs_ioctl_vol_args     args;
1235         int     fd, res, len, e;
1236         char    *amount, *path;
1237         DIR     *dirstream = NULL;
1238
1239         if (check_argc_exact(argc, 3))
1240                 usage(cmd_resize_usage);
1241
1242         amount = argv[1];
1243         path = argv[2];
1244
1245         len = strlen(amount);
1246         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
1247                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
1248                         amount);
1249                 return 1;
1250         }
1251
1252         fd = open_file_or_dir(path, &dirstream);
1253         if (fd < 0) {
1254                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
1255                 return 1;
1256         }
1257
1258         printf("Resize '%s' of '%s'\n", path, amount);
1259         strncpy_null(args.name, amount);
1260         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
1261         e = errno;
1262         close_file_or_dir(fd, dirstream);
1263         if( res < 0 ){
1264                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
1265                         path, strerror(e));
1266                 return 1;
1267         }
1268         return 0;
1269 }
1270
1271 static const char * const cmd_label_usage[] = {
1272         "btrfs filesystem label [<device>|<mount_point>] [<newlabel>]",
1273         "Get or change the label of a filesystem",
1274         "With one argument, get the label of filesystem on <device>.",
1275         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
1276         NULL
1277 };
1278
1279 static int cmd_label(int argc, char **argv)
1280 {
1281         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
1282                 usage(cmd_label_usage);
1283
1284         if (argc > 2) {
1285                 return set_label(argv[1], argv[2]);
1286         } else {
1287                 char label[BTRFS_LABEL_SIZE];
1288                 int ret;
1289
1290                 ret = get_label(argv[1], label);
1291                 if (!ret)
1292                         fprintf(stdout, "%s\n", label);
1293
1294                 return ret;
1295         }
1296 }
1297
1298 const struct cmd_group filesystem_cmd_group = {
1299         filesystem_cmd_group_usage, NULL, {
1300                 { "df", cmd_filesystem_df, cmd_filesystem_df_usage, NULL, 0 },
1301                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
1302                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
1303                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
1304                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
1305                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
1306                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
1307                 { "usage", cmd_filesystem_usage,
1308                         cmd_filesystem_usage_usage, NULL, 0 },
1309
1310                 NULL_CMD_STRUCT
1311         }
1312 };
1313
1314 int cmd_filesystem(int argc, char **argv)
1315 {
1316         return handle_command_group(&filesystem_cmd_group, argc, argv);
1317 }