btrfs-progs: lblkid wouldn't find non mapper path input
[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                 ret = -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         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
368         struct btrfs_ioctl_dev_info_args *tmp_dev_info;
369         int ret;
370
371         ret = add_seen_fsid(fs_info->fsid);
372         if (ret == -EEXIST)
373                 return 0;
374         else if (ret)
375                 return ret;
376
377         uuid_unparse(fs_info->fsid, uuidbuf);
378         if (label && strlen(label))
379                 printf("Label: '%s' ", label);
380         else
381                 printf("Label: none ");
382
383         printf(" uuid: %s\n\tTotal devices %llu FS bytes used %s\n", uuidbuf,
384                         fs_info->num_devices,
385                         pretty_size(calc_used_bytes(space_info)));
386
387         for (i = 0; i < fs_info->num_devices; i++) {
388                 tmp_dev_info = (struct btrfs_ioctl_dev_info_args *)&dev_info[i];
389                 printf("\tdevid %4llu size %s used %s path %s\n",
390                         tmp_dev_info->devid,
391                         pretty_size(tmp_dev_info->total_bytes),
392                         pretty_size(tmp_dev_info->bytes_used),
393                         tmp_dev_info->path);
394         }
395
396         printf("\n");
397         return 0;
398 }
399
400 /* This function checks if the given input parameter is
401  * an uuid or a path
402  * return -1: some error in the given input
403  * return 0: unknow input
404  * return 1: given input is uuid
405  * return 2: given input is path
406  */
407 static int check_arg_type(char *input)
408 {
409         uuid_t  out;
410         char path[PATH_MAX];
411
412         if (!input)
413                 return -EINVAL;
414
415         if (realpath(input, path)) {
416                 if (is_block_device(input) == 1)
417                         return BTRFS_ARG_BLKDEV;
418
419                 if (is_mount_point(input) == 1)
420                         return BTRFS_ARG_MNTPOINT;
421
422                 return BTRFS_ARG_UNKNOWN;
423         }
424
425         if (strlen(input) == (BTRFS_UUID_UNPARSED_SIZE - 1) &&
426                 !uuid_parse(input, out))
427                 return BTRFS_ARG_UUID;
428
429         return BTRFS_ARG_UNKNOWN;
430 }
431
432 static int btrfs_scan_kernel(void *search)
433 {
434         int ret = 0, fd;
435         FILE *f;
436         struct mntent *mnt;
437         struct btrfs_ioctl_fs_info_args fs_info_arg;
438         struct btrfs_ioctl_dev_info_args *dev_info_arg = NULL;
439         struct btrfs_ioctl_space_args *space_info_arg;
440         char label[BTRFS_LABEL_SIZE];
441
442         f = setmntent("/proc/self/mounts", "r");
443         if (f == NULL)
444                 return 1;
445
446         memset(label, 0, sizeof(label));
447         while ((mnt = getmntent(f)) != NULL) {
448                 if (strcmp(mnt->mnt_type, "btrfs"))
449                         continue;
450                 ret = get_fs_info(mnt->mnt_dir, &fs_info_arg,
451                                 &dev_info_arg);
452                 if (ret)
453                         goto out;
454
455                 if (get_label_mounted(mnt->mnt_dir, label)) {
456                         kfree(dev_info_arg);
457                         ret = 1;
458                         goto out;
459                 }
460                 if (search && !match_search_item_kernel(fs_info_arg.fsid,
461                                         mnt->mnt_dir, label, search)) {
462                         kfree(dev_info_arg);
463                         continue;
464                 }
465
466                 fd = open(mnt->mnt_dir, O_RDONLY);
467                 if ((fd != -1) && !get_df(fd, &space_info_arg)) {
468                         print_one_fs(&fs_info_arg, dev_info_arg,
469                                         space_info_arg, label, mnt->mnt_dir);
470                         kfree(space_info_arg);
471                         memset(label, 0, sizeof(label));
472                 }
473                 if (fd != -1)
474                         close(fd);
475                 kfree(dev_info_arg);
476                 if (search)
477                         ret = 0;
478         }
479         if (search)
480                 ret = 1;
481
482 out:
483         endmntent(f);
484         return ret;
485 }
486
487 static int dev_to_fsid(char *dev, __u8 *fsid)
488 {
489         struct btrfs_super_block *disk_super;
490         char *buf;
491         int ret;
492         int fd;
493
494         buf = malloc(4096);
495         if (!buf)
496                 return -ENOMEM;
497
498         fd = open(dev, O_RDONLY);
499         if (fd < 0) {
500                 ret = -errno;
501                 free(buf);
502                 return ret;
503         }
504
505         disk_super = (struct btrfs_super_block *)buf;
506         ret = btrfs_read_dev_super(fd, disk_super,
507                         BTRFS_SUPER_INFO_OFFSET);
508         if (ret)
509                 goto out;
510
511         memcpy(fsid, disk_super->fsid, BTRFS_FSID_SIZE);
512         ret = 0;
513
514 out:
515         close(fd);
516         free(buf);
517         return ret;
518 }
519
520 static const char * const cmd_show_usage[] = {
521         "btrfs filesystem show [options] [<path>|<uuid>|<device>|label]",
522         "Show the structure of a filesystem",
523         "-d|--all-devices   show only disks under /dev containing btrfs filesystem",
524         "-m|--mounted       show only mounted btrfs",
525         "If no argument is given, structure of all present filesystems is shown.",
526         NULL
527 };
528
529 static int cmd_show(int argc, char **argv)
530 {
531         struct list_head *all_uuids;
532         struct btrfs_fs_devices *fs_devices;
533         struct list_head *cur_uuid;
534         char *search = NULL;
535         int ret;
536         int where = BTRFS_SCAN_LBLKID;
537         int type = 0;
538         char mp[BTRFS_PATH_NAME_MAX + 1];
539         char path[PATH_MAX];
540         __u8 fsid[BTRFS_FSID_SIZE];
541         char uuid_buf[37];
542
543         while (1) {
544                 int long_index;
545                 static struct option long_options[] = {
546                         { "all-devices", no_argument, NULL, 'd'},
547                         { "mounted", no_argument, NULL, 'm'},
548                         { NULL, no_argument, NULL, 0 },
549                 };
550                 int c = getopt_long(argc, argv, "dm", long_options,
551                                         &long_index);
552                 if (c < 0)
553                         break;
554                 switch (c) {
555                 case 'd':
556                         where = BTRFS_SCAN_DEV;
557                         break;
558                 case 'm':
559                         where = BTRFS_SCAN_MOUNTED;
560                         break;
561                 default:
562                         usage(cmd_show_usage);
563                 }
564         }
565
566         if (check_argc_max(argc, optind + 1))
567                 usage(cmd_show_usage);
568
569         if (argc > optind) {
570                 search = argv[optind];
571                 if (strlen(search) == 0)
572                         usage(cmd_show_usage);
573                 type = check_arg_type(search);
574                 /*
575                  * needs spl handling if input arg is block dev
576                  * And if input arg is mount-point just print it
577                  * right away
578                  */
579                 if (type == BTRFS_ARG_BLKDEV) {
580                         if (where == BTRFS_SCAN_DEV) {
581                                 /* we need to do this because
582                                  * legacy BTRFS_SCAN_DEV
583                                  * provides /dev/dm-x paths
584                                  */
585                                 if (realpath(search, path))
586                                         search = path;
587                         } else {
588                                 ret = get_btrfs_mount(search,
589                                                 mp, sizeof(mp));
590                                 if (!ret) {
591                                         /* given block dev is mounted*/
592                                         search = mp;
593                                         type = BTRFS_ARG_MNTPOINT;
594                                 } else {
595                                         ret = dev_to_fsid(search, fsid);
596                                         if (ret) {
597                                                 fprintf(stderr,
598                                                         "ERROR: No btrfs on %s\n",
599                                                         search);
600                                                 return 1;
601                                         }
602                                         uuid_unparse(fsid, uuid_buf);
603                                         search = uuid_buf;
604                                         type = BTRFS_ARG_UUID;
605                                         goto devs_only;
606                                 }
607                         }
608                 }
609         }
610
611         if (where == BTRFS_SCAN_DEV)
612                 goto devs_only;
613
614         /* show mounted btrfs */
615         ret = btrfs_scan_kernel(search);
616         if (search && !ret)
617                 return 0;
618
619         /* shows mounted only */
620         if (where == BTRFS_SCAN_MOUNTED)
621                 goto out;
622
623 devs_only:
624         ret = scan_for_btrfs(where, !BTRFS_UPDATE_KERNEL);
625
626         if (ret) {
627                 fprintf(stderr, "ERROR: %d while scanning\n", ret);
628                 return 1;
629         }
630         
631         all_uuids = btrfs_scanned_uuids();
632         list_for_each(cur_uuid, all_uuids) {
633                 fs_devices = list_entry(cur_uuid, struct btrfs_fs_devices,
634                                         list);
635                 if (search && uuid_search(fs_devices, search) == 0)
636                         continue;
637
638                 print_one_uuid(fs_devices);
639         }
640
641 out:
642         printf("%s\n", BTRFS_BUILD_VERSION);
643         free_seen_fsid();
644         return 0;
645 }
646
647 static const char * const cmd_sync_usage[] = {
648         "btrfs filesystem sync <path>",
649         "Force a sync on a filesystem",
650         NULL
651 };
652
653 static int cmd_sync(int argc, char **argv)
654 {
655         int     fd, res, e;
656         char    *path;
657         DIR     *dirstream = NULL;
658
659         if (check_argc_exact(argc, 2))
660                 usage(cmd_sync_usage);
661
662         path = argv[1];
663
664         fd = open_file_or_dir(path, &dirstream);
665         if (fd < 0) {
666                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
667                 return 1;
668         }
669
670         printf("FSSync '%s'\n", path);
671         res = ioctl(fd, BTRFS_IOC_SYNC);
672         e = errno;
673         close_file_or_dir(fd, dirstream);
674         if( res < 0 ){
675                 fprintf(stderr, "ERROR: unable to fs-syncing '%s' - %s\n", 
676                         path, strerror(e));
677                 return 1;
678         }
679
680         return 0;
681 }
682
683 static int parse_compress_type(char *s)
684 {
685         if (strcmp(optarg, "zlib") == 0)
686                 return BTRFS_COMPRESS_ZLIB;
687         else if (strcmp(optarg, "lzo") == 0)
688                 return BTRFS_COMPRESS_LZO;
689         else {
690                 fprintf(stderr, "Unknown compress type %s\n", s);
691                 exit(1);
692         };
693 }
694
695 static const char * const cmd_defrag_usage[] = {
696         "btrfs filesystem defragment [options] <file>|<dir> [<file>|<dir>...]",
697         "Defragment a file or a directory",
698         "",
699         "-v             be verbose",
700         "-r             defragment files recursively",
701         "-c[zlib,lzo]   compress the file while defragmenting",
702         "-f             flush data to disk immediately after defragmenting",
703         "-s start       defragment only from byte onward",
704         "-l len         defragment only up to len bytes",
705         "-t size        minimal size of file to be considered for defragmenting",
706         NULL
707 };
708
709 static int do_defrag(int fd, int fancy_ioctl,
710                 struct btrfs_ioctl_defrag_range_args *range)
711 {
712         int ret;
713
714         if (!fancy_ioctl)
715                 ret = ioctl(fd, BTRFS_IOC_DEFRAG, NULL);
716         else
717                 ret = ioctl(fd, BTRFS_IOC_DEFRAG_RANGE, range);
718
719         return ret;
720 }
721
722 static int defrag_global_fancy_ioctl;
723 static struct btrfs_ioctl_defrag_range_args defrag_global_range;
724 static int defrag_global_verbose;
725 static int defrag_global_errors;
726 static int defrag_callback(const char *fpath, const struct stat *sb,
727                 int typeflag, struct FTW *ftwbuf)
728 {
729         int ret = 0;
730         int e = 0;
731         int fd = 0;
732
733         if ((typeflag == FTW_F) && S_ISREG(sb->st_mode)) {
734                 if (defrag_global_verbose)
735                         printf("%s\n", fpath);
736                 fd = open(fpath, O_RDWR);
737                 e = errno;
738                 if (fd < 0)
739                         goto error;
740                 ret = do_defrag(fd, defrag_global_fancy_ioctl, &defrag_global_range);
741                 e = errno;
742                 close(fd);
743                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
744                         fprintf(stderr, "ERROR: defrag range ioctl not "
745                                 "supported in this kernel, please try "
746                                 "without any options.\n");
747                         defrag_global_errors++;
748                         return ENOTTY;
749                 }
750                 if (ret)
751                         goto error;
752         }
753         return 0;
754
755 error:
756         fprintf(stderr, "ERROR: defrag failed on %s - %s\n", fpath, strerror(e));
757         defrag_global_errors++;
758         return 0;
759 }
760
761 static int cmd_defrag(int argc, char **argv)
762 {
763         int fd;
764         int flush = 0;
765         u64 start = 0;
766         u64 len = (u64)-1;
767         u32 thresh = 0;
768         int i;
769         int recursive = 0;
770         int ret = 0;
771         struct btrfs_ioctl_defrag_range_args range;
772         int e = 0;
773         int compress_type = BTRFS_COMPRESS_NONE;
774         DIR *dirstream;
775
776         defrag_global_errors = 0;
777         defrag_global_verbose = 0;
778         defrag_global_errors = 0;
779         defrag_global_fancy_ioctl = 0;
780         optind = 1;
781         while(1) {
782                 int c = getopt(argc, argv, "vrc::fs:l:t:");
783                 if (c < 0)
784                         break;
785
786                 switch(c) {
787                 case 'c':
788                         compress_type = BTRFS_COMPRESS_ZLIB;
789                         if (optarg)
790                                 compress_type = parse_compress_type(optarg);
791                         defrag_global_fancy_ioctl = 1;
792                         break;
793                 case 'f':
794                         flush = 1;
795                         defrag_global_fancy_ioctl = 1;
796                         break;
797                 case 'v':
798                         defrag_global_verbose = 1;
799                         break;
800                 case 's':
801                         start = parse_size(optarg);
802                         defrag_global_fancy_ioctl = 1;
803                         break;
804                 case 'l':
805                         len = parse_size(optarg);
806                         defrag_global_fancy_ioctl = 1;
807                         break;
808                 case 't':
809                         thresh = parse_size(optarg);
810                         defrag_global_fancy_ioctl = 1;
811                         break;
812                 case 'r':
813                         recursive = 1;
814                         break;
815                 default:
816                         usage(cmd_defrag_usage);
817                 }
818         }
819
820         if (check_argc_min(argc - optind, 1))
821                 usage(cmd_defrag_usage);
822
823         memset(&defrag_global_range, 0, sizeof(range));
824         defrag_global_range.start = start;
825         defrag_global_range.len = len;
826         defrag_global_range.extent_thresh = thresh;
827         if (compress_type) {
828                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_COMPRESS;
829                 defrag_global_range.compress_type = compress_type;
830         }
831         if (flush)
832                 defrag_global_range.flags |= BTRFS_DEFRAG_RANGE_START_IO;
833
834         for (i = optind; i < argc; i++) {
835                 struct stat st;
836
837                 dirstream = NULL;
838                 fd = open_file_or_dir(argv[i], &dirstream);
839                 if (fd < 0) {
840                         fprintf(stderr, "ERROR: failed to open %s - %s\n", argv[i],
841                                         strerror(errno));
842                         defrag_global_errors++;
843                         close_file_or_dir(fd, dirstream);
844                         continue;
845                 }
846                 if (fstat(fd, &st)) {
847                         fprintf(stderr, "ERROR: failed to stat %s - %s\n",
848                                         argv[i], strerror(errno));
849                         defrag_global_errors++;
850                         close_file_or_dir(fd, dirstream);
851                         continue;
852                 }
853                 if (!(S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))) {
854                         fprintf(stderr,
855                             "ERROR: %s is not a directory or a regular file\n",
856                             argv[i]);
857                         defrag_global_errors++;
858                         close_file_or_dir(fd, dirstream);
859                         continue;
860                 }
861                 if (recursive) {
862                         if (S_ISDIR(st.st_mode)) {
863                                 ret = nftw(argv[i], defrag_callback, 10,
864                                                 FTW_MOUNT | FTW_PHYS);
865                                 if (ret == ENOTTY)
866                                         exit(1);
867                                 /* errors are handled in the callback */
868                                 ret = 0;
869                         } else {
870                                 if (defrag_global_verbose)
871                                         printf("%s\n", argv[i]);
872                                 ret = do_defrag(fd, defrag_global_fancy_ioctl,
873                                                 &defrag_global_range);
874                                 e = errno;
875                         }
876                 } else {
877                         if (defrag_global_verbose)
878                                 printf("%s\n", argv[i]);
879                         ret = do_defrag(fd, defrag_global_fancy_ioctl,
880                                         &defrag_global_range);
881                         e = errno;
882                 }
883                 close_file_or_dir(fd, dirstream);
884                 if (ret && e == ENOTTY && defrag_global_fancy_ioctl) {
885                         fprintf(stderr, "ERROR: defrag range ioctl not "
886                                 "supported in this kernel, please try "
887                                 "without any options.\n");
888                         defrag_global_errors++;
889                         break;
890                 }
891                 if (ret) {
892                         fprintf(stderr, "ERROR: defrag failed on %s - %s\n",
893                                 argv[i], strerror(e));
894                         defrag_global_errors++;
895                 }
896         }
897         if (defrag_global_verbose)
898                 printf("%s\n", BTRFS_BUILD_VERSION);
899         if (defrag_global_errors)
900                 fprintf(stderr, "total %d failures\n", defrag_global_errors);
901
902         return !!defrag_global_errors;
903 }
904
905 static const char * const cmd_resize_usage[] = {
906         "btrfs filesystem resize [devid:][+/-]<newsize>[gkm]|[devid:]max <path>",
907         "Resize a filesystem",
908         "If 'max' is passed, the filesystem will occupy all available space",
909         "on the device 'devid'.",
910         NULL
911 };
912
913 static int cmd_resize(int argc, char **argv)
914 {
915         struct btrfs_ioctl_vol_args     args;
916         int     fd, res, len, e;
917         char    *amount, *path;
918         DIR     *dirstream = NULL;
919
920         if (check_argc_exact(argc, 3))
921                 usage(cmd_resize_usage);
922
923         amount = argv[1];
924         path = argv[2];
925
926         len = strlen(amount);
927         if (len == 0 || len >= BTRFS_VOL_NAME_MAX) {
928                 fprintf(stderr, "ERROR: size value too long ('%s)\n",
929                         amount);
930                 return 1;
931         }
932
933         fd = open_file_or_dir(path, &dirstream);
934         if (fd < 0) {
935                 fprintf(stderr, "ERROR: can't access '%s'\n", path);
936                 return 1;
937         }
938
939         printf("Resize '%s' of '%s'\n", path, amount);
940         strncpy_null(args.name, amount);
941         res = ioctl(fd, BTRFS_IOC_RESIZE, &args);
942         e = errno;
943         close_file_or_dir(fd, dirstream);
944         if( res < 0 ){
945                 fprintf(stderr, "ERROR: unable to resize '%s' - %s\n", 
946                         path, strerror(e));
947                 return 1;
948         }
949         return 0;
950 }
951
952 static const char * const cmd_label_usage[] = {
953         "btrfs filesystem label [<device>|<mount_point>] [<newlabel>]",
954         "Get or change the label of a filesystem",
955         "With one argument, get the label of filesystem on <device>.",
956         "If <newlabel> is passed, set the filesystem label to <newlabel>.",
957         NULL
958 };
959
960 static int cmd_label(int argc, char **argv)
961 {
962         if (check_argc_min(argc, 2) || check_argc_max(argc, 3))
963                 usage(cmd_label_usage);
964
965         if (argc > 2) {
966                 return set_label(argv[1], argv[2]);
967         } else {
968                 char label[BTRFS_LABEL_SIZE];
969                 int ret;
970
971                 ret = get_label(argv[1], label);
972                 if (!ret)
973                         fprintf(stdout, "%s\n", label);
974
975                 return ret;
976         }
977 }
978
979 const struct cmd_group filesystem_cmd_group = {
980         filesystem_cmd_group_usage, NULL, {
981                 { "df", cmd_df, cmd_df_usage, NULL, 0 },
982                 { "show", cmd_show, cmd_show_usage, NULL, 0 },
983                 { "sync", cmd_sync, cmd_sync_usage, NULL, 0 },
984                 { "defragment", cmd_defrag, cmd_defrag_usage, NULL, 0 },
985                 { "balance", cmd_balance, NULL, &balance_cmd_group, 1 },
986                 { "resize", cmd_resize, cmd_resize_usage, NULL, 0 },
987                 { "label", cmd_label, cmd_label_usage, NULL, 0 },
988                 NULL_CMD_STRUCT
989         }
990 };
991
992 int cmd_filesystem(int argc, char **argv)
993 {
994         return handle_command_group(&filesystem_cmd_group, argc, argv);
995 }