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