0f29afc5b289507d39c98f69000e807a5a26cafe
[platform/upstream/btrfs-progs.git] / cmds-filesystem.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #define _XOPEN_SOURCE 500
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <sys/ioctl.h>
23 #include <errno.h>
24 #include <uuid/uuid.h>
25 #include <ctype.h>
26 #include <fcntl.h>
27 #include <ftw.h>
28 #include <mntent.h>
29 #include <linux/limits.h>
30 #include <getopt.h>
31
32 #include "kerncompat.h"
33 #include "ctree.h"
34 #include "ioctl.h"
35 #include "utils.h"
36 #include "volumes.h"
37 #include "version.h"
38 #include "commands.h"
39 #include "list_sort.h"
40
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 add_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         struct seen_fsid *alloc;
61
62         if (!seen)
63                 goto insert;
64
65         while (1) {
66                 if (memcmp(seen->fsid, fsid, BTRFS_FSID_SIZE) == 0)
67                         return -EEXIST;
68
69                 if (!seen->next)
70                         break;
71
72                 seen = seen->next;
73         }
74
75 insert:
76
77         alloc = malloc(sizeof(*alloc));
78         if (!alloc)
79                 return -ENOMEM;
80
81         alloc->next = NULL;
82         memcpy(alloc->fsid, fsid, BTRFS_FSID_SIZE);
83
84         if (seen)
85                 seen->next = alloc;
86         else
87                 seen_fsid_hash[slot] = alloc;
88
89         return 0;
90 }
91
92 static void free_seen_fsid(void)
93 {
94         int slot;
95         struct seen_fsid *seen;
96         struct seen_fsid *next;
97
98         for (slot = 0; slot < SEEN_FSID_HASH_SIZE; slot++) {
99                 seen = seen_fsid_hash[slot];
100                 while (seen) {
101                         next = seen->next;
102                         free(seen);
103                         seen = next;
104                 }
105                 seen_fsid_hash[slot] = NULL;
106         }
107 }
108
109 static const char * const filesystem_cmd_group_usage[] = {
110         "btrfs filesystem [<group>] <command> [<args>]",
111         NULL
112 };
113
114 static const char * const cmd_df_usage[] = {
115         "btrfs filesystem df <path>",
116         "Show space usage information for a mount point",
117         NULL
118 };
119
120 static char *group_type_str(u64 flag)
121 {
122         switch (flag & BTRFS_BLOCK_GROUP_TYPE_MASK) {
123         case BTRFS_BLOCK_GROUP_DATA:
124                 return "Data";
125         case BTRFS_BLOCK_GROUP_SYSTEM:
126                 return "System";
127         case BTRFS_BLOCK_GROUP_METADATA:
128                 return "Metadata";
129         case BTRFS_BLOCK_GROUP_DATA|BTRFS_BLOCK_GROUP_METADATA:
130                 return "Data+Metadata";
131         default:
132                 return "unknown";
133         }
134 }
135
136 static char *group_profile_str(u64 flag)
137 {
138         switch (flag & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
139         case 0:
140                 return "single";
141         case BTRFS_BLOCK_GROUP_RAID0:
142                 return "RAID0";
143         case BTRFS_BLOCK_GROUP_RAID1:
144                 return "RAID1";
145         case BTRFS_BLOCK_GROUP_RAID5:
146                 return "RAID5";
147         case BTRFS_BLOCK_GROUP_RAID6:
148                 return "RAID6";
149         case BTRFS_BLOCK_GROUP_DUP:
150                 return "DUP";
151         case BTRFS_BLOCK_GROUP_RAID10:
152                 return "RAID10";
153         default:
154                 return "unknown";
155         }
156 }
157
158 static int get_df(int fd, struct btrfs_ioctl_space_args **sargs_ret)
159 {
160         u64 count = 0;
161         int ret, e;
162         struct btrfs_ioctl_space_args *sargs;
163
164         sargs = malloc(sizeof(struct btrfs_ioctl_space_args));
165         if (!sargs)
166                 return -ENOMEM;
167
168         sargs->space_slots = 0;
169         sargs->total_spaces = 0;
170
171         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
172         e = errno;
173         if (ret) {
174                 fprintf(stderr, "ERROR: couldn't get space info - %s\n",
175                         strerror(e));
176                 free(sargs);
177                 return -e;
178         }
179         /* This really should never happen */
180         if (!sargs->total_spaces) {
181                 free(sargs);
182                 return -ENOENT;
183         }
184         count = sargs->total_spaces;
185         free(sargs);
186
187         sargs = malloc(sizeof(struct btrfs_ioctl_space_args) +
188                         (count * sizeof(struct btrfs_ioctl_space_info)));
189         if (!sargs)
190                 ret = -ENOMEM;
191
192         sargs->space_slots = count;
193         sargs->total_spaces = 0;
194         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
195         e = errno;
196         if (ret) {
197                 fprintf(stderr, "ERROR: get space info count %llu - %s\n",
198                                 count, strerror(e));
199                 free(sargs);
200                 return -e;
201         }
202         *sargs_ret = sargs;
203         return 0;
204 }
205
206 static void print_df(struct btrfs_ioctl_space_args *sargs)
207 {
208         u64 i;
209         struct btrfs_ioctl_space_info *sp = sargs->spaces;
210
211         for (i = 0; i < sargs->total_spaces; i++, sp++) {
212                 printf("%s, %s: total=%s, used=%s\n",
213                         group_type_str(sp->flags),
214                         group_profile_str(sp->flags),
215                         pretty_size(sp->total_bytes),
216                         pretty_size(sp->used_bytes));
217         }
218 }
219
220 static int cmd_df(int argc, char **argv)
221 {
222         struct btrfs_ioctl_space_args *sargs = NULL;
223         int ret;
224         int fd;
225         char *path;
226         DIR  *dirstream = NULL;
227
228         if (check_argc_exact(argc, 2))
229                 usage(cmd_df_usage);
230
231         path = argv[1];
232
233         fd = open_file_or_dir(path, &dirstream);
234         if (fd < 0) {
235                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
236                 return 1;
237         }
238         ret = get_df(fd, &sargs);
239
240         if (!ret && sargs) {
241                 print_df(sargs);
242                 free(sargs);
243         } else {
244                 fprintf(stderr, "ERROR: get_df failed %s\n", strerror(-ret));
245         }
246
247         close_file_or_dir(fd, dirstream);
248         return !!ret;
249 }
250
251 static int match_search_item_kernel(__u8 *fsid, char *mnt, char *label,
252                                         char *search)
253 {
254         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
255         int search_len = strlen(search);
256
257         search_len = min(search_len, BTRFS_UUID_UNPARSED_SIZE);
258         uuid_unparse(fsid, uuidbuf);
259         if (!strncmp(uuidbuf, search, search_len))
260                 return 1;
261
262         if (strlen(label) && strcmp(label, search) == 0)
263                 return 1;
264
265         if (strcmp(mnt, search) == 0)
266                 return 1;
267
268         return 0;
269 }
270
271 static int uuid_search(struct btrfs_fs_devices *fs_devices, char *search)
272 {
273         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
274         struct list_head *cur;
275         struct btrfs_device *device;
276         int search_len = strlen(search);
277
278         search_len = min(search_len, BTRFS_UUID_UNPARSED_SIZE);
279         uuid_unparse(fs_devices->fsid, uuidbuf);
280         if (!strncmp(uuidbuf, search, search_len))
281                 return 1;
282
283         list_for_each(cur, &fs_devices->devices) {
284                 device = list_entry(cur, struct btrfs_device, dev_list);
285                 if ((device->label && strcmp(device->label, search) == 0) ||
286                     strcmp(device->name, search) == 0)
287                         return 1;
288         }
289         return 0;
290 }
291
292 /*
293  * Sort devices by devid, ascending
294  */
295 static int cmp_device_id(void *priv, struct list_head *a,
296                 struct list_head *b)
297 {
298         const struct btrfs_device *da = list_entry(a, struct btrfs_device,
299                         dev_list);
300         const struct btrfs_device *db = list_entry(b, struct btrfs_device,
301                         dev_list);
302
303         return da->devid < db->devid ? -1 :
304                 da->devid > db->devid ? 1 : 0;
305 }
306
307 static void print_one_uuid(struct btrfs_fs_devices *fs_devices)
308 {
309         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
310         struct list_head *cur;
311         struct btrfs_device *device;
312         u64 devs_found = 0;
313         u64 total;
314
315         if (add_seen_fsid(fs_devices->fsid))
316                 return;
317
318         uuid_unparse(fs_devices->fsid, uuidbuf);
319         device = list_entry(fs_devices->devices.next, struct btrfs_device,
320                             dev_list);
321         if (device->label && device->label[0])
322                 printf("Label: '%s' ", device->label);
323         else
324                 printf("Label: none ");
325
326
327         total = device->total_devs;
328         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
329                (unsigned long long)total,
330                pretty_size(device->super_bytes_used));
331
332         list_sort(NULL, &fs_devices->devices, cmp_device_id);
333         list_for_each(cur, &fs_devices->devices) {
334                 device = list_entry(cur, struct btrfs_device, dev_list);
335
336                 printf("\tdevid %4llu size %s used %s path %s\n",
337                        (unsigned long long)device->devid,
338                        pretty_size(device->total_bytes),
339                        pretty_size(device->bytes_used), device->name);
340
341                 devs_found++;
342         }
343         if (devs_found < total) {
344                 printf("\t*** Some devices missing\n");
345         }
346         printf("\n");
347 }
348
349 /* adds up all the used spaces as reported by the space info ioctl
350  */
351 static u64 calc_used_bytes(struct btrfs_ioctl_space_args *si)
352 {
353         u64 ret = 0;
354         int i;
355         for (i = 0; i < si->total_spaces; i++)
356                 ret += si->spaces[i].used_bytes;
357         return ret;
358 }
359
360 static int print_one_fs(struct btrfs_ioctl_fs_info_args *fs_info,
361                 struct btrfs_ioctl_dev_info_args *dev_info,
362                 struct btrfs_ioctl_space_args *space_info,
363                 char *label, char *path)
364 {
365         int i;
366         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
367         struct btrfs_ioctl_dev_info_args *tmp_dev_info;
368         int ret;
369
370         ret = add_seen_fsid(fs_info->fsid);
371         if (ret == -EEXIST)
372                 return 0;
373         else if (ret)
374                 return ret;
375
376         uuid_unparse(fs_info->fsid, uuidbuf);
377         if (label && strlen(label))
378                 printf("Label: '%s' ", label);
379         else
380                 printf("Label: none ");
381
382         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
383                         fs_info->num_devices,
384                         pretty_size(calc_used_bytes(space_info)));
385
386         for (i = 0; i < fs_info->num_devices; i++) {
387                 tmp_dev_info = (struct btrfs_ioctl_dev_info_args *)&dev_info[i];
388                 printf("\tdevid %4llu size %s used %s path %s\n",
389                         tmp_dev_info->devid,
390                         pretty_size(tmp_dev_info->total_bytes),
391                         pretty_size(tmp_dev_info->bytes_used),
392                         tmp_dev_info->path);
393         }
394
395         printf("\n");
396         return 0;
397 }
398
399 /* This function checks if the given input parameter is
400  * an uuid or a path
401  * return -1: some error in the given input
402  * return 0: unknow input
403  * return 1: given input is uuid
404  * return 2: given input is path
405  */
406 static int check_arg_type(char *input)
407 {
408         uuid_t  out;
409         char path[PATH_MAX];
410
411         if (!input)
412                 return -EINVAL;
413
414         if (realpath(input, path)) {
415                 if (is_block_device(input) == 1)
416                         return BTRFS_ARG_BLKDEV;
417
418                 if (is_mount_point(input) == 1)
419                         return BTRFS_ARG_MNTPOINT;
420
421                 return BTRFS_ARG_UNKNOWN;
422         }
423
424         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
425                 !uuid_parse(input, out))
426                 return BTRFS_ARG_UUID;
427
428         return BTRFS_ARG_UNKNOWN;
429 }
430
431 static int btrfs_scan_kernel(void *search)
432 {
433         int ret = 0, fd;
434         FILE *f;
435         struct mntent *mnt;
436         struct btrfs_ioctl_fs_info_args fs_info_arg;
437         struct btrfs_ioctl_dev_info_args *dev_info_arg = NULL;
438         struct btrfs_ioctl_space_args *space_info_arg;
439         char label[BTRFS_LABEL_SIZE];
440
441         f = setmntent("/proc/self/mounts", "r");
442         if (f == NULL)
443                 return 1;
444
445         memset(label, 0, sizeof(label));
446         while ((mnt = getmntent(f)) != NULL) {
447                 if (strcmp(mnt->mnt_type, "btrfs"))
448                         continue;
449                 ret = get_fs_info(mnt->mnt_dir, &fs_info_arg,
450                                 &dev_info_arg);
451                 if (ret)
452                         goto out;
453
454                 if (get_label_mounted(mnt->mnt_dir, label)) {
455                         kfree(dev_info_arg);
456                         ret = 1;
457                         goto out;
458                 }
459                 if (search && !match_search_item_kernel(fs_info_arg.fsid,
460                                         mnt->mnt_dir, label, search)) {
461                         kfree(dev_info_arg);
462                         continue;
463                 }
464
465                 fd = open(mnt->mnt_dir, O_RDONLY);
466                 if ((fd != -1) && !get_df(fd, &space_info_arg)) {
467                         print_one_fs(&fs_info_arg, dev_info_arg,
468                                         space_info_arg, label, mnt->mnt_dir);
469                         kfree(space_info_arg);
470                         memset(label, 0, sizeof(label));
471                 }
472                 if (fd != -1)
473                         close(fd);
474                 kfree(dev_info_arg);
475                 if (search)
476                         ret = 0;
477         }
478         if (search)
479                 ret = 1;
480
481 out:
482         endmntent(f);
483         return ret;
484 }
485
486 static const char * const cmd_show_usage[] = {
487         "btrfs filesystem show [options] [<path>|<uuid>|<device>|label]",
488         "Show the structure of a filesystem",
489         "-d|--all-devices   show only disks under /dev containing btrfs filesystem",
490         "-m|--mounted       show only mounted btrfs",
491         "If no argument is given, structure of all present filesystems is shown.",
492         NULL
493 };
494
495 static int cmd_show(int argc, char **argv)
496 {
497         struct list_head *all_uuids;
498         struct btrfs_fs_devices *fs_devices;
499         struct list_head *cur_uuid;
500         char *search = NULL;
501         int ret;
502         int where = BTRFS_SCAN_LBLKID;
503         int type = 0;
504         char mp[BTRFS_PATH_NAME_MAX + 1];
505         char path[PATH_MAX];
506
507         while (1) {
508                 int long_index;
509                 static struct option long_options[] = {
510                         { "all-devices", no_argument, NULL, 'd'},
511                         { "mounted", no_argument, NULL, 'm'},
512                         { NULL, no_argument, NULL, 0 },
513                 };
514                 int c = getopt_long(argc, argv, "dm", long_options,
515                                         &long_index);
516                 if (c < 0)
517                         break;
518                 switch (c) {
519                 case 'd':
520                         where = BTRFS_SCAN_DEV;
521                         break;
522                 case 'm':
523                         where = BTRFS_SCAN_MOUNTED;
524                         break;
525                 default:
526                         usage(cmd_show_usage);
527                 }
528         }
529
530         if (check_argc_max(argc, optind + 1))
531                 usage(cmd_show_usage);
532
533         if (argc > optind) {
534                 search = argv[optind];
535                 if (strlen(search) == 0)
536                         usage(cmd_show_usage);
537                 type = check_arg_type(search);
538                 if (type == BTRFS_ARG_BLKDEV) {
539                         if (where == BTRFS_SCAN_DEV) {
540                                 /* we need to do this because
541                                  * legacy BTRFS_SCAN_DEV
542                                  * provides /dev/dm-x paths
543                                  */
544                                 if (realpath(search, path))
545                                         search = path;
546                         } else {
547                                 ret = get_btrfs_mount(search,
548                                                 mp, sizeof(mp));
549                                 if (!ret)
550                                         /* given block dev is mounted*/
551                                         search = mp;
552                                 else
553                                         goto devs_only;
554                         }
555                 }
556         }
557
558         if (where == BTRFS_SCAN_DEV)
559                 goto devs_only;
560
561         /* show mounted btrfs */
562         ret = btrfs_scan_kernel(search);
563         if (search && !ret)
564                 return 0;
565
566         /* shows mounted only */
567         if (where == BTRFS_SCAN_MOUNTED)
568                 goto out;
569
570 devs_only:
571         ret = scan_for_btrfs(where, !BTRFS_UPDATE_KERNEL);
572
573         if (ret) {
574                 fprintf(stderr, "ERROR: %d while scanning\n", ret);
575                 return 1;
576         }
577         
578         all_uuids = btrfs_scanned_uuids();
579         list_for_each(cur_uuid, all_uuids) {
580                 fs_devices = list_entry(cur_uuid, struct btrfs_fs_devices,
581                                         list);
582                 if (search && uuid_search(fs_devices, search) == 0)
583                         continue;
584
585                 print_one_uuid(fs_devices);
586         }
587
588 out:
589         printf("%s\n", BTRFS_BUILD_VERSION);
590         free_seen_fsid();
591         return 0;
592 }
593
594 static const char * const cmd_sync_usage[] = {
595         "btrfs filesystem sync <path>",
596         "Force a sync on a filesystem",
597         NULL
598 };
599
600 static int cmd_sync(int argc, char **argv)
601 {
602         int     fd, res, e;
603         char    *path;
604         DIR     *dirstream = NULL;
605
606         if (check_argc_exact(argc, 2))
607                 usage(cmd_sync_usage);
608
609         path = argv[1];
610
611         fd = open_file_or_dir(path, &dirstream);
612         if (fd < 0) {
613                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
614                 return 1;
615         }
616
617         printf("FSSync '%s'\n", path);
618         res = ioctl(fd, BTRFS_IOC_SYNC);
619         e = errno;
620         close_file_or_dir(fd, dirstream);
621         if( res < 0 ){
622                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
623                         path, strerror(e));
624                 return 1;
625         }
626
627         return 0;
628 }
629
630 static int parse_compress_type(char *s)
631 {
632         if (strcmp(optarg, "zlib") == 0)
633                 return BTRFS_COMPRESS_ZLIB;
634         else if (strcmp(optarg, "lzo") == 0)
635                 return BTRFS_COMPRESS_LZO;
636         else {
637                 fprintf(stderr, "Unknown compress type %s\n", s);
638                 exit(1);
639         };
640 }
641
642 static const char * const cmd_defrag_usage[] = {
643         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
644         "Defragment a file or a directory",
645         "",
646         "-v             be verbose",
647         "-r             defragment files recursively",
648         "-c[zlib,lzo]   compress the file while defragmenting",
649         "-f             flush data to disk immediately after defragmenting",
650         "-s start       defragment only from byte onward",
651         "-l len         defragment only up to len bytes",
652         "-t size        minimal size of file to be considered for defragmenting",
653         NULL
654 };
655
656 static int do_defrag(int fd, int fancy_ioctl,
657                 struct btrfs_ioctl_defrag_range_args *range)
658 {
659         int ret;
660
661         if (!fancy_ioctl)
662                 ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
663         else
664                 ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, range);
665
666         return ret;
667 }
668
669 static int defrag_global_fancy_ioctl;
670 static struct btrfs_ioctl_defrag_range_args defrag_global_range;
671 static int defrag_global_verbose;
672 static int defrag_global_errors;
673 static int defrag_callback(const char *fpath, const struct stat *sb,
674                 int typeflag, struct FTW *ftwbuf)
675 {
676         int ret = 0;
677         int e = 0;
678         int fd = 0;
679
680         if (typeflag == FTW_F) {
681                 if (defrag_global_verbose)
682                         printf("%s\n", fpath);
683                 fd = open(fpath, O_RDWR);
684                 e = errno;
685                 if (fd < 0)
686                         goto error;
687                 ret = do_defrag(fd, defrag_global_fancy_ioctl, &defrag_global_range);
688                 e = errno;
689                 close(fd);
690                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
691                         fprintf(stderr, "ERROR: defrag range ioctl not "
692                                 "supported in this kernel, please try "
693                                 "without any options.\n");
694                         defrag_global_errors++;
695                         return ENOTTY;
696                 }
697                 if (ret)
698                         goto error;
699         }
700         return 0;
701
702 error:
703         fprintf(stderr, "ERROR: defrag failed on %s - %s\n", fpath, strerror(e));
704         defrag_global_errors++;
705         return 0;
706 }
707
708 static int cmd_defrag(int argc, char **argv)
709 {
710         int fd;
711         int flush = 0;
712         u64 start = 0;
713         u64 len = (u64)-1;
714         u32 thresh = 0;
715         int i;
716         int recursive = 0;
717         int ret = 0;
718         struct btrfs_ioctl_defrag_range_args range;
719         int e = 0;
720         int compress_type = BTRFS_COMPRESS_NONE;
721         DIR *dirstream;
722
723         defrag_global_errors = 0;
724         defrag_global_verbose = 0;
725         defrag_global_errors = 0;
726         defrag_global_fancy_ioctl = 0;
727         optind = 1;
728         while(1) {
729                 int c = getopt(argc, argv, "vrc::fs:l:t:");
730                 if (c < 0)
731                         break;
732
733                 switch(c) {
734                 case 'c':
735                         compress_type = BTRFS_COMPRESS_ZLIB;
736                         if (optarg)
737                                 compress_type = parse_compress_type(optarg);
738                         defrag_global_fancy_ioctl = 1;
739                         break;
740                 case 'f':
741                         flush = 1;
742                         defrag_global_fancy_ioctl = 1;
743                         break;
744                 case 'v':
745                         defrag_global_verbose = 1;
746                         break;
747                 case 's':
748                         start = parse_size(optarg);
749                         defrag_global_fancy_ioctl = 1;
750                         break;
751                 case 'l':
752                         len = parse_size(optarg);
753                         defrag_global_fancy_ioctl = 1;
754                         break;
755                 case 't':
756                         thresh = parse_size(optarg);
757                         defrag_global_fancy_ioctl = 1;
758                         break;
759                 case 'r':
760                         recursive = 1;
761                         break;
762                 default:
763                         usage(cmd_defrag_usage);
764                 }
765         }
766
767         if (check_argc_min(argc - optind, 1))
768                 usage(cmd_defrag_usage);
769
770         memset(&defrag_global_range, 0, sizeof(range));
771         defrag_global_range.start = start;
772         defrag_global_range.len = len;
773         defrag_global_range.extent_thresh = thresh;
774         if (compress_type) {
775                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
776                 defrag_global_range.compress_type = compress_type;
777         }
778         if (flush)
779                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
780
781         for (i = optind; i < argc; i++) {
782                 dirstream = NULL;
783                 fd = open_file_or_dir(argv[i], &dirstream);
784                 if (fd < 0) {
785                         fprintf(stderr, "ERROR: failed to open %s - %s\n", argv[i],
786                                         strerror(errno));
787                         defrag_global_errors++;
788                         close_file_or_dir(fd, dirstream);
789                         continue;
790                 }
791                 if (recursive) {
792                         struct stat st;
793
794                         if (fstat(fd, &st)) {
795                                 fprintf(stderr, "ERROR: failed to stat %s - %s\n",
796                                                 argv[i], strerror(errno));
797                                 defrag_global_errors++;
798                                 close_file_or_dir(fd, dirstream);
799                                 continue;
800                         }
801                         if (S_ISDIR(st.st_mode)) {
802                                 ret = nftw(argv[i], defrag_callback, 10,
803                                                 FTW_MOUNT | FTW_PHYS);
804                                 if (ret == ENOTTY)
805                                         exit(1);
806                                 /* errors are handled in the callback */
807                                 ret = 0;
808                         } else {
809                                 if (defrag_global_verbose)
810                                         printf("%s\n", argv[i]);
811                                 ret = do_defrag(fd, defrag_global_fancy_ioctl,
812                                                 &defrag_global_range);
813                                 e = errno;
814                         }
815                 } else {
816                         if (defrag_global_verbose)
817                                 printf("%s\n", argv[i]);
818                         ret = do_defrag(fd, defrag_global_fancy_ioctl,
819                                         &defrag_global_range);
820                         e = errno;
821                 }
822                 close_file_or_dir(fd, dirstream);
823                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
824                         fprintf(stderr, "ERROR: defrag range ioctl not "
825                                 "supported in this kernel, please try "
826                                 "without any options.\n");
827                         defrag_global_errors++;
828                         break;
829                 }
830                 if (ret) {
831                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
832                                 argv[i], strerror(e));
833                         defrag_global_errors++;
834                 }
835         }
836         if (defrag_global_verbose)
837                 printf("%s\n", BTRFS_BUILD_VERSION);
838         if (defrag_global_errors)
839                 fprintf(stderr, "total %d failures\n", defrag_global_errors);
840
841         return !!defrag_global_errors;
842 }
843
844 static const char * const cmd_resize_usage[] = {
845         "btrfs filesystem resize [devid:][+/-]<newsize>[gkm]|[devid:]max <path>",
846         "Resize a filesystem",
847         "If 'max' is passed, the filesystem will occupy all available space",
848         "on the device 'devid'.",
849         NULL
850 };
851
852 static int cmd_resize(int argc, char **argv)
853 {
854         struct btrfs_ioctl_vol_args     args;
855         int     fd, res, len, e;
856         char    *amount, *path;
857         DIR     *dirstream = NULL;
858
859         if (check_argc_exact(argc, 3))
860                 usage(cmd_resize_usage);
861
862         amount = argv[1];
863         path = argv[2];
864
865         len = strlen(amount);
866         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
867                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
868                         amount);
869                 return 1;
870         }
871
872         fd = open_file_or_dir(path, &dirstream);
873         if (fd < 0) {
874                 fprintf(stderr, "ERROR: can't access to '%s'\n", path);
875                 return 1;
876         }
877
878         printf("Resize '%s' of '%s'\n", path, amount);
879         strncpy_null(args.name, amount);
880         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
881         e = errno;
882         close_file_or_dir(fd, dirstream);
883         if( res < 0 ){
884                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
885                         path, strerror(e));
886                 return 1;
887         }
888         return 0;
889 }
890
891 static const char * const cmd_label_usage[] = {
892         "btrfs filesystem label [<device>|<mount_point>] [<newlabel>]",
893         "Get or change the label of a filesystem",
894         "With one argument, get the label of filesystem on <device>.",
895         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
896         NULL
897 };
898
899 static int cmd_label(int argc, char **argv)
900 {
901         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
902                 usage(cmd_label_usage);
903
904         if (argc > 2) {
905                 return set_label(argv[1], argv[2]);
906         } else {
907                 char label[BTRFS_LABEL_SIZE];
908                 int ret;
909
910                 ret = get_label(argv[1], label);
911                 if (!ret)
912                         fprintf(stdout, "%s\n", label);
913
914                 return ret;
915         }
916 }
917
918 const struct cmd_group filesystem_cmd_group = {
919         filesystem_cmd_group_usage, NULL, {
920                 { "df", cmd_df, cmd_df_usage, NULL, 0 },
921                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
922                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
923                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
924                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
925                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
926                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
927                 NULL_CMD_STRUCT
928         }
929 };
930
931 int cmd_filesystem(int argc, char **argv)
932 {
933         return handle_command_group(&filesystem_cmd_group, argc, argv);
934 }