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