btrfs-progs: balance: use errno directly
[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         optind = 1;
526         while (1) {
527                 enum { GETOPT_VAL_FULL_BALANCE = 256 };
528                 static const struct option longopts[] = {
529                         { "data", optional_argument, NULL, 'd'},
530                         { "metadata", optional_argument, NULL, 'm' },
531                         { "system", optional_argument, NULL, 's' },
532                         { "force", no_argument, NULL, 'f' },
533                         { "verbose", no_argument, NULL, 'v' },
534                         { "full-balance", no_argument, NULL,
535                                 GETOPT_VAL_FULL_BALANCE },
536                         { NULL, 0, NULL, 0 }
537                 };
538
539                 int opt = getopt_long(argc, argv, "d::s::m::fv", longopts, NULL);
540                 if (opt < 0)
541                         break;
542
543                 switch (opt) {
544                 case 'd':
545                         start_flags |= BALANCE_START_FILTERS;
546                         args.flags |= BTRFS_BALANCE_DATA;
547
548                         if (parse_filters(optarg, &args.data))
549                                 return 1;
550                         break;
551                 case 's':
552                         start_flags |= BALANCE_START_FILTERS;
553                         args.flags |= BTRFS_BALANCE_SYSTEM;
554
555                         if (parse_filters(optarg, &args.sys))
556                                 return 1;
557                         break;
558                 case 'm':
559                         start_flags |= BALANCE_START_FILTERS;
560                         args.flags |= BTRFS_BALANCE_METADATA;
561
562                         if (parse_filters(optarg, &args.meta))
563                                 return 1;
564                         break;
565                 case 'f':
566                         force = 1;
567                         break;
568                 case 'v':
569                         verbose = 1;
570                         break;
571                 case GETOPT_VAL_FULL_BALANCE:
572                         start_flags |= BALANCE_START_NOWARN;
573                         break;
574                 default:
575                         usage(cmd_balance_start_usage);
576                 }
577         }
578
579         if (check_argc_exact(argc - optind, 1))
580                 usage(cmd_balance_start_usage);
581
582         /*
583          * allow -s only under --force, otherwise do with system chunks
584          * the same thing we were ordered to do with meta chunks
585          */
586         if (args.flags & BTRFS_BALANCE_SYSTEM) {
587                 if (!force) {
588                         error(
589                             "Refusing to explicitly operate on system chunks.\n"
590                             "Pass --force if you really want to do that.");
591                         return 1;
592                 }
593         } else if (args.flags & BTRFS_BALANCE_METADATA) {
594                 args.flags |= BTRFS_BALANCE_SYSTEM;
595                 memcpy(&args.sys, &args.meta,
596                         sizeof(struct btrfs_balance_args));
597         }
598
599         if (!(start_flags & BALANCE_START_FILTERS)) {
600                 /* relocate everything - no filters */
601                 args.flags |= BTRFS_BALANCE_TYPE_MASK;
602         }
603
604         /* drange makes sense only when devid is set */
605         for (i = 0; ptrs[i]; i++) {
606                 if ((ptrs[i]->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
607                     !(ptrs[i]->flags & BTRFS_BALANCE_ARGS_DEVID)) {
608                         error("drange filter must be used with devid filter");
609                         return 1;
610                 }
611         }
612
613         /* soft makes sense only when convert for corresponding type is set */
614         for (i = 0; ptrs[i]; i++) {
615                 if ((ptrs[i]->flags & BTRFS_BALANCE_ARGS_SOFT) &&
616                     !(ptrs[i]->flags & BTRFS_BALANCE_ARGS_CONVERT)) {
617                         error("'soft' option can be used only when converting profiles");
618                         return 1;
619                 }
620         }
621
622         if (force)
623                 args.flags |= BTRFS_BALANCE_FORCE;
624         if (verbose)
625                 dump_ioctl_balance_args(&args);
626
627         return do_balance(argv[optind], &args, start_flags);
628 }
629
630 static const char * const cmd_balance_pause_usage[] = {
631         "btrfs balance pause <path>",
632         "Pause running balance",
633         NULL
634 };
635
636 static int cmd_balance_pause(int argc, char **argv)
637 {
638         const char *path;
639         int fd;
640         int ret;
641         DIR *dirstream = NULL;
642
643         clean_args_no_options(argc, argv, cmd_balance_pause_usage);
644
645         if (check_argc_exact(argc - optind, 1))
646                 usage(cmd_balance_pause_usage);
647
648         path = argv[optind];
649
650         fd = btrfs_open_dir(path, &dirstream, 1);
651         if (fd < 0)
652                 return 1;
653
654         ret = ioctl(fd, BTRFS_IOC_BALANCE_CTL, BTRFS_BALANCE_CTL_PAUSE);
655         if (ret < 0) {
656                 error("balance pause on '%s' failed: %s", path,
657                         (errno == ENOTCONN) ? "Not running" : strerror(errno));
658                 if (errno == ENOTCONN)
659                         ret = 2;
660                 else
661                         ret = 1;
662         }
663
664         close_file_or_dir(fd, dirstream);
665         return ret;
666 }
667
668 static const char * const cmd_balance_cancel_usage[] = {
669         "btrfs balance cancel <path>",
670         "Cancel running or paused balance",
671         NULL
672 };
673
674 static int cmd_balance_cancel(int argc, char **argv)
675 {
676         const char *path;
677         int fd;
678         int ret;
679         DIR *dirstream = NULL;
680
681         clean_args_no_options(argc, argv, cmd_balance_cancel_usage);
682
683         if (check_argc_exact(argc - optind, 1))
684                 usage(cmd_balance_cancel_usage);
685
686         path = argv[optind];
687
688         fd = btrfs_open_dir(path, &dirstream, 1);
689         if (fd < 0)
690                 return 1;
691
692         ret = ioctl(fd, BTRFS_IOC_BALANCE_CTL, BTRFS_BALANCE_CTL_CANCEL);
693         if (ret < 0) {
694                 error("balance cancel on '%s' failed: %s", path,
695                         (errno == ENOTCONN) ? "Not in progress" : strerror(errno));
696                 if (errno == ENOTCONN)
697                         ret = 2;
698                 else
699                         ret = 1;
700         }
701
702         close_file_or_dir(fd, dirstream);
703         return ret;
704 }
705
706 static const char * const cmd_balance_resume_usage[] = {
707         "btrfs balance resume <path>",
708         "Resume interrupted balance",
709         NULL
710 };
711
712 static int cmd_balance_resume(int argc, char **argv)
713 {
714         struct btrfs_ioctl_balance_args args;
715         const char *path;
716         DIR *dirstream = NULL;
717         int fd;
718         int ret;
719
720         clean_args_no_options(argc, argv, cmd_balance_resume_usage);
721
722         if (check_argc_exact(argc - optind, 1))
723                 usage(cmd_balance_resume_usage);
724
725         path = argv[optind];
726
727         fd = btrfs_open_dir(path, &dirstream, 1);
728         if (fd < 0)
729                 return 1;
730
731         memset(&args, 0, sizeof(args));
732         args.flags |= BTRFS_BALANCE_RESUME;
733
734         ret = ioctl(fd, BTRFS_IOC_BALANCE_V2, &args);
735         if (ret < 0) {
736                 if (errno == ECANCELED) {
737                         if (args.state & BTRFS_BALANCE_STATE_PAUSE_REQ)
738                                 fprintf(stderr, "balance paused by user\n");
739                         if (args.state & BTRFS_BALANCE_STATE_CANCEL_REQ)
740                                 fprintf(stderr, "balance canceled by user\n");
741                 } else if (errno == ENOTCONN || errno == EINPROGRESS) {
742                         error("balance resume on '%s' failed: %s", path,
743                                 (errno == ENOTCONN) ? "Not in progress" :
744                                                   "Already running");
745                         if (errno == ENOTCONN)
746                                 ret = 2;
747                         else
748                                 ret = 1;
749                 } else {
750                         error("error during balancing '%s': %s\n"
751                           "There may be more info in syslog - try dmesg | tail",
752                                 path, strerror(errno));
753                         ret = 1;
754                 }
755         } else {
756                 printf("Done, had to relocate %llu out of %llu chunks\n",
757                        (unsigned long long)args.stat.completed,
758                        (unsigned long long)args.stat.considered);
759         }
760
761         close_file_or_dir(fd, dirstream);
762         return ret;
763 }
764
765 static const char * const cmd_balance_status_usage[] = {
766         "btrfs balance status [-v] <path>",
767         "Show status of running or paused balance",
768         "",
769         "-v     be verbose",
770         NULL
771 };
772
773 /* Checks the status of the balance if any
774  * return codes:
775  *   2 : Error failed to know if there is any pending balance
776  *   1 : Successful to know status of a pending balance
777  *   0 : When there is no pending balance or completed
778  */
779 static int cmd_balance_status(int argc, char **argv)
780 {
781         struct btrfs_ioctl_balance_args args;
782         const char *path;
783         DIR *dirstream = NULL;
784         int fd;
785         int verbose = 0;
786         int ret;
787
788         optind = 1;
789         while (1) {
790                 int opt;
791                 static const struct option longopts[] = {
792                         { "verbose", no_argument, NULL, 'v' },
793                         { NULL, 0, NULL, 0 }
794                 };
795
796                 opt = getopt_long(argc, argv, "v", longopts, NULL);
797                 if (opt < 0)
798                         break;
799
800                 switch (opt) {
801                 case 'v':
802                         verbose = 1;
803                         break;
804                 default:
805                         usage(cmd_balance_status_usage);
806                 }
807         }
808
809         if (check_argc_exact(argc - optind, 1))
810                 usage(cmd_balance_status_usage);
811
812         path = argv[optind];
813
814         fd = btrfs_open_dir(path, &dirstream, 1);
815         if (fd < 0)
816                 return 2;
817
818         ret = ioctl(fd, BTRFS_IOC_BALANCE_PROGRESS, &args);
819         if (ret < 0) {
820                 if (errno == ENOTCONN) {
821                         printf("No balance found on '%s'\n", path);
822                         ret = 0;
823                         goto out;
824                 }
825                 error("balance status on '%s' failed: %s", path, strerror(errno));
826                 ret = 2;
827                 goto out;
828         }
829
830         if (args.state & BTRFS_BALANCE_STATE_RUNNING) {
831                 printf("Balance on '%s' is running", path);
832                 if (args.state & BTRFS_BALANCE_STATE_CANCEL_REQ)
833                         printf(", cancel requested\n");
834                 else if (args.state & BTRFS_BALANCE_STATE_PAUSE_REQ)
835                         printf(", pause requested\n");
836                 else
837                         printf("\n");
838         } else {
839                 printf("Balance on '%s' is paused\n", path);
840         }
841
842         printf("%llu out of about %llu chunks balanced (%llu considered), "
843                "%3.f%% left\n", (unsigned long long)args.stat.completed,
844                (unsigned long long)args.stat.expected,
845                (unsigned long long)args.stat.considered,
846                100 * (1 - (float)args.stat.completed/args.stat.expected));
847
848         if (verbose)
849                 dump_ioctl_balance_args(&args);
850
851         ret = 1;
852 out:
853         close_file_or_dir(fd, dirstream);
854         return ret;
855 }
856
857 static int cmd_balance_full(int argc, char **argv)
858 {
859         struct btrfs_ioctl_balance_args args;
860
861         memset(&args, 0, sizeof(args));
862         args.flags |= BTRFS_BALANCE_TYPE_MASK;
863
864         return do_balance(argv[1], &args, BALANCE_START_NOWARN);
865 }
866
867 static const char balance_cmd_group_info[] =
868 "balance data across devices, or change block groups using filters";
869
870 const struct cmd_group balance_cmd_group = {
871         balance_cmd_group_usage, balance_cmd_group_info, {
872                 { "start", cmd_balance_start, cmd_balance_start_usage, NULL, 0 },
873                 { "pause", cmd_balance_pause, cmd_balance_pause_usage, NULL, 0 },
874                 { "cancel", cmd_balance_cancel, cmd_balance_cancel_usage, NULL, 0 },
875                 { "resume", cmd_balance_resume, cmd_balance_resume_usage, NULL, 0 },
876                 { "status", cmd_balance_status, cmd_balance_status_usage, NULL, 0 },
877                 { "--full-balance", cmd_balance_full, NULL, NULL, 1 },
878                 NULL_CMD_STRUCT
879         }
880 };
881
882 int cmd_balance(int argc, char **argv)
883 {
884         if (argc == 2 && strcmp("start", argv[1]) != 0) {
885                 /* old 'btrfs filesystem balance <path>' syntax */
886                 struct btrfs_ioctl_balance_args args;
887
888                 memset(&args, 0, sizeof(args));
889                 args.flags |= BTRFS_BALANCE_TYPE_MASK;
890
891                 return do_balance(argv[1], &args, 0);
892         }
893
894         return handle_command_group(&balance_cmd_group, argc, argv);
895 }