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