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