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