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