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