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