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