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