btrfs-progs: mkfs: Separate shrink from rootdir
[platform/upstream/btrfs-progs.git] / cmds-balance.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <getopt.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <errno.h>
27
28 #include "kerncompat.h"
29 #include "ctree.h"
30 #include "ioctl.h"
31 #include "volumes.h"
32
33 #include "commands.h"
34 #include "utils.h"
35 #include "help.h"
36
37 static const char * const balance_cmd_group_usage[] = {
38         "btrfs balance <command> [options] <path>",
39         "btrfs balance <path>",
40         NULL
41 };
42
43 static int parse_one_profile(const char *profile, u64 *flags)
44 {
45         if (!strcmp(profile, "raid0")) {
46                 *flags |= BTRFS_BLOCK_GROUP_RAID0;
47         } else if (!strcmp(profile, "raid1")) {
48                 *flags |= BTRFS_BLOCK_GROUP_RAID1;
49         } else if (!strcmp(profile, "raid10")) {
50                 *flags |= BTRFS_BLOCK_GROUP_RAID10;
51         } else if (!strcmp(profile, "raid5")) {
52                 *flags |= BTRFS_BLOCK_GROUP_RAID5;
53         } else if (!strcmp(profile, "raid6")) {
54                 *flags |= BTRFS_BLOCK_GROUP_RAID6;
55         } else if (!strcmp(profile, "dup")) {
56                 *flags |= BTRFS_BLOCK_GROUP_DUP;
57         } else if (!strcmp(profile, "single")) {
58                 *flags |= BTRFS_AVAIL_ALLOC_BIT_SINGLE;
59         } else {
60                 error("unknown profile: %s", profile);
61                 return 1;
62         }
63
64         return 0;
65 }
66
67 static int parse_profiles(char *profiles, u64 *flags)
68 {
69         char *this_char;
70         char *save_ptr = NULL; /* Satisfy static checkers */
71
72         for (this_char = strtok_r(profiles, "|", &save_ptr);
73              this_char != NULL;
74              this_char = strtok_r(NULL, "|", &save_ptr)) {
75                 if (parse_one_profile(this_char, flags))
76                         return 1;
77         }
78
79         return 0;
80 }
81
82 static int parse_u64(const char *str, u64 *result)
83 {
84         char *endptr;
85         u64 val;
86
87         val = strtoull(str, &endptr, 10);
88         if (*endptr)
89                 return 1;
90
91         *result = val;
92         return 0;
93 }
94
95 /*
96  * Parse range that's missing some part that can be implicit:
97  * a..b - exact range, a can be equal to b
98  * a..  - implicitly unbounded maximum (end == (u64)-1)
99  * ..b  - implicitly starting at 0
100  * a    - invalid; unclear semantics, use parse_u64 instead
101  *
102  * Returned values are u64, value validation and interpretation should be done
103  * by the caller.
104  */
105 static int parse_range(const char *range, u64 *start, u64 *end)
106 {
107         char *dots;
108         char *endptr;
109         const char *rest;
110         int skipped = 0;
111
112         dots = strstr(range, "..");
113         if (!dots)
114                 return 1;
115
116         rest = dots + 2;
117
118         if (!*rest) {
119                 *end = (u64)-1;
120                 skipped++;
121         } else {
122                 *end = strtoull(rest, &endptr, 10);
123                 if (*endptr)
124                         return 1;
125         }
126         if (dots == range) {
127                 *start = 0;
128                 skipped++;
129         } else {
130                 *start = strtoull(range, &endptr, 10);
131                 if (*endptr != 0 && *endptr != '.')
132                         return 1;
133         }
134
135         if (*start > *end) {
136                 error("range %llu..%llu doesn't make sense",
137                         (unsigned long long)*start,
138                         (unsigned long long)*end);
139                 return 1;
140         }
141
142         if (skipped <= 1)
143                 return 0;
144
145         return 1;
146 }
147
148 /*
149  * Parse range and check if start < end
150  */
151 static int parse_range_strict(const char *range, u64 *start, u64 *end)
152 {
153         if (parse_range(range, start, end) == 0) {
154                 if (*start >= *end) {
155                         error("range %llu..%llu not allowed",
156                                 (unsigned long long)*start,
157                                 (unsigned long long)*end);
158                         return 1;
159                 }
160                 return 0;
161         }
162
163         return 1;
164 }
165
166 /*
167  * Convert 64bit range to 32bit with boundary checks
168  */
169 static int range_to_u32(u64 start, u64 end, u32 *start32, u32 *end32)
170 {
171         if (start > (u32)-1)
172                 return 1;
173
174         if (end != (u64)-1 && end > (u32)-1)
175                 return 1;
176
177         *start32 = (u32)start;
178         *end32 = (u32)end;
179
180         return 0;
181 }
182
183 __attribute__ ((unused))
184 static int parse_range_u32(const char *range, u32 *start, u32 *end)
185 {
186         u64 tmp_start;
187         u64 tmp_end;
188
189         if (parse_range(range, &tmp_start, &tmp_end))
190                 return 1;
191
192         if (range_to_u32(tmp_start, tmp_end, start, end))
193                 return 1;
194
195         return 0;
196 }
197
198 __attribute__ ((unused))
199 static void print_range(u64 start, u64 end)
200 {
201         if (start)
202                 printf("%llu", (unsigned long long)start);
203         printf("..");
204         if (end != (u64)-1)
205                 printf("%llu", (unsigned long long)end);
206 }
207
208 __attribute__ ((unused))
209 static void print_range_u32(u32 start, u32 end)
210 {
211         if (start)
212                 printf("%u", start);
213         printf("..");
214         if (end != (u32)-1)
215                 printf("%u", end);
216 }
217
218 static int parse_filters(char *filters, struct btrfs_balance_args *args)
219 {
220         char *this_char;
221         char *value;
222         char *save_ptr = NULL; /* Satisfy static checkers */
223
224         if (!filters)
225                 return 0;
226
227         for (this_char = strtok_r(filters, ",", &save_ptr);
228              this_char != NULL;
229              this_char = strtok_r(NULL, ",", &save_ptr)) {
230                 if ((value = strchr(this_char, '=')) != NULL)
231                         *value++ = 0;
232                 if (!strcmp(this_char, "profiles")) {
233                         if (!value || !*value) {
234                                 error("the profiles filter requires an argument");
235                                 return 1;
236                         }
237                         if (parse_profiles(value, &args->profiles)) {
238                                 error("invalid profiles argument");
239                                 return 1;
240                         }
241                         args->flags |= BTRFS_BALANCE_ARGS_PROFILES;
242                 } else if (!strcmp(this_char, "usage")) {
243                         if (!value || !*value) {
244                                 error("the usage filter requires an argument");
245                                 return 1;
246                         }
247                         if (parse_u64(value, &args->usage)) {
248                                 if (parse_range_u32(value, &args->usage_min,
249                                                         &args->usage_max)) {
250                                         error("invalid usage argument: %s",
251                                                 value);
252                                         return 1;
253                                 }
254                                 if (args->usage_max > 100) {
255                                         error("invalid usage argument: %s",
256                                                 value);
257                                 }
258                                 args->flags &= ~BTRFS_BALANCE_ARGS_USAGE;
259                                 args->flags |= BTRFS_BALANCE_ARGS_USAGE_RANGE;
260                         } else {
261                                 if (args->usage > 100) {
262                                         error("invalid usage argument: %s",
263                                                 value);
264                                         return 1;
265                                 }
266                                 args->flags &= ~BTRFS_BALANCE_ARGS_USAGE_RANGE;
267                                 args->flags |= BTRFS_BALANCE_ARGS_USAGE;
268                         }
269                         args->flags |= BTRFS_BALANCE_ARGS_USAGE;
270                 } else if (!strcmp(this_char, "devid")) {
271                         if (!value || !*value) {
272                                 error("the devid filter requires an argument");
273                                 return 1;
274                         }
275                         if (parse_u64(value, &args->devid) || args->devid == 0) {
276                                 error("invalid devid argument: %s", value);
277                                 return 1;
278                         }
279                         args->flags |= BTRFS_BALANCE_ARGS_DEVID;
280                 } else if (!strcmp(this_char, "drange")) {
281                         if (!value || !*value) {
282                                 error("the drange filter requires an argument");
283                                 return 1;
284                         }
285                         if (parse_range_strict(value, &args->pstart, &args->pend)) {
286                                 error("invalid drange argument");
287                                 return 1;
288                         }
289                         args->flags |= BTRFS_BALANCE_ARGS_DRANGE;
290                 } else if (!strcmp(this_char, "vrange")) {
291                         if (!value || !*value) {
292                                 error("the vrange filter requires an argument");
293                                 return 1;
294                         }
295                         if (parse_range_strict(value, &args->vstart, &args->vend)) {
296                                 error("invalid vrange argument");
297                                 return 1;
298                         }
299                         args->flags |= BTRFS_BALANCE_ARGS_VRANGE;
300                 } else if (!strcmp(this_char, "convert")) {
301                         if (!value || !*value) {
302                                 error("the convert option requires an argument");
303                                 return 1;
304                         }
305                         if (parse_one_profile(value, &args->target)) {
306                                 error("invalid convert argument");
307                                 return 1;
308                         }
309                         args->flags |= BTRFS_BALANCE_ARGS_CONVERT;
310                 } else if (!strcmp(this_char, "soft")) {
311                         args->flags |= BTRFS_BALANCE_ARGS_SOFT;
312                 } else if (!strcmp(this_char, "limit")) {
313                         if (!value || !*value) {
314                                 error("the limit filter requires an argument");
315                                 return 1;
316                         }
317                         if (parse_u64(value, &args->limit)) {
318                                 if (parse_range_u32(value, &args->limit_min,
319                                                         &args->limit_max)) {
320                                         error("Invalid limit argument: %s",
321                                                value);
322                                         return 1;
323                                 }
324                                 args->flags &= ~BTRFS_BALANCE_ARGS_LIMIT;
325                                 args->flags |= BTRFS_BALANCE_ARGS_LIMIT_RANGE;
326                         } else {
327                                 args->flags &= ~BTRFS_BALANCE_ARGS_LIMIT_RANGE;
328                                 args->flags |= BTRFS_BALANCE_ARGS_LIMIT;
329                         }
330                 } else if (!strcmp(this_char, "stripes")) {
331                         if (!value || !*value) {
332                                 error("the stripes filter requires an argument");
333                                 return 1;
334                         }
335                         if (parse_range_u32(value, &args->stripes_min,
336                                             &args->stripes_max)) {
337                                 error("invalid stripes argument");
338                                 return 1;
339                         }
340                         args->flags |= BTRFS_BALANCE_ARGS_STRIPES_RANGE;
341                 } else {
342                         error("unrecognized balance option: %s", this_char);
343                         return 1;
344                 }
345         }
346
347         return 0;
348 }
349
350 static void dump_balance_args(struct btrfs_balance_args *args)
351 {
352         if (args->flags & BTRFS_BALANCE_ARGS_CONVERT) {
353                 printf("converting, target=%llu, soft is %s",
354                        (unsigned long long)args->target,
355                        (args->flags & BTRFS_BALANCE_ARGS_SOFT) ? "on" : "off");
356         } else {
357                 printf("balancing");
358         }
359
360         if (args->flags & BTRFS_BALANCE_ARGS_PROFILES)
361                 printf(", profiles=%llu", (unsigned long long)args->profiles);
362         if (args->flags & BTRFS_BALANCE_ARGS_USAGE)
363                 printf(", usage=%llu", (unsigned long long)args->usage);
364         if (args->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) {
365                 printf(", usage=");
366                 print_range_u32(args->usage_min, args->usage_max);
367         }
368         if (args->flags & BTRFS_BALANCE_ARGS_DEVID)
369                 printf(", devid=%llu", (unsigned long long)args->devid);
370         if (args->flags & BTRFS_BALANCE_ARGS_DRANGE)
371                 printf(", drange=%llu..%llu",
372                        (unsigned long long)args->pstart,
373                        (unsigned long long)args->pend);
374         if (args->flags & BTRFS_BALANCE_ARGS_VRANGE)
375                 printf(", vrange=%llu..%llu",
376                        (unsigned long long)args->vstart,
377                        (unsigned long long)args->vend);
378         if (args->flags & BTRFS_BALANCE_ARGS_LIMIT)
379                 printf(", limit=%llu", (unsigned long long)args->limit);
380         if (args->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE) {
381                 printf(", limit=");
382                 print_range_u32(args->limit_min, args->limit_max);
383         }
384         if (args->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) {
385                 printf(", stripes=");
386                 print_range_u32(args->stripes_min, args->stripes_max);
387         }
388
389         printf("\n");
390 }
391
392 static void dump_ioctl_balance_args(struct btrfs_ioctl_balance_args *args)
393 {
394         printf("Dumping filters: flags 0x%llx, state 0x%llx, force is %s\n",
395                (unsigned long long)args->flags, (unsigned long long)args->state,
396                (args->flags & BTRFS_BALANCE_FORCE) ? "on" : "off");
397         if (args->flags & BTRFS_BALANCE_DATA) {
398                 printf("  DATA (flags 0x%llx): ",
399                        (unsigned long long)args->data.flags);
400                 dump_balance_args(&args->data);
401         }
402         if (args->flags & BTRFS_BALANCE_METADATA) {
403                 printf("  METADATA (flags 0x%llx): ",
404                        (unsigned long long)args->meta.flags);
405                 dump_balance_args(&args->meta);
406         }
407         if (args->flags & BTRFS_BALANCE_SYSTEM) {
408                 printf("  SYSTEM (flags 0x%llx): ",
409                        (unsigned long long)args->sys.flags);
410                 dump_balance_args(&args->sys);
411         }
412 }
413
414 static int do_balance_v1(int fd)
415 {
416         struct btrfs_ioctl_vol_args args;
417         int ret;
418
419         memset(&args, 0, sizeof(args));
420         ret = ioctl(fd, BTRFS_IOC_BALANCE, &args);
421         return ret;
422 }
423
424 enum {
425         BALANCE_START_FILTERS = 1 << 0,
426         BALANCE_START_NOWARN  = 1 << 1
427 };
428
429 static int do_balance(const char *path, struct btrfs_ioctl_balance_args *args,
430                       unsigned flags)
431 {
432         int fd;
433         int ret;
434         DIR *dirstream = NULL;
435
436         fd = btrfs_open_dir(path, &dirstream, 1);
437         if (fd < 0)
438                 return 1;
439
440         if (!(flags & BALANCE_START_FILTERS) && !(flags & BALANCE_START_NOWARN)) {
441                 int delay = 10;
442
443                 printf("WARNING:\n\n");
444                 printf("\tFull balance without filters requested. This operation is very\n");
445                 printf("\tintense and takes potentially very long. It is recommended to\n");
446                 printf("\tuse the balance filters to narrow down the scope of balance.\n");
447                 printf("\tUse 'btrfs balance start --full-balance' option to skip this\n");
448                 printf("\twarning. The operation will start in %d seconds.\n", delay);
449                 printf("\tUse Ctrl-C to stop it.\n");
450                 while (delay) {
451                         printf("%2d", delay--);
452                         fflush(stdout);
453                         sleep(1);
454                 }
455                 printf("\nStarting balance without any filters.\n");
456         }
457
458         ret = ioctl(fd, BTRFS_IOC_BALANCE_V2, args);
459         if (ret < 0) {
460                 /*
461                  * older kernels don't have the new balance ioctl, try the
462                  * old one.  But, the old one doesn't know any filters, so
463                  * don't fall back if they tried to use the fancy new things
464                  */
465                 if (errno == ENOTTY && !(flags & BALANCE_START_FILTERS)) {
466                         ret = do_balance_v1(fd);
467                         if (ret == 0)
468                                 goto out;
469                 }
470
471                 if (errno == ECANCELED) {
472                         if (args->state & BTRFS_BALANCE_STATE_PAUSE_REQ)
473                                 fprintf(stderr, "balance paused by user\n");
474                         if (args->state & BTRFS_BALANCE_STATE_CANCEL_REQ)
475                                 fprintf(stderr, "balance canceled by user\n");
476                         ret = 0;
477                 } else {
478                         error("error during balancing '%s': %s", path,
479                                         strerror(errno));
480                         if (errno != EINPROGRESS)
481                                 fprintf(stderr,
482                         "There may be more info in syslog - try dmesg | tail\n");
483                         ret = 1;
484                 }
485         } else {
486                 printf("Done, had to relocate %llu out of %llu chunks\n",
487                        (unsigned long long)args->stat.completed,
488                        (unsigned long long)args->stat.considered);
489                 ret = 0;
490         }
491
492 out:
493         close_file_or_dir(fd, dirstream);
494         return ret;
495 }
496
497 static const char * const cmd_balance_start_usage[] = {
498         "btrfs balance start [options] <path>",
499         "Balance chunks across the devices",
500         "Balance and/or convert (change allocation profile of) chunks that",
501         "passed all filters in a comma-separated list of filters for a",
502         "particular chunk type.  If filter list is not given balance all",
503         "chunks of that type.  In case none of the -d, -m or -s options is",
504         "given balance all chunks in a filesystem. This is potentially",
505         "long operation and the user is warned before this start, with",
506         "a delay to stop it.",
507         "",
508         "-d[filters]    act on data chunks",
509         "-m[filters]    act on metadata chunks",
510         "-s[filters]    act on system chunks (only under -f)",
511         "-v             be verbose",
512         "-f             force reducing of metadata integrity",
513         "--full-balance do not print warning and do not delay start",
514         "--background|--bg",
515         "               run the balance as a background process",
516         NULL
517 };
518
519 static int cmd_balance_start(int argc, char **argv)
520 {
521         struct btrfs_ioctl_balance_args args;
522         struct btrfs_balance_args *ptrs[] = { &args.data, &args.sys,
523                                                 &args.meta, NULL };
524         int force = 0;
525         int verbose = 0;
526         int background = 0;
527         unsigned start_flags = 0;
528         int i;
529
530         memset(&args, 0, sizeof(args));
531
532         while (1) {
533                 enum { GETOPT_VAL_FULL_BALANCE = 256,
534                         GETOPT_VAL_BACKGROUND = 257 };
535                 static const struct option longopts[] = {
536                         { "data", optional_argument, NULL, 'd'},
537                         { "metadata", optional_argument, NULL, 'm' },
538                         { "system", optional_argument, NULL, 's' },
539                         { "force", no_argument, NULL, 'f' },
540                         { "verbose", no_argument, NULL, 'v' },
541                         { "full-balance", no_argument, NULL,
542                                 GETOPT_VAL_FULL_BALANCE },
543                         { "background", no_argument, NULL,
544                                 GETOPT_VAL_BACKGROUND },
545                         { "bg", no_argument, NULL, GETOPT_VAL_BACKGROUND },
546                         { NULL, 0, NULL, 0 }
547                 };
548
549                 int opt = getopt_long(argc, argv, "d::s::m::fv", longopts, NULL);
550                 if (opt < 0)
551                         break;
552
553                 switch (opt) {
554                 case 'd':
555                         start_flags |= BALANCE_START_FILTERS;
556                         args.flags |= BTRFS_BALANCE_DATA;
557
558                         if (parse_filters(optarg, &args.data))
559                                 return 1;
560                         break;
561                 case 's':
562                         start_flags |= BALANCE_START_FILTERS;
563                         args.flags |= BTRFS_BALANCE_SYSTEM;
564
565                         if (parse_filters(optarg, &args.sys))
566                                 return 1;
567                         break;
568                 case 'm':
569                         start_flags |= BALANCE_START_FILTERS;
570                         args.flags |= BTRFS_BALANCE_METADATA;
571
572                         if (parse_filters(optarg, &args.meta))
573                                 return 1;
574                         break;
575                 case 'f':
576                         force = 1;
577                         break;
578                 case 'v':
579                         verbose = 1;
580                         break;
581                 case GETOPT_VAL_FULL_BALANCE:
582                         start_flags |= BALANCE_START_NOWARN;
583                         break;
584                 case GETOPT_VAL_BACKGROUND:
585                         background = 1;
586                         break;
587                 default:
588                         usage(cmd_balance_start_usage);
589                 }
590         }
591
592         if (check_argc_exact(argc - optind, 1))
593                 usage(cmd_balance_start_usage);
594
595         /*
596          * allow -s only under --force, otherwise do with system chunks
597          * the same thing we were ordered to do with meta chunks
598          */
599         if (args.flags & BTRFS_BALANCE_SYSTEM) {
600                 if (!force) {
601                         error(
602                             "Refusing to explicitly operate on system chunks.\n"
603                             "Pass --force if you really want to do that.");
604                         return 1;
605                 }
606         } else if (args.flags & BTRFS_BALANCE_METADATA) {
607                 args.flags |= BTRFS_BALANCE_SYSTEM;
608                 memcpy(&args.sys, &args.meta,
609                         sizeof(struct btrfs_balance_args));
610         }
611
612         if (!(start_flags & BALANCE_START_FILTERS)) {
613                 /* relocate everything - no filters */
614                 args.flags |= BTRFS_BALANCE_TYPE_MASK;
615         }
616
617         /* drange makes sense only when devid is set */
618         for (i = 0; ptrs[i]; i++) {
619                 if ((ptrs[i]->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
620                     !(ptrs[i]->flags & BTRFS_BALANCE_ARGS_DEVID)) {
621                         error("drange filter must be used with devid filter");
622                         return 1;
623                 }
624         }
625
626         /* soft makes sense only when convert for corresponding type is set */
627         for (i = 0; ptrs[i]; i++) {
628                 if ((ptrs[i]->flags & BTRFS_BALANCE_ARGS_SOFT) &&
629                     !(ptrs[i]->flags & BTRFS_BALANCE_ARGS_CONVERT)) {
630                         error("'soft' option can be used only when converting profiles");
631                         return 1;
632                 }
633         }
634
635         if (force)
636                 args.flags |= BTRFS_BALANCE_FORCE;
637         if (verbose)
638                 dump_ioctl_balance_args(&args);
639         if (background) {
640                 switch (fork()) {
641                 case (-1):
642                         error("unable to fork to run balance in background");
643                         return 1;
644                 case (0):
645                         setsid();
646                         switch(fork()) {
647                         case (-1):
648                                 error(
649                                 "unable to fork to run balance in background");
650                                 exit(1);
651                         case (0):
652                                 /*
653                                  * Read the return value to silence compiler
654                                  * warning. Change to / should succeed and
655                                  * we're not in a security-sensitive context.
656                                  */
657                                 i = chdir("/");
658                                 close(0);
659                                 close(1);
660                                 close(2);
661                                 open("/dev/null", O_RDONLY);
662                                 open("/dev/null", O_WRONLY);
663                                 open("/dev/null", O_WRONLY);
664                                 break;
665                         default:
666                                 exit(0);
667                         }
668                         break;
669                 default:
670                         exit(0);
671                 }
672         }
673
674         return do_balance(argv[optind], &args, start_flags);
675 }
676
677 static const char * const cmd_balance_pause_usage[] = {
678         "btrfs balance pause <path>",
679         "Pause running balance",
680         NULL
681 };
682
683 static int cmd_balance_pause(int argc, char **argv)
684 {
685         const char *path;
686         int fd;
687         int ret;
688         DIR *dirstream = NULL;
689
690         clean_args_no_options(argc, argv, cmd_balance_pause_usage);
691
692         if (check_argc_exact(argc - optind, 1))
693                 usage(cmd_balance_pause_usage);
694
695         path = argv[optind];
696
697         fd = btrfs_open_dir(path, &dirstream, 1);
698         if (fd < 0)
699                 return 1;
700
701         ret = ioctl(fd, BTRFS_IOC_BALANCE_CTL, BTRFS_BALANCE_CTL_PAUSE);
702         if (ret < 0) {
703                 error("balance pause on '%s' failed: %s", path,
704                         (errno == ENOTCONN) ? "Not running" : strerror(errno));
705                 if (errno == ENOTCONN)
706                         ret = 2;
707                 else
708                         ret = 1;
709         }
710
711         close_file_or_dir(fd, dirstream);
712         return ret;
713 }
714
715 static const char * const cmd_balance_cancel_usage[] = {
716         "btrfs balance cancel <path>",
717         "Cancel running or paused balance",
718         NULL
719 };
720
721 static int cmd_balance_cancel(int argc, char **argv)
722 {
723         const char *path;
724         int fd;
725         int ret;
726         DIR *dirstream = NULL;
727
728         clean_args_no_options(argc, argv, cmd_balance_cancel_usage);
729
730         if (check_argc_exact(argc - optind, 1))
731                 usage(cmd_balance_cancel_usage);
732
733         path = argv[optind];
734
735         fd = btrfs_open_dir(path, &dirstream, 1);
736         if (fd < 0)
737                 return 1;
738
739         ret = ioctl(fd, BTRFS_IOC_BALANCE_CTL, BTRFS_BALANCE_CTL_CANCEL);
740         if (ret < 0) {
741                 error("balance cancel on '%s' failed: %s", path,
742                         (errno == ENOTCONN) ? "Not in progress" : strerror(errno));
743                 if (errno == ENOTCONN)
744                         ret = 2;
745                 else
746                         ret = 1;
747         }
748
749         close_file_or_dir(fd, dirstream);
750         return ret;
751 }
752
753 static const char * const cmd_balance_resume_usage[] = {
754         "btrfs balance resume <path>",
755         "Resume interrupted balance",
756         NULL
757 };
758
759 static int cmd_balance_resume(int argc, char **argv)
760 {
761         struct btrfs_ioctl_balance_args args;
762         const char *path;
763         DIR *dirstream = NULL;
764         int fd;
765         int ret;
766
767         clean_args_no_options(argc, argv, cmd_balance_resume_usage);
768
769         if (check_argc_exact(argc - optind, 1))
770                 usage(cmd_balance_resume_usage);
771
772         path = argv[optind];
773
774         fd = btrfs_open_dir(path, &dirstream, 1);
775         if (fd < 0)
776                 return 1;
777
778         memset(&args, 0, sizeof(args));
779         args.flags |= BTRFS_BALANCE_RESUME;
780
781         ret = ioctl(fd, BTRFS_IOC_BALANCE_V2, &args);
782         if (ret < 0) {
783                 if (errno == ECANCELED) {
784                         if (args.state & BTRFS_BALANCE_STATE_PAUSE_REQ)
785                                 fprintf(stderr, "balance paused by user\n");
786                         if (args.state & BTRFS_BALANCE_STATE_CANCEL_REQ)
787                                 fprintf(stderr, "balance canceled by user\n");
788                 } else if (errno == ENOTCONN || errno == EINPROGRESS) {
789                         error("balance resume on '%s' failed: %s", path,
790                                 (errno == ENOTCONN) ? "Not in progress" :
791                                                   "Already running");
792                         if (errno == ENOTCONN)
793                                 ret = 2;
794                         else
795                                 ret = 1;
796                 } else {
797                         error("error during balancing '%s': %s\n"
798                           "There may be more info in syslog - try dmesg | tail",
799                                 path, strerror(errno));
800                         ret = 1;
801                 }
802         } else {
803                 printf("Done, had to relocate %llu out of %llu chunks\n",
804                        (unsigned long long)args.stat.completed,
805                        (unsigned long long)args.stat.considered);
806         }
807
808         close_file_or_dir(fd, dirstream);
809         return ret;
810 }
811
812 static const char * const cmd_balance_status_usage[] = {
813         "btrfs balance status [-v] <path>",
814         "Show status of running or paused balance",
815         "",
816         "-v     be verbose",
817         NULL
818 };
819
820 /* Checks the status of the balance if any
821  * return codes:
822  *   2 : Error failed to know if there is any pending balance
823  *   1 : Successful to know status of a pending balance
824  *   0 : When there is no pending balance or completed
825  */
826 static int cmd_balance_status(int argc, char **argv)
827 {
828         struct btrfs_ioctl_balance_args args;
829         const char *path;
830         DIR *dirstream = NULL;
831         int fd;
832         int verbose = 0;
833         int ret;
834
835         while (1) {
836                 int opt;
837                 static const struct option longopts[] = {
838                         { "verbose", no_argument, NULL, 'v' },
839                         { NULL, 0, NULL, 0 }
840                 };
841
842                 opt = getopt_long(argc, argv, "v", longopts, NULL);
843                 if (opt < 0)
844                         break;
845
846                 switch (opt) {
847                 case 'v':
848                         verbose = 1;
849                         break;
850                 default:
851                         usage(cmd_balance_status_usage);
852                 }
853         }
854
855         if (check_argc_exact(argc - optind, 1))
856                 usage(cmd_balance_status_usage);
857
858         path = argv[optind];
859
860         fd = btrfs_open_dir(path, &dirstream, 1);
861         if (fd < 0)
862                 return 2;
863
864         ret = ioctl(fd, BTRFS_IOC_BALANCE_PROGRESS, &args);
865         if (ret < 0) {
866                 if (errno == ENOTCONN) {
867                         printf("No balance found on '%s'\n", path);
868                         ret = 0;
869                         goto out;
870                 }
871                 error("balance status on '%s' failed: %s", path, strerror(errno));
872                 ret = 2;
873                 goto out;
874         }
875
876         if (args.state & BTRFS_BALANCE_STATE_RUNNING) {
877                 printf("Balance on '%s' is running", path);
878                 if (args.state & BTRFS_BALANCE_STATE_CANCEL_REQ)
879                         printf(", cancel requested\n");
880                 else if (args.state & BTRFS_BALANCE_STATE_PAUSE_REQ)
881                         printf(", pause requested\n");
882                 else
883                         printf("\n");
884         } else {
885                 printf("Balance on '%s' is paused\n", path);
886         }
887
888         printf("%llu out of about %llu chunks balanced (%llu considered), "
889                "%3.f%% left\n", (unsigned long long)args.stat.completed,
890                (unsigned long long)args.stat.expected,
891                (unsigned long long)args.stat.considered,
892                100 * (1 - (float)args.stat.completed/args.stat.expected));
893
894         if (verbose)
895                 dump_ioctl_balance_args(&args);
896
897         ret = 1;
898 out:
899         close_file_or_dir(fd, dirstream);
900         return ret;
901 }
902
903 static int cmd_balance_full(int argc, char **argv)
904 {
905         struct btrfs_ioctl_balance_args args;
906
907         memset(&args, 0, sizeof(args));
908         args.flags |= BTRFS_BALANCE_TYPE_MASK;
909
910         return do_balance(argv[1], &args, BALANCE_START_NOWARN);
911 }
912
913 static const char balance_cmd_group_info[] =
914 "balance data across devices, or change block groups using filters";
915
916 const struct cmd_group balance_cmd_group = {
917         balance_cmd_group_usage, balance_cmd_group_info, {
918                 { "start", cmd_balance_start, cmd_balance_start_usage, NULL, 0 },
919                 { "pause", cmd_balance_pause, cmd_balance_pause_usage, NULL, 0 },
920                 { "cancel", cmd_balance_cancel, cmd_balance_cancel_usage, NULL, 0 },
921                 { "resume", cmd_balance_resume, cmd_balance_resume_usage, NULL, 0 },
922                 { "status", cmd_balance_status, cmd_balance_status_usage, NULL, 0 },
923                 { "--full-balance", cmd_balance_full, NULL, NULL, 1 },
924                 NULL_CMD_STRUCT
925         }
926 };
927
928 int cmd_balance(int argc, char **argv)
929 {
930         if (argc == 2 && strcmp("start", argv[1]) != 0) {
931                 /* old 'btrfs filesystem balance <path>' syntax */
932                 struct btrfs_ioctl_balance_args args;
933
934                 memset(&args, 0, sizeof(args));
935                 args.flags |= BTRFS_BALANCE_TYPE_MASK;
936
937                 return do_balance(argv[1], &args, 0);
938         }
939
940         return handle_command_group(&balance_cmd_group, argc, argv);
941 }