btrfs-progs: fix memory leaks in error path
[platform/upstream/btrfs-progs.git] / cmds-scrub.c
1 /*
2  * Copyright (C) 2011 STRATO.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include "kerncompat.h"
20
21 #include <sys/ioctl.h>
22 #include <sys/wait.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <sys/syscall.h>
28 #include <poll.h>
29 #include <sys/file.h>
30 #include <uuid/uuid.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <pthread.h>
34 #include <ctype.h>
35 #include <signal.h>
36 #include <stdarg.h>
37 #include <limits.h>
38
39 #include "ctree.h"
40 #include "ioctl.h"
41 #include "utils.h"
42 #include "volumes.h"
43 #include "disk-io.h"
44
45 #include "commands.h"
46
47 static const char * const scrub_cmd_group_usage[] = {
48         "btrfs scrub <command> [options] <path>|<device>",
49         NULL
50 };
51
52 #define SCRUB_DATA_FILE "/var/lib/btrfs/scrub.status"
53 #define SCRUB_PROGRESS_SOCKET_PATH "/var/lib/btrfs/scrub.progress"
54 #define SCRUB_FILE_VERSION_PREFIX "scrub status"
55 #define SCRUB_FILE_VERSION "1"
56
57 struct scrub_stats {
58         time_t t_start;
59         time_t t_resumed;
60         u64 duration;
61         u64 finished;
62         u64 canceled;
63         int in_progress;
64 };
65
66 /* TBD: replace with #include "linux/ioprio.h" in some years */
67 #if !defined (IOPRIO_H)
68 #define IOPRIO_WHO_PROCESS 1
69 #define IOPRIO_CLASS_SHIFT 13
70 #define IOPRIO_PRIO_VALUE(class, data) \
71                 (((class) << IOPRIO_CLASS_SHIFT) | (data))
72 #define IOPRIO_CLASS_IDLE 3
73 #endif
74
75 struct scrub_progress {
76         struct btrfs_ioctl_scrub_args scrub_args;
77         int fd;
78         int ret;
79         int skip;
80         struct scrub_stats stats;
81         struct scrub_file_record *resumed;
82         int ioctl_errno;
83         pthread_mutex_t progress_mutex;
84         int ioprio_class;
85         int ioprio_classdata;
86 };
87
88 struct scrub_file_record {
89         u8 fsid[BTRFS_FSID_SIZE];
90         u64 devid;
91         struct scrub_stats stats;
92         struct btrfs_scrub_progress p;
93 };
94
95 struct scrub_progress_cycle {
96         int fdmnt;
97         int prg_fd;
98         int do_record;
99         struct btrfs_ioctl_fs_info_args *fi;
100         struct scrub_progress *progress;
101         struct scrub_progress *shared_progress;
102         pthread_mutex_t *write_mutex;
103 };
104
105 struct scrub_fs_stat {
106         struct btrfs_scrub_progress p;
107         struct scrub_stats s;
108         int i;
109 };
110
111 static void print_scrub_full(struct btrfs_scrub_progress *sp)
112 {
113         printf("\tdata_extents_scrubbed: %lld\n", sp->data_extents_scrubbed);
114         printf("\ttree_extents_scrubbed: %lld\n", sp->tree_extents_scrubbed);
115         printf("\tdata_bytes_scrubbed: %lld\n", sp->data_bytes_scrubbed);
116         printf("\ttree_bytes_scrubbed: %lld\n", sp->tree_bytes_scrubbed);
117         printf("\tread_errors: %lld\n", sp->read_errors);
118         printf("\tcsum_errors: %lld\n", sp->csum_errors);
119         printf("\tverify_errors: %lld\n", sp->verify_errors);
120         printf("\tno_csum: %lld\n", sp->no_csum);
121         printf("\tcsum_discards: %lld\n", sp->csum_discards);
122         printf("\tsuper_errors: %lld\n", sp->super_errors);
123         printf("\tmalloc_errors: %lld\n", sp->malloc_errors);
124         printf("\tuncorrectable_errors: %lld\n", sp->uncorrectable_errors);
125         printf("\tunverified_errors: %lld\n", sp->unverified_errors);
126         printf("\tcorrected_errors: %lld\n", sp->corrected_errors);
127         printf("\tlast_physical: %lld\n", sp->last_physical);
128 }
129
130 #define ERR(test, ...) do {                     \
131         if (test)                               \
132                 fprintf(stderr, __VA_ARGS__);   \
133 } while (0)
134
135 #define PRINT_SCRUB_ERROR(test, desc) do {      \
136         if (test)                               \
137                 printf(" %s=%llu", desc, test); \
138 } while (0)
139
140 static void print_scrub_summary(struct btrfs_scrub_progress *p)
141 {
142         u64 err_cnt;
143         u64 err_cnt2;
144
145         err_cnt = p->read_errors +
146                         p->csum_errors +
147                         p->verify_errors +
148                         p->super_errors;
149
150         err_cnt2 = p->corrected_errors + p->uncorrectable_errors;
151
152         if (p->malloc_errors)
153                 printf("*** WARNING: memory allocation failed while scrubbing. "
154                        "results may be inaccurate\n");
155
156         printf("\ttotal bytes scrubbed: %s with %llu errors\n",
157                 pretty_size(p->data_bytes_scrubbed + p->tree_bytes_scrubbed),
158                 max(err_cnt, err_cnt2));
159
160         if (err_cnt || err_cnt2) {
161                 printf("\terror details:");
162                 PRINT_SCRUB_ERROR(p->read_errors, "read");
163                 PRINT_SCRUB_ERROR(p->super_errors, "super");
164                 PRINT_SCRUB_ERROR(p->verify_errors, "verify");
165                 PRINT_SCRUB_ERROR(p->csum_errors, "csum");
166                 printf("\n");
167                 printf("\tcorrected errors: %llu, uncorrectable errors: %llu, "
168                         "unverified errors: %llu\n", p->corrected_errors,
169                         p->uncorrectable_errors, p->unverified_errors);
170         }
171 }
172
173 #define _SCRUB_FS_STAT(p, name, fs_stat) do {   \
174         fs_stat->p.name += p->name;             \
175 } while (0)
176
177 #define _SCRUB_FS_STAT_MIN(ss, name, fs_stat)   \
178 do {                                            \
179         if (fs_stat->s.name > ss->name) {       \
180                 fs_stat->s.name = ss->name;     \
181         }                                       \
182 } while (0)
183
184 #define _SCRUB_FS_STAT_ZMIN(ss, name, fs_stat)                  \
185 do {                                                            \
186         if (!fs_stat->s.name || fs_stat->s.name > ss->name) {   \
187                 fs_stat->s.name = ss->name;                     \
188         }                                                       \
189 } while (0)
190
191 #define _SCRUB_FS_STAT_ZMAX(ss, name, fs_stat)                          \
192 do {                                                                    \
193         if (!(fs_stat)->s.name || (fs_stat)->s.name < (ss)->name) {     \
194                 (fs_stat)->s.name = (ss)->name;                         \
195         }                                                               \
196 } while (0)
197
198 static void add_to_fs_stat(struct btrfs_scrub_progress *p,
199                                 struct scrub_stats *ss,
200                                 struct scrub_fs_stat *fs_stat)
201 {
202         _SCRUB_FS_STAT(p, data_extents_scrubbed, fs_stat);
203         _SCRUB_FS_STAT(p, tree_extents_scrubbed, fs_stat);
204         _SCRUB_FS_STAT(p, data_bytes_scrubbed, fs_stat);
205         _SCRUB_FS_STAT(p, tree_bytes_scrubbed, fs_stat);
206         _SCRUB_FS_STAT(p, read_errors, fs_stat);
207         _SCRUB_FS_STAT(p, csum_errors, fs_stat);
208         _SCRUB_FS_STAT(p, verify_errors, fs_stat);
209         _SCRUB_FS_STAT(p, no_csum, fs_stat);
210         _SCRUB_FS_STAT(p, csum_discards, fs_stat);
211         _SCRUB_FS_STAT(p, super_errors, fs_stat);
212         _SCRUB_FS_STAT(p, malloc_errors, fs_stat);
213         _SCRUB_FS_STAT(p, uncorrectable_errors, fs_stat);
214         _SCRUB_FS_STAT(p, corrected_errors, fs_stat);
215         _SCRUB_FS_STAT(p, last_physical, fs_stat);
216         _SCRUB_FS_STAT_ZMIN(ss, t_start, fs_stat);
217         _SCRUB_FS_STAT_ZMIN(ss, t_resumed, fs_stat);
218         _SCRUB_FS_STAT_ZMAX(ss, duration, fs_stat);
219         _SCRUB_FS_STAT_ZMAX(ss, canceled, fs_stat);
220         _SCRUB_FS_STAT_MIN(ss, finished, fs_stat);
221 }
222
223 static void init_fs_stat(struct scrub_fs_stat *fs_stat)
224 {
225         memset(fs_stat, 0, sizeof(*fs_stat));
226         fs_stat->s.finished = 1;
227 }
228
229 static void _print_scrub_ss(struct scrub_stats *ss)
230 {
231         char t[4096];
232         struct tm tm;
233         time_t seconds;
234         unsigned hours;
235
236         if (!ss || !ss->t_start) {
237                 printf("\tno stats available\n");
238                 return;
239         }
240         if (ss->t_resumed) {
241                 localtime_r(&ss->t_resumed, &tm);
242                 strftime(t, sizeof(t), "%c", &tm);
243                 t[sizeof(t) - 1] = '\0';
244                 printf("\tscrub resumed at %s", t);
245         } else {
246                 localtime_r(&ss->t_start, &tm);
247                 strftime(t, sizeof(t), "%c", &tm);
248                 t[sizeof(t) - 1] = '\0';
249                 printf("\tscrub started at %s", t);
250         }
251
252         seconds = ss->duration;
253         hours = ss->duration / (60 * 60);
254         gmtime_r(&seconds, &tm);
255         strftime(t, sizeof(t), "%M:%S", &tm);
256         if (ss->finished && !ss->canceled) {
257                 printf(" and finished after %02u:%s\n", hours, t);
258         } else if (ss->canceled) {
259                 printf(" and was aborted after %02u:%s\n", hours, t);
260         } else {
261                 if (ss->in_progress)
262                         printf(", running for %02u:%s\n", hours, t);
263                 else
264                         printf(", interrupted after %02u:%s, not running\n",
265                                         hours, t);
266         }
267 }
268
269 static void print_scrub_dev(struct btrfs_ioctl_dev_info_args *di,
270                                 struct btrfs_scrub_progress *p, int raw,
271                                 const char *append, struct scrub_stats *ss)
272 {
273         printf("scrub device %s (id %llu) %s\n", di->path, di->devid,
274                append ? append : "");
275
276         _print_scrub_ss(ss);
277
278         if (p) {
279                 if (raw)
280                         print_scrub_full(p);
281                 else
282                         print_scrub_summary(p);
283         }
284 }
285
286 static void print_fs_stat(struct scrub_fs_stat *fs_stat, int raw)
287 {
288         _print_scrub_ss(&fs_stat->s);
289
290         if (raw)
291                 print_scrub_full(&fs_stat->p);
292         else
293                 print_scrub_summary(&fs_stat->p);
294 }
295
296 static void free_history(struct scrub_file_record **last_scrubs)
297 {
298         struct scrub_file_record **l = last_scrubs;
299         if (!l || IS_ERR(l))
300                 return;
301         while (*l)
302                 free(*l++);
303         free(last_scrubs);
304 }
305
306 /*
307  * cancels a running scrub and makes the master process record the current
308  * progress status before exiting.
309  */
310 static int cancel_fd = -1;
311 static void scrub_sigint_record_progress(int signal)
312 {
313         int ret;
314
315         ret = ioctl(cancel_fd, BTRFS_IOC_SCRUB_CANCEL, NULL);
316         if (ret < 0)
317                 perror("Scrub cancel failed");
318 }
319
320 static int scrub_handle_sigint_parent(void)
321 {
322         struct sigaction sa = {
323                 .sa_handler = SIG_IGN,
324                 .sa_flags = SA_RESTART,
325         };
326
327         return sigaction(SIGINT, &sa, NULL);
328 }
329
330 static int scrub_handle_sigint_child(int fd)
331 {
332         struct sigaction sa = {
333                 .sa_handler = fd == -1 ? SIG_DFL : scrub_sigint_record_progress,
334         };
335
336         cancel_fd = fd;
337         return sigaction(SIGINT, &sa, NULL);
338 }
339
340 static int scrub_datafile(const char *fn_base, const char *fn_local,
341                                 const char *fn_tmp, char *datafile, int size)
342 {
343         int ret;
344         int end = size - 2;
345
346         datafile[end + 1] = '\0';
347         strncpy(datafile, fn_base, end);
348         ret = strlen(datafile);
349
350         if (ret + 1 > end)
351                 return -EOVERFLOW;
352
353         datafile[ret] = '.';
354         strncpy(datafile + ret + 1, fn_local, end - ret - 1);
355         ret = strlen(datafile);
356
357         if (ret + 1 > end)
358                 return -EOVERFLOW;
359
360         if (fn_tmp) {
361                 datafile[ret] = '_';
362                 strncpy(datafile + ret + 1, fn_tmp, end - ret - 1);
363                 ret = strlen(datafile);
364
365                 if (ret > end)
366                         return -EOVERFLOW;
367         }
368
369         return 0;
370 }
371
372 static int scrub_open_file(const char *datafile, int m)
373 {
374         int fd;
375         int ret;
376
377         fd = open(datafile, m, 0600);
378         if (fd < 0)
379                 return -errno;
380
381         ret = flock(fd, LOCK_EX|LOCK_NB);
382         if (ret) {
383                 ret = errno;
384                 close(fd);
385                 return -ret;
386         }
387
388         return fd;
389 }
390
391 static int scrub_open_file_r(const char *fn_base, const char *fn_local)
392 {
393         int ret;
394         char datafile[PATH_MAX];
395         ret = scrub_datafile(fn_base, fn_local, NULL,
396                                 datafile, sizeof(datafile));
397         if (ret < 0)
398                 return ret;
399         return scrub_open_file(datafile, O_RDONLY);
400 }
401
402 static int scrub_open_file_w(const char *fn_base, const char *fn_local,
403                                 const char *tmp)
404 {
405         int ret;
406         char datafile[PATH_MAX];
407         ret = scrub_datafile(fn_base, fn_local, tmp,
408                                 datafile, sizeof(datafile));
409         if (ret < 0)
410                 return ret;
411         return scrub_open_file(datafile, O_WRONLY|O_CREAT);
412 }
413
414 static int scrub_rename_file(const char *fn_base, const char *fn_local,
415                                 const char *tmp)
416 {
417         int ret;
418         char datafile_old[PATH_MAX];
419         char datafile_new[PATH_MAX];
420         ret = scrub_datafile(fn_base, fn_local, tmp,
421                                 datafile_old, sizeof(datafile_old));
422         if (ret < 0)
423                 return ret;
424         ret = scrub_datafile(fn_base, fn_local, NULL,
425                                 datafile_new, sizeof(datafile_new));
426         if (ret < 0)
427                 return ret;
428         ret = rename(datafile_old, datafile_new);
429         return ret ? -errno : 0;
430 }
431
432 #define _SCRUB_KVREAD(ret, i, name, avail, l, dest) if (ret == 0) {       \
433         ret = scrub_kvread(i, sizeof(#name), avail, l, #name, dest.name); \
434 }
435
436 /*
437  * returns 0 if the key did not match (nothing was read)
438  *         1 if the key did match (success)
439  *        -1 if the key did match and an error occured
440  */
441 static int scrub_kvread(int *i, int len, int avail, const char *buf,
442                         const char *key, u64 *dest)
443 {
444         int j;
445
446         if (*i + len + 1 < avail && strncmp(&buf[*i], key, len - 1) == 0) {
447                 *i += len - 1;
448                 if (buf[*i] != ':')
449                         return -1;
450                 *i += 1;
451                 for (j = 0; isdigit(buf[*i + j]) && *i + j < avail; ++j)
452                         ;
453                 if (*i + j >= avail)
454                         return -1;
455                 *dest = atoll(&buf[*i]);
456                 *i += j;
457                 return 1;
458         }
459
460         return 0;
461 }
462
463 #define _SCRUB_INVALID do {                                             \
464         if (report_errors)                                              \
465                 fprintf(stderr, "WARNING: invalid data in line %d pos " \
466                         "%d state %d (near \"%.*s\") at %s:%d\n",       \
467                         lineno, i, state, 20 > avail ? avail : 20,      \
468                         l + i,  __FILE__, __LINE__);                    \
469         goto skip;                                                      \
470 } while (0)
471
472 static struct scrub_file_record **scrub_read_file(int fd, int report_errors)
473 {
474         int avail = 0;
475         int old_avail = 0;
476         char l[16 * 1024];
477         int state = 0;
478         int curr = -1;
479         int i = 0;
480         int j;
481         int ret;
482         int eof = 0;
483         int lineno = 0;
484         u64 version;
485         char empty_uuid[BTRFS_FSID_SIZE] = {0};
486         struct scrub_file_record **p = NULL;
487
488 again:
489         old_avail = avail - i;
490         BUG_ON(old_avail < 0);
491         if (old_avail)
492                 memmove(l, l + i, old_avail);
493         avail = read(fd, l + old_avail, sizeof(l) - old_avail);
494         if (avail == 0)
495                 eof = 1;
496         if (avail == 0 && old_avail == 0) {
497                 if (curr >= 0 &&
498                     memcmp(p[curr]->fsid, empty_uuid, BTRFS_FSID_SIZE) == 0) {
499                         p[curr] = NULL;
500                 } else if (curr == -1) {
501                         p = ERR_PTR(-ENODATA);
502                 }
503                 return p;
504         }
505         if (avail == -1) {
506                 free_history(p);
507                 return ERR_PTR(-errno);
508         }
509         avail += old_avail;
510
511         i = 0;
512         while (i < avail) {
513                 void *tmp;
514
515                 switch (state) {
516                 case 0: /* start of file */
517                         ret = scrub_kvread(&i,
518                                 sizeof(SCRUB_FILE_VERSION_PREFIX), avail, l,
519                                 SCRUB_FILE_VERSION_PREFIX, &version);
520                         if (ret != 1)
521                                 _SCRUB_INVALID;
522                         if (version != atoll(SCRUB_FILE_VERSION))
523                                 return ERR_PTR(-ENOTSUP);
524                         state = 6;
525                         continue;
526                 case 1: /* start of line, alloc */
527                         /*
528                          * this state makes sure we have a complete line in
529                          * further processing, so we don't need wrap-tracking
530                          * everywhere.
531                          */
532                         if (!eof && !memchr(l + i, '\n', avail - i))
533                                 goto again;
534                         ++lineno;
535                         if (curr > -1 && memcmp(p[curr]->fsid, empty_uuid,
536                                                 BTRFS_FSID_SIZE) == 0) {
537                                 state = 2;
538                                 continue;
539                         }
540                         ++curr;
541                         tmp = p;
542                         p = realloc(p, (curr + 2) * sizeof(*p));
543                         if (!p) {
544                                 free_history(tmp);
545                                 return ERR_PTR(-errno);
546                         }
547                         p[curr] = malloc(sizeof(**p));
548                         if (!p[curr]) {
549                                 free_history(p);
550                                 return ERR_PTR(-errno);
551                         }
552                         memset(p[curr], 0, sizeof(**p));
553                         p[curr + 1] = NULL;
554                         ++state;
555                         /* fall through */
556                 case 2: /* start of line, skip space */
557                         while (isspace(l[i]) && i < avail) {
558                                 if (l[i] == '\n')
559                                         ++lineno;
560                                 ++i;
561                         }
562                         if (i >= avail ||
563                             (!eof && !memchr(l + i, '\n', avail - i)))
564                                 goto again;
565                         ++state;
566                         /* fall through */
567                 case 3: /* read fsid */
568                         if (i == avail)
569                                 continue;
570                         for (j = 0; l[i + j] != ':' && i + j < avail; ++j)
571                                 ;
572                         if (i + j + 1 >= avail)
573                                 _SCRUB_INVALID;
574                         if (j != BTRFS_UUID_UNPARSED_SIZE - 1)
575                                 _SCRUB_INVALID;
576                         l[i + j] = '\0';
577                         ret = uuid_parse(l + i, p[curr]->fsid);
578                         if (ret)
579                                 _SCRUB_INVALID;
580                         i += j + 1;
581                         ++state;
582                         /* fall through */
583                 case 4: /* read dev id */
584                         for (j = 0; isdigit(l[i + j]) && i+j < avail; ++j)
585                                 ;
586                         if (j == 0 || i + j + 1 >= avail)
587                                 _SCRUB_INVALID;
588                         p[curr]->devid = atoll(&l[i]);
589                         i += j + 1;
590                         ++state;
591                         /* fall through */
592                 case 5: /* read key/value pair */
593                         ret = 0;
594                         _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
595                                         &p[curr]->p);
596                         _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
597                                         &p[curr]->p);
598                         _SCRUB_KVREAD(ret, &i, tree_extents_scrubbed, avail, l,
599                                         &p[curr]->p);
600                         _SCRUB_KVREAD(ret, &i, data_bytes_scrubbed, avail, l,
601                                         &p[curr]->p);
602                         _SCRUB_KVREAD(ret, &i, tree_bytes_scrubbed, avail, l,
603                                         &p[curr]->p);
604                         _SCRUB_KVREAD(ret, &i, read_errors, avail, l,
605                                         &p[curr]->p);
606                         _SCRUB_KVREAD(ret, &i, csum_errors, avail, l,
607                                         &p[curr]->p);
608                         _SCRUB_KVREAD(ret, &i, verify_errors, avail, l,
609                                         &p[curr]->p);
610                         _SCRUB_KVREAD(ret, &i, no_csum, avail, l,
611                                         &p[curr]->p);
612                         _SCRUB_KVREAD(ret, &i, csum_discards, avail, l,
613                                         &p[curr]->p);
614                         _SCRUB_KVREAD(ret, &i, super_errors, avail, l,
615                                         &p[curr]->p);
616                         _SCRUB_KVREAD(ret, &i, malloc_errors, avail, l,
617                                         &p[curr]->p);
618                         _SCRUB_KVREAD(ret, &i, uncorrectable_errors, avail, l,
619                                         &p[curr]->p);
620                         _SCRUB_KVREAD(ret, &i, corrected_errors, avail, l,
621                                         &p[curr]->p);
622                         _SCRUB_KVREAD(ret, &i, last_physical, avail, l,
623                                         &p[curr]->p);
624                         _SCRUB_KVREAD(ret, &i, finished, avail, l,
625                                         &p[curr]->stats);
626                         _SCRUB_KVREAD(ret, &i, t_start, avail, l,
627                                         (u64 *)&p[curr]->stats);
628                         _SCRUB_KVREAD(ret, &i, t_resumed, avail, l,
629                                         (u64 *)&p[curr]->stats);
630                         _SCRUB_KVREAD(ret, &i, duration, avail, l,
631                                         (u64 *)&p[curr]->stats);
632                         _SCRUB_KVREAD(ret, &i, canceled, avail, l,
633                                         &p[curr]->stats);
634                         if (ret != 1)
635                                 _SCRUB_INVALID;
636                         ++state;
637                         /* fall through */
638                 case 6: /* after number */
639                         if (l[i] == '|')
640                                 state = 5;
641                         else if (l[i] == '\n')
642                                 state = 1;
643                         else
644                                 _SCRUB_INVALID;
645                         ++i;
646                         continue;
647                 case 99: /* skip rest of line */
648 skip:
649                         state = 99;
650                         do {
651                                 ++i;
652                                 if (l[i - 1] == '\n') {
653                                         state = 1;
654                                         break;
655                                 }
656                         } while (i < avail);
657                         continue;
658                 }
659                 BUG();
660         }
661         goto again;
662 }
663
664 static int scrub_write_buf(int fd, const void *data, int len)
665 {
666         int ret;
667         ret = write(fd, data, len);
668         return ret - len;
669 }
670
671 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
672                                 __attribute__ ((format (printf, 4, 5)));
673 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
674 {
675         int ret;
676         va_list args;
677
678         va_start(args, fmt);
679         ret = vsnprintf(buf, max, fmt, args);
680         va_end(args);
681         if (ret >= max)
682                 return ret - max;
683         return scrub_write_buf(fd, buf, ret);
684 }
685
686 #define _SCRUB_SUM(dest, data, name) dest->scrub_args.progress.name =   \
687                         data->resumed->p.name + data->scrub_args.progress.name
688
689 static struct scrub_progress *scrub_resumed_stats(struct scrub_progress *data,
690                                                   struct scrub_progress *dest)
691 {
692         if (!data->resumed || data->skip)
693                 return data;
694
695         _SCRUB_SUM(dest, data, data_extents_scrubbed);
696         _SCRUB_SUM(dest, data, tree_extents_scrubbed);
697         _SCRUB_SUM(dest, data, data_bytes_scrubbed);
698         _SCRUB_SUM(dest, data, tree_bytes_scrubbed);
699         _SCRUB_SUM(dest, data, read_errors);
700         _SCRUB_SUM(dest, data, csum_errors);
701         _SCRUB_SUM(dest, data, verify_errors);
702         _SCRUB_SUM(dest, data, no_csum);
703         _SCRUB_SUM(dest, data, csum_discards);
704         _SCRUB_SUM(dest, data, super_errors);
705         _SCRUB_SUM(dest, data, malloc_errors);
706         _SCRUB_SUM(dest, data, uncorrectable_errors);
707         _SCRUB_SUM(dest, data, corrected_errors);
708         _SCRUB_SUM(dest, data, last_physical);
709         dest->stats.canceled = data->stats.canceled;
710         dest->stats.finished = data->stats.finished;
711         dest->stats.t_resumed = data->stats.t_start;
712         dest->stats.t_start = data->resumed->stats.t_start;
713         dest->stats.duration = data->resumed->stats.duration +
714                                                         data->stats.duration;
715         dest->scrub_args.devid = data->scrub_args.devid;
716         return dest;
717 }
718
719 #define _SCRUB_KVWRITE(fd, buf, name, use)              \
720         scrub_kvwrite(fd, buf, sizeof(buf), #name,      \
721                         use->scrub_args.progress.name)
722
723 #define _SCRUB_KVWRITE_STATS(fd, buf, name, use)        \
724         scrub_kvwrite(fd, buf, sizeof(buf), #name,      \
725                         use->stats.name)
726
727 static int scrub_kvwrite(int fd, char *buf, int max, const char *key, u64 val)
728 {
729         return scrub_writev(fd, buf, max, "|%s:%lld", key, val);
730 }
731
732 static int scrub_write_file(int fd, const char *fsid,
733                                 struct scrub_progress *data, int n)
734 {
735         int ret = 0;
736         int i;
737         char buf[1024];
738         struct scrub_progress local;
739         struct scrub_progress *use;
740
741         if (n < 1)
742                 return -EINVAL;
743
744         /* each -1 is to subtract one \0 byte, the + 2 is for ':' and '\n' */
745         ret = scrub_write_buf(fd, SCRUB_FILE_VERSION_PREFIX ":"
746                                 SCRUB_FILE_VERSION "\n",
747                                 (sizeof(SCRUB_FILE_VERSION_PREFIX) - 1) +
748                                 (sizeof(SCRUB_FILE_VERSION) - 1) + 2);
749         if (ret)
750                 return -EOVERFLOW;
751
752         for (i = 0; i < n; ++i) {
753                 use = scrub_resumed_stats(&data[i], &local);
754                 if (scrub_write_buf(fd, fsid, strlen(fsid)) ||
755                     scrub_write_buf(fd, ":", 1) ||
756                     scrub_writev(fd, buf, sizeof(buf), "%lld",
757                                         use->scrub_args.devid) ||
758                     scrub_write_buf(fd, buf, ret) ||
759                     _SCRUB_KVWRITE(fd, buf, data_extents_scrubbed, use) ||
760                     _SCRUB_KVWRITE(fd, buf, tree_extents_scrubbed, use) ||
761                     _SCRUB_KVWRITE(fd, buf, data_bytes_scrubbed, use) ||
762                     _SCRUB_KVWRITE(fd, buf, tree_bytes_scrubbed, use) ||
763                     _SCRUB_KVWRITE(fd, buf, read_errors, use) ||
764                     _SCRUB_KVWRITE(fd, buf, csum_errors, use) ||
765                     _SCRUB_KVWRITE(fd, buf, verify_errors, use) ||
766                     _SCRUB_KVWRITE(fd, buf, no_csum, use) ||
767                     _SCRUB_KVWRITE(fd, buf, csum_discards, use) ||
768                     _SCRUB_KVWRITE(fd, buf, super_errors, use) ||
769                     _SCRUB_KVWRITE(fd, buf, malloc_errors, use) ||
770                     _SCRUB_KVWRITE(fd, buf, uncorrectable_errors, use) ||
771                     _SCRUB_KVWRITE(fd, buf, corrected_errors, use) ||
772                     _SCRUB_KVWRITE(fd, buf, last_physical, use) ||
773                     _SCRUB_KVWRITE_STATS(fd, buf, t_start, use) ||
774                     _SCRUB_KVWRITE_STATS(fd, buf, t_resumed, use) ||
775                     _SCRUB_KVWRITE_STATS(fd, buf, duration, use) ||
776                     _SCRUB_KVWRITE_STATS(fd, buf, canceled, use) ||
777                     _SCRUB_KVWRITE_STATS(fd, buf, finished, use) ||
778                     scrub_write_buf(fd, "\n", 1)) {
779                         return -EOVERFLOW;
780                 }
781         }
782
783         return 0;
784 }
785
786 static int scrub_write_progress(pthread_mutex_t *m, const char *fsid,
787                                 struct scrub_progress *data, int n)
788 {
789         int ret;
790         int err;
791         int fd = -1;
792         int old;
793
794         ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old);
795         if (ret) {
796                 err = -ret;
797                 goto out3;
798         }
799
800         ret = pthread_mutex_lock(m);
801         if (ret) {
802                 err = -ret;
803                 goto out2;
804         }
805
806         fd = scrub_open_file_w(SCRUB_DATA_FILE, fsid, "tmp");
807         if (fd < 0) {
808                 err = fd;
809                 goto out1;
810         }
811         err = scrub_write_file(fd, fsid, data, n);
812         if (err)
813                 goto out1;
814         err = scrub_rename_file(SCRUB_DATA_FILE, fsid, "tmp");
815         if (err)
816                 goto out1;
817
818 out1:
819         if (fd >= 0) {
820                 ret = close(fd);
821                 if (ret)
822                         err = -errno;
823         }
824
825         ret = pthread_mutex_unlock(m);
826         if (ret && !err)
827                 err = -ret;
828
829 out2:
830         ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old);
831         if (ret && !err)
832                 err = -ret;
833
834 out3:
835         return err;
836 }
837
838 static void *scrub_one_dev(void *ctx)
839 {
840         struct scrub_progress *sp = ctx;
841         int ret;
842         struct timeval tv;
843
844         sp->stats.canceled = 0;
845         sp->stats.duration = 0;
846         sp->stats.finished = 0;
847
848         ret = syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0,
849                       IOPRIO_PRIO_VALUE(sp->ioprio_class,
850                                         sp->ioprio_classdata));
851         if (ret)
852                 fprintf(stderr,
853                         "WARNING: setting ioprio failed: %s (ignored).\n",
854                         strerror(errno));
855
856         ret = ioctl(sp->fd, BTRFS_IOC_SCRUB, &sp->scrub_args);
857         gettimeofday(&tv, NULL);
858         sp->ret = ret;
859         sp->stats.duration = tv.tv_sec - sp->stats.t_start;
860         sp->stats.canceled = !!ret;
861         sp->ioctl_errno = errno;
862         ret = pthread_mutex_lock(&sp->progress_mutex);
863         if (ret)
864                 return ERR_PTR(-ret);
865         sp->stats.finished = 1;
866         ret = pthread_mutex_unlock(&sp->progress_mutex);
867         if (ret)
868                 return ERR_PTR(-ret);
869
870         return NULL;
871 }
872
873 static void *progress_one_dev(void *ctx)
874 {
875         struct scrub_progress *sp = ctx;
876
877         sp->ret = ioctl(sp->fd, BTRFS_IOC_SCRUB_PROGRESS, &sp->scrub_args);
878         sp->ioctl_errno = errno;
879
880         return NULL;
881 }
882
883 /* nb: returns a negative errno via ERR_PTR */
884 static void *scrub_progress_cycle(void *ctx)
885 {
886         int ret = 0;
887         int  perr = 0;  /* positive / pthread error returns */
888         int old;
889         int i;
890         char fsid[BTRFS_UUID_UNPARSED_SIZE];
891         struct scrub_progress *sp;
892         struct scrub_progress *sp_last;
893         struct scrub_progress *sp_shared;
894         struct timeval tv;
895         struct scrub_progress_cycle *spc = ctx;
896         int ndev = spc->fi->num_devices;
897         int this = 1;
898         int last = 0;
899         int peer_fd = -1;
900         struct pollfd accept_poll_fd = {
901                 .fd = spc->prg_fd,
902                 .events = POLLIN,
903                 .revents = 0,
904         };
905         struct pollfd write_poll_fd = {
906                 .events = POLLOUT,
907                 .revents = 0,
908         };
909         struct sockaddr_un peer;
910         socklen_t peer_size = sizeof(peer);
911
912         perr = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old);
913         if (perr)
914                 goto out;
915
916         uuid_unparse(spc->fi->fsid, fsid);
917
918         for (i = 0; i < ndev; ++i) {
919                 sp = &spc->progress[i];
920                 sp_last = &spc->progress[i + ndev];
921                 sp_shared = &spc->shared_progress[i];
922                 sp->scrub_args.devid = sp_last->scrub_args.devid =
923                                                 sp_shared->scrub_args.devid;
924                 sp->fd = sp_last->fd = spc->fdmnt;
925                 sp->stats.t_start = sp_last->stats.t_start =
926                                                 sp_shared->stats.t_start;
927                 sp->resumed = sp_last->resumed = sp_shared->resumed;
928                 sp->skip = sp_last->skip = sp_shared->skip;
929                 sp->stats.finished = sp_last->stats.finished =
930                                                 sp_shared->stats.finished;
931         }
932
933         while (1) {
934                 ret = poll(&accept_poll_fd, 1, 5 * 1000);
935                 if (ret == -1) {
936                         ret = -errno;
937                         goto out;
938                 }
939                 if (ret)
940                         peer_fd = accept(spc->prg_fd, (struct sockaddr *)&peer,
941                                          &peer_size);
942                 gettimeofday(&tv, NULL);
943                 this = (this + 1)%2;
944                 last = (last + 1)%2;
945                 for (i = 0; i < ndev; ++i) {
946                         sp = &spc->progress[this * ndev + i];
947                         sp_last = &spc->progress[last * ndev + i];
948                         sp_shared = &spc->shared_progress[i];
949                         if (sp->stats.finished)
950                                 continue;
951                         progress_one_dev(sp);
952                         sp->stats.duration = tv.tv_sec - sp->stats.t_start;
953                         if (!sp->ret)
954                                 continue;
955                         if (sp->ioctl_errno != ENOTCONN &&
956                             sp->ioctl_errno != ENODEV) {
957                                 ret = -sp->ioctl_errno;
958                                 goto out;
959                         }
960                         /*
961                          * scrub finished or device removed, check the
962                          * finished flag. if unset, just use the last
963                          * result we got for the current write and go
964                          * on. flag should be set on next cycle, then.
965                          */
966                         perr = pthread_setcancelstate(
967                                         PTHREAD_CANCEL_DISABLE, &old);
968                         if (perr)
969                                 goto out;
970                         perr = pthread_mutex_lock(&sp_shared->progress_mutex);
971                         if (perr)
972                                 goto out;
973                         if (!sp_shared->stats.finished) {
974                                 perr = pthread_mutex_unlock(
975                                                 &sp_shared->progress_mutex);
976                                 if (perr)
977                                         goto out;
978                                 perr = pthread_setcancelstate(
979                                                 PTHREAD_CANCEL_ENABLE, &old);
980                                 if (perr)
981                                         goto out;
982                                 memcpy(sp, sp_last, sizeof(*sp));
983                                 continue;
984                         }
985                         perr = pthread_mutex_unlock(&sp_shared->progress_mutex);
986                         if (perr)
987                                 goto out;
988                         perr = pthread_setcancelstate(
989                                         PTHREAD_CANCEL_ENABLE, &old);
990                         if (perr)
991                                 goto out;
992                         memcpy(sp, sp_shared, sizeof(*sp));
993                         memcpy(sp_last, sp_shared, sizeof(*sp));
994                 }
995                 if (peer_fd != -1) {
996                         write_poll_fd.fd = peer_fd;
997                         ret = poll(&write_poll_fd, 1, 0);
998                         if (ret == -1) {
999                                 ret = -errno;
1000                                 goto out;
1001                         }
1002                         if (ret) {
1003                                 ret = scrub_write_file(
1004                                         peer_fd, fsid,
1005                                         &spc->progress[this * ndev], ndev);
1006                                 if (ret)
1007                                         goto out;
1008                         }
1009                         close(peer_fd);
1010                         peer_fd = -1;
1011                 }
1012                 if (!spc->do_record)
1013                         continue;
1014                 ret = scrub_write_progress(spc->write_mutex, fsid,
1015                                            &spc->progress[this * ndev], ndev);
1016                 if (ret)
1017                         goto out;
1018         }
1019 out:
1020         if (peer_fd != -1)
1021                 close(peer_fd);
1022         if (perr)
1023                 ret = -perr;
1024         return ERR_PTR(ret);
1025 }
1026
1027 static struct scrub_file_record *last_dev_scrub(
1028                 struct scrub_file_record *const *const past_scrubs, u64 devid)
1029 {
1030         int i;
1031
1032         if (!past_scrubs || IS_ERR(past_scrubs))
1033                 return NULL;
1034
1035         for (i = 0; past_scrubs[i]; ++i)
1036                 if (past_scrubs[i]->devid == devid)
1037                         return past_scrubs[i];
1038
1039         return NULL;
1040 }
1041
1042 static int mkdir_p(char *path)
1043 {
1044         int i;
1045         int ret;
1046
1047         for (i = 1; i < strlen(path); ++i) {
1048                 if (path[i] != '/')
1049                         continue;
1050                 path[i] = '\0';
1051                 ret = mkdir(path, 0777);
1052                 if (ret && errno != EEXIST)
1053                         return -errno;
1054                 path[i] = '/';
1055         }
1056
1057         return 0;
1058 }
1059
1060 static int is_scrub_running_on_fs(struct btrfs_ioctl_fs_info_args *fi_args,
1061                                   struct btrfs_ioctl_dev_info_args *di_args,
1062                                   struct scrub_file_record **past_scrubs)
1063 {
1064         int i;
1065
1066         if (!fi_args || !di_args || !past_scrubs)
1067                 return 0;
1068
1069         for (i = 0; i < fi_args->num_devices; i++) {
1070                 struct scrub_file_record *sfr =
1071                         last_dev_scrub(past_scrubs, di_args[i].devid);
1072
1073                 if (!sfr)
1074                         continue;
1075                 if (!(sfr->stats.finished || sfr->stats.canceled))
1076                         return 1;
1077         }
1078         return 0;
1079 }
1080
1081 static int is_scrub_running_in_kernel(int fd,
1082                 struct btrfs_ioctl_dev_info_args *di_args, u64 max_devices)
1083 {
1084         struct scrub_progress sp;
1085         int i;
1086         int ret;
1087
1088         for (i = 0; i < max_devices; i++) {
1089                 memset(&sp, 0, sizeof(sp));
1090                 sp.scrub_args.devid = di_args[i].devid;
1091                 ret = ioctl(fd, BTRFS_IOC_SCRUB_PROGRESS, &sp.scrub_args);
1092                 if (!ret)
1093                         return 1;
1094         }
1095
1096         return 0;
1097 }
1098
1099 static const char * const cmd_scrub_start_usage[];
1100 static const char * const cmd_scrub_resume_usage[];
1101
1102 static int scrub_start(int argc, char **argv, int resume)
1103 {
1104         int fdmnt;
1105         int prg_fd = -1;
1106         int fdres = -1;
1107         int ret;
1108         pid_t pid;
1109         int c;
1110         int i;
1111         int err = 0;
1112         int e_uncorrectable = 0;
1113         int e_correctable = 0;
1114         int print_raw = 0;
1115         char *path;
1116         int do_background = 1;
1117         int do_wait = 0;
1118         int do_print = 0;
1119         int do_quiet = 0;
1120         int do_record = 1;
1121         int readonly = 0;
1122         int do_stats_per_dev = 0;
1123         int ioprio_class = IOPRIO_CLASS_IDLE;
1124         int ioprio_classdata = 0;
1125         int n_start = 0;
1126         int n_skip = 0;
1127         int n_resume = 0;
1128         struct btrfs_ioctl_fs_info_args fi_args;
1129         struct btrfs_ioctl_dev_info_args *di_args = NULL;
1130         struct scrub_progress *sp = NULL;
1131         struct scrub_fs_stat fs_stat;
1132         struct timeval tv;
1133         struct sockaddr_un addr = {
1134                 .sun_family = AF_UNIX,
1135         };
1136         pthread_t *t_devs = NULL;
1137         pthread_t t_prog;
1138         struct scrub_file_record **past_scrubs = NULL;
1139         struct scrub_file_record *last_scrub = NULL;
1140         char *datafile = strdup(SCRUB_DATA_FILE);
1141         char fsid[BTRFS_UUID_UNPARSED_SIZE];
1142         char sock_path[PATH_MAX] = "";
1143         struct scrub_progress_cycle spc;
1144         pthread_mutex_t spc_write_mutex = PTHREAD_MUTEX_INITIALIZER;
1145         void *terr;
1146         u64 devid;
1147         DIR *dirstream = NULL;
1148         int force = 0;
1149         int nothing_to_resume = 0;
1150
1151         optind = 1;
1152         while ((c = getopt(argc, argv, "BdqrRc:n:f")) != -1) {
1153                 switch (c) {
1154                 case 'B':
1155                         do_background = 0;
1156                         do_wait = 1;
1157                         do_print = 1;
1158                         break;
1159                 case 'd':
1160                         do_stats_per_dev = 1;
1161                         break;
1162                 case 'q':
1163                         do_quiet = 1;
1164                         break;
1165                 case 'r':
1166                         readonly = 1;
1167                         break;
1168                 case 'R':
1169                         print_raw = 1;
1170                         break;
1171                 case 'c':
1172                         ioprio_class = (int)strtol(optarg, NULL, 10);
1173                         break;
1174                 case 'n':
1175                         ioprio_classdata = (int)strtol(optarg, NULL, 10);
1176                         break;
1177                 case 'f':
1178                         force = 1;
1179                         break;
1180                 case '?':
1181                 default:
1182                         usage(resume ? cmd_scrub_resume_usage :
1183                                                 cmd_scrub_start_usage);
1184                 }
1185         }
1186
1187         /* try to catch most error cases before forking */
1188
1189         if (check_argc_exact(argc - optind, 1)) {
1190                 usage(resume ? cmd_scrub_resume_usage :
1191                                         cmd_scrub_start_usage);
1192         }
1193
1194         spc.progress = NULL;
1195         if (do_quiet && do_print)
1196                 do_print = 0;
1197
1198         if (mkdir_p(datafile)) {
1199                 ERR(!do_quiet, "WARNING: cannot create scrub data "
1200                                "file, mkdir %s failed: %s. Status recording "
1201                                "disabled\n", datafile, strerror(errno));
1202                 do_record = 0;
1203         }
1204         free(datafile);
1205
1206         path = argv[optind];
1207
1208         fdmnt = open_path_or_dev_mnt(path, &dirstream);
1209
1210         if (fdmnt < 0) {
1211                 if (errno == EINVAL)
1212                         ERR(!do_quiet,
1213                             "ERROR: '%s' is not a mounted btrfs device\n",
1214                             path);
1215                 else
1216                         ERR(!do_quiet, "ERROR: can't access '%s': %s\n",
1217                             path, strerror(errno));
1218                 return 1;
1219         }
1220
1221         ret = get_fs_info(path, &fi_args, &di_args);
1222         if (ret) {
1223                 ERR(!do_quiet, "ERROR: getting dev info for scrub failed: "
1224                     "%s\n", strerror(-ret));
1225                 err = 1;
1226                 goto out;
1227         }
1228         if (!fi_args.num_devices) {
1229                 ERR(!do_quiet, "ERROR: no devices found\n");
1230                 err = 1;
1231                 goto out;
1232         }
1233
1234         uuid_unparse(fi_args.fsid, fsid);
1235         fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1236         if (fdres < 0 && fdres != -ENOENT) {
1237                 ERR(!do_quiet, "WARNING: failed to open status file: "
1238                     "%s\n", strerror(-fdres));
1239         } else if (fdres >= 0) {
1240                 past_scrubs = scrub_read_file(fdres, !do_quiet);
1241                 if (IS_ERR(past_scrubs))
1242                         ERR(!do_quiet, "WARNING: failed to read status file: "
1243                             "%s\n", strerror(-PTR_ERR(past_scrubs)));
1244                 close(fdres);
1245         }
1246
1247         /*
1248          * Check for stale information in the status file, ie. if it's
1249          * canceled=0, finished=0 but no scrub is running.
1250          */
1251         if (!is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices))
1252                 force = 1;
1253
1254         /*
1255          * check whether any involved device is already busy running a
1256          * scrub. This would cause damaged status messages and the state
1257          * "aborted" without the explanation that a scrub was already
1258          * running. Therefore check it first, prevent it and give some
1259          * feedback to the user if scrub is already running.
1260          * Note that if scrub is started with a block device as the
1261          * parameter, only that particular block device is checked. It
1262          * is a normal mode of operation to start scrub on multiple
1263          * single devices, there is no reason to prevent this.
1264          */
1265         if (!force && is_scrub_running_on_fs(&fi_args, di_args, past_scrubs)) {
1266                 ERR(!do_quiet,
1267                     "ERROR: scrub is already running.\n"
1268                     "To cancel use 'btrfs scrub cancel %s'.\n"
1269                     "To see the status use 'btrfs scrub status [-d] %s'.\n",
1270                     path, path);
1271                 err = 1;
1272                 goto out;
1273         }
1274
1275         t_devs = malloc(fi_args.num_devices * sizeof(*t_devs));
1276         sp = calloc(fi_args.num_devices, sizeof(*sp));
1277         spc.progress = calloc(fi_args.num_devices * 2, sizeof(*spc.progress));
1278
1279         if (!t_devs || !sp || !spc.progress) {
1280                 ERR(!do_quiet, "ERROR: scrub failed: %s", strerror(errno));
1281                 err = 1;
1282                 goto out;
1283         }
1284
1285         for (i = 0; i < fi_args.num_devices; ++i) {
1286                 devid = di_args[i].devid;
1287                 ret = pthread_mutex_init(&sp[i].progress_mutex, NULL);
1288                 if (ret) {
1289                         ERR(!do_quiet, "ERROR: pthread_mutex_init failed: "
1290                             "%s\n", strerror(ret));
1291                         err = 1;
1292                         goto out;
1293                 }
1294                 last_scrub = last_dev_scrub(past_scrubs, devid);
1295                 sp[i].scrub_args.devid = devid;
1296                 sp[i].fd = fdmnt;
1297                 if (resume && last_scrub && (last_scrub->stats.canceled ||
1298                                              !last_scrub->stats.finished)) {
1299                         ++n_resume;
1300                         sp[i].scrub_args.start = last_scrub->p.last_physical;
1301                         sp[i].resumed = last_scrub;
1302                 } else if (resume) {
1303                         ++n_skip;
1304                         sp[i].skip = 1;
1305                         sp[i].resumed = last_scrub;
1306                         continue;
1307                 } else {
1308                         ++n_start;
1309                         sp[i].scrub_args.start = 0ll;
1310                         sp[i].resumed = NULL;
1311                 }
1312                 sp[i].skip = 0;
1313                 sp[i].scrub_args.end = (u64)-1ll;
1314                 sp[i].scrub_args.flags = readonly ? BTRFS_SCRUB_READONLY : 0;
1315                 sp[i].ioprio_class = ioprio_class;
1316                 sp[i].ioprio_classdata = ioprio_classdata;
1317         }
1318
1319         if (!n_start && !n_resume) {
1320                 if (!do_quiet)
1321                         printf("scrub: nothing to resume for %s, fsid %s\n",
1322                                path, fsid);
1323                 nothing_to_resume = 1;
1324                 goto out;
1325         }
1326
1327         ret = prg_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1328         while (ret != -1) {
1329                 ret = scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid, NULL,
1330                                         sock_path, sizeof(sock_path));
1331                 /* ignore EOVERFLOW, try using a shorter path for the socket */
1332                 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1333                 strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1);
1334                 ret = bind(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1335                 if (ret != -1 || errno != EADDRINUSE)
1336                         break;
1337                 /*
1338                  * bind failed with EADDRINUSE. so let's see if anyone answers
1339                  * when we make a call to the socket ...
1340                  */
1341                 ret = connect(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1342                 if (!ret || errno != ECONNREFUSED) {
1343                         /* ... yes, so scrub must be running. error out */
1344                         fprintf(stderr, "ERROR: scrub already running\n");
1345                         close(prg_fd);
1346                         prg_fd = -1;
1347                         goto out;
1348                 }
1349                 /*
1350                  * ... no, this means someone left us alone with an unused
1351                  * socket in the file system. remove it and try again.
1352                  */
1353                 ret = unlink(sock_path);
1354         }
1355         if (ret != -1)
1356                 ret = listen(prg_fd, 100);
1357         if (ret == -1) {
1358                 ERR(!do_quiet, "WARNING: failed to open the progress status "
1359                     "socket at %s: %s. Progress cannot be queried\n",
1360                     sock_path[0] ? sock_path : SCRUB_PROGRESS_SOCKET_PATH,
1361                     strerror(errno));
1362                 if (prg_fd != -1) {
1363                         close(prg_fd);
1364                         prg_fd = -1;
1365                         if (sock_path[0])
1366                                 unlink(sock_path);
1367                 }
1368         }
1369
1370         if (do_record) {
1371                 /* write all-zero progress file for a start */
1372                 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1373                                            fi_args.num_devices);
1374                 if (ret) {
1375                         ERR(!do_quiet, "WARNING: failed to write the progress "
1376                             "status file: %s. Status recording disabled\n",
1377                             strerror(-ret));
1378                         do_record = 0;
1379                 }
1380         }
1381
1382         if (do_background) {
1383                 pid = fork();
1384                 if (pid == -1) {
1385                         ERR(!do_quiet, "ERROR: cannot scrub, fork failed: "
1386                                         "%s\n", strerror(errno));
1387                         err = 1;
1388                         goto out;
1389                 }
1390
1391                 if (pid) {
1392                         int stat;
1393                         scrub_handle_sigint_parent();
1394                         if (!do_quiet)
1395                                 printf("scrub %s on %s, fsid %s (pid=%d)\n",
1396                                        n_start ? "started" : "resumed",
1397                                        path, fsid, pid);
1398                         if (!do_wait) {
1399                                 err = 0;
1400                                 goto out;
1401                         }
1402                         ret = wait(&stat);
1403                         if (ret != pid) {
1404                                 ERR(!do_quiet, "ERROR: wait failed: (ret=%d) "
1405                                     "%s\n", ret, strerror(errno));
1406                                 err = 1;
1407                                 goto out;
1408                         }
1409                         if (!WIFEXITED(stat) || WEXITSTATUS(stat)) {
1410                                 ERR(!do_quiet, "ERROR: scrub process failed\n");
1411                                 err = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
1412                                 goto out;
1413                         }
1414                         err = 0;
1415                         goto out;
1416                 }
1417         }
1418
1419         scrub_handle_sigint_child(fdmnt);
1420
1421         for (i = 0; i < fi_args.num_devices; ++i) {
1422                 if (sp[i].skip) {
1423                         sp[i].scrub_args.progress = sp[i].resumed->p;
1424                         sp[i].stats = sp[i].resumed->stats;
1425                         sp[i].ret = 0;
1426                         sp[i].stats.finished = 1;
1427                         continue;
1428                 }
1429                 devid = di_args[i].devid;
1430                 gettimeofday(&tv, NULL);
1431                 sp[i].stats.t_start = tv.tv_sec;
1432                 ret = pthread_create(&t_devs[i], NULL,
1433                                         scrub_one_dev, &sp[i]);
1434                 if (ret) {
1435                         if (do_print)
1436                                 fprintf(stderr, "ERROR: creating "
1437                                         "scrub_one_dev[%llu] thread failed: "
1438                                         "%s\n", devid, strerror(ret));
1439                         err = 1;
1440                         goto out;
1441                 }
1442         }
1443
1444         spc.fdmnt = fdmnt;
1445         spc.prg_fd = prg_fd;
1446         spc.do_record = do_record;
1447         spc.write_mutex = &spc_write_mutex;
1448         spc.shared_progress = sp;
1449         spc.fi = &fi_args;
1450         ret = pthread_create(&t_prog, NULL, scrub_progress_cycle, &spc);
1451         if (ret) {
1452                 if (do_print)
1453                         fprintf(stderr, "ERROR: creating progress thread "
1454                                 "failed: %s\n", strerror(ret));
1455                 err = 1;
1456                 goto out;
1457         }
1458
1459         err = 0;
1460         for (i = 0; i < fi_args.num_devices; ++i) {
1461                 if (sp[i].skip)
1462                         continue;
1463                 devid = di_args[i].devid;
1464                 ret = pthread_join(t_devs[i], NULL);
1465                 if (ret) {
1466                         if (do_print)
1467                                 fprintf(stderr, "ERROR: pthread_join failed "
1468                                         "for scrub_one_dev[%llu]: %s\n", devid,
1469                                         strerror(ret));
1470                         ++err;
1471                         continue;
1472                 }
1473                 if (sp[i].ret && sp[i].ioctl_errno == ENODEV) {
1474                         if (do_print)
1475                                 fprintf(stderr, "WARNING: device %lld not "
1476                                         "present\n", devid);
1477                         continue;
1478                 }
1479                 if (sp[i].ret && sp[i].ioctl_errno == ECANCELED) {
1480                         ++err;
1481                 } else if (sp[i].ret) {
1482                         if (do_print)
1483                                 fprintf(stderr, "ERROR: scrubbing %s failed "
1484                                         "for device id %lld (%s)\n", path,
1485                                         devid, strerror(sp[i].ioctl_errno));
1486                         ++err;
1487                         continue;
1488                 }
1489                 if (sp[i].scrub_args.progress.uncorrectable_errors > 0)
1490                         e_uncorrectable++;
1491                 if (sp[i].scrub_args.progress.corrected_errors > 0
1492                     || sp[i].scrub_args.progress.unverified_errors > 0)
1493                         e_correctable++;
1494         }
1495
1496         if (do_print) {
1497                 const char *append = "done";
1498                 if (!do_stats_per_dev)
1499                         init_fs_stat(&fs_stat);
1500                 for (i = 0; i < fi_args.num_devices; ++i) {
1501                         if (do_stats_per_dev) {
1502                                 print_scrub_dev(&di_args[i],
1503                                                 &sp[i].scrub_args.progress,
1504                                                 print_raw,
1505                                                 sp[i].ret ? "canceled" : "done",
1506                                                 &sp[i].stats);
1507                         } else {
1508                                 if (sp[i].ret)
1509                                         append = "canceled";
1510                                 add_to_fs_stat(&sp[i].scrub_args.progress,
1511                                                 &sp[i].stats, &fs_stat);
1512                         }
1513                 }
1514                 if (!do_stats_per_dev) {
1515                         printf("scrub %s for %s\n", append, fsid);
1516                         print_fs_stat(&fs_stat, print_raw);
1517                 }
1518         }
1519
1520         ret = pthread_cancel(t_prog);
1521         if (!ret)
1522                 ret = pthread_join(t_prog, &terr);
1523
1524         /* check for errors from the handling of the progress thread */
1525         if (do_print && ret) {
1526                 fprintf(stderr, "ERROR: progress thread handling failed: %s\n",
1527                         strerror(ret));
1528         }
1529
1530         /* check for errors returned from the progress thread itself */
1531         if (do_print && terr && terr != PTHREAD_CANCELED) {
1532                 fprintf(stderr, "ERROR: recording progress "
1533                         "failed: %s\n", strerror(-PTR_ERR(terr)));
1534         }
1535
1536         if (do_record) {
1537                 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1538                                            fi_args.num_devices);
1539                 if (ret && do_print) {
1540                         fprintf(stderr, "ERROR: failed to record the result: "
1541                                 "%s\n", strerror(-ret));
1542                 }
1543         }
1544
1545         scrub_handle_sigint_child(-1);
1546
1547 out:
1548         free_history(past_scrubs);
1549         free(di_args);
1550         free(t_devs);
1551         free(sp);
1552         free(spc.progress);
1553         if (prg_fd > -1) {
1554                 close(prg_fd);
1555                 if (sock_path[0])
1556                         unlink(sock_path);
1557         }
1558         close_file_or_dir(fdmnt, dirstream);
1559
1560         if (err)
1561                 return 1;
1562         if (nothing_to_resume)
1563                 return 2;
1564         if (e_uncorrectable) {
1565                 ERR(!do_quiet, "ERROR: There are uncorrectable errors.\n");
1566                 return 3;
1567         }
1568         if (e_correctable)
1569                 ERR(!do_quiet, "WARNING: errors detected during scrubbing, corrected.\n");
1570
1571         return 0;
1572 }
1573
1574 static const char * const cmd_scrub_start_usage[] = {
1575         "btrfs scrub start [-BdqrRf] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1576         "Start a new scrub. If a scrub is already running, the new one fails.",
1577         "",
1578         "-B     do not background",
1579         "-d     stats per device (-B only)",
1580         "-q     be quiet",
1581         "-r     read only mode",
1582         "-R     raw print mode, print full data instead of summary",
1583         "-c     set ioprio class (see ionice(1) manpage)",
1584         "-n     set ioprio classdata (see ionice(1) manpage)",
1585         "-f     force starting new scrub even if a scrub is already running",
1586         "       this is useful when scrub stats record file is damaged",
1587         NULL
1588 };
1589
1590 static int cmd_scrub_start(int argc, char **argv)
1591 {
1592         return scrub_start(argc, argv, 0);
1593 }
1594
1595 static const char * const cmd_scrub_cancel_usage[] = {
1596         "btrfs scrub cancel <path>|<device>",
1597         "Cancel a running scrub",
1598         NULL
1599 };
1600
1601 static int cmd_scrub_cancel(int argc, char **argv)
1602 {
1603         char *path;
1604         int ret;
1605         int fdmnt = -1;
1606         DIR *dirstream = NULL;
1607
1608         if (check_argc_exact(argc, 2))
1609                 usage(cmd_scrub_cancel_usage);
1610
1611         path = argv[1];
1612
1613         fdmnt = open_path_or_dev_mnt(path, &dirstream);
1614         if (fdmnt < 0) {
1615                 if (errno == EINVAL)
1616                         fprintf(stderr,
1617                                 "ERROR: '%s' is not a mounted btrfs device\n",
1618                                 path);
1619                 else
1620                         fprintf(stderr, "ERROR: can't access '%s': %s\n",
1621                                 path, strerror(errno));
1622                 ret = 1;
1623                 goto out;
1624         }
1625
1626         ret = ioctl(fdmnt, BTRFS_IOC_SCRUB_CANCEL, NULL);
1627
1628         if (ret < 0) {
1629                 fprintf(stderr, "ERROR: scrub cancel failed on %s: %s\n", path,
1630                         errno == ENOTCONN ? "not running" : strerror(errno));
1631                 if (errno == ENOTCONN)
1632                         ret = 2;
1633                 else
1634                         ret = 1;
1635                 goto out;
1636         }
1637
1638         ret = 0;
1639         printf("scrub cancelled\n");
1640
1641 out:
1642         close_file_or_dir(fdmnt, dirstream);
1643         return ret;
1644 }
1645
1646 static const char * const cmd_scrub_resume_usage[] = {
1647         "btrfs scrub resume [-BdqrR] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1648         "Resume previously canceled or interrupted scrub",
1649         "",
1650         "-B     do not background",
1651         "-d     stats per device (-B only)",
1652         "-q     be quiet",
1653         "-r     read only mode",
1654         "-R     raw print mode, print full data instead of summary",
1655         "-c     set ioprio class (see ionice(1) manpage)",
1656         "-n     set ioprio classdata (see ionice(1) manpage)",
1657         NULL
1658 };
1659
1660 static int cmd_scrub_resume(int argc, char **argv)
1661 {
1662         return scrub_start(argc, argv, 1);
1663 }
1664
1665 static const char * const cmd_scrub_status_usage[] = {
1666         "btrfs scrub status [-dR] <path>|<device>",
1667         "Show status of running or finished scrub",
1668         "",
1669         "-d     stats per device",
1670         "-R     print raw stats",
1671         NULL
1672 };
1673
1674 static int cmd_scrub_status(int argc, char **argv)
1675 {
1676         char *path;
1677         struct btrfs_ioctl_fs_info_args fi_args;
1678         struct btrfs_ioctl_dev_info_args *di_args = NULL;
1679         struct scrub_file_record **past_scrubs = NULL;
1680         struct scrub_file_record *last_scrub;
1681         struct scrub_fs_stat fs_stat;
1682         struct sockaddr_un addr = {
1683                 .sun_family = AF_UNIX,
1684         };
1685         int in_progress;
1686         int ret;
1687         int i;
1688         int fdmnt;
1689         int print_raw = 0;
1690         int do_stats_per_dev = 0;
1691         int c;
1692         char fsid[BTRFS_UUID_UNPARSED_SIZE];
1693         int fdres = -1;
1694         int err = 0;
1695         DIR *dirstream = NULL;
1696
1697         optind = 1;
1698         while ((c = getopt(argc, argv, "dR")) != -1) {
1699                 switch (c) {
1700                 case 'd':
1701                         do_stats_per_dev = 1;
1702                         break;
1703                 case 'R':
1704                         print_raw = 1;
1705                         break;
1706                 case '?':
1707                 default:
1708                         usage(cmd_scrub_status_usage);
1709                 }
1710         }
1711
1712         if (check_argc_exact(argc - optind, 1))
1713                 usage(cmd_scrub_status_usage);
1714
1715         path = argv[optind];
1716
1717         fdmnt = open_path_or_dev_mnt(path, &dirstream);
1718
1719         if (fdmnt < 0) {
1720                 if (errno == EINVAL)
1721                         fprintf(stderr,
1722                                 "ERROR: '%s' is not a mounted btrfs device\n",
1723                                 path);
1724                 else
1725                         fprintf(stderr, "ERROR: can't access '%s': %s\n",
1726                                 path, strerror(errno));
1727                 return 1;
1728         }
1729
1730         ret = get_fs_info(path, &fi_args, &di_args);
1731         if (ret) {
1732                 fprintf(stderr, "ERROR: getting dev info for scrub failed: "
1733                                 "%s\n", strerror(-ret));
1734                 err = 1;
1735                 goto out;
1736         }
1737         if (!fi_args.num_devices) {
1738                 fprintf(stderr, "ERROR: no devices found\n");
1739                 err = 1;
1740                 goto out;
1741         }
1742
1743         uuid_unparse(fi_args.fsid, fsid);
1744
1745         fdres = socket(AF_UNIX, SOCK_STREAM, 0);
1746         if (fdres == -1) {
1747                 fprintf(stderr, "ERROR: failed to create socket to "
1748                         "receive progress information: %s\n",
1749                         strerror(errno));
1750                 err = 1;
1751                 goto out;
1752         }
1753         scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid,
1754                         NULL, addr.sun_path, sizeof(addr.sun_path));
1755         /* ignore EOVERFLOW, just use shorter name and hope for the best */
1756         addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1757         ret = connect(fdres, (struct sockaddr *)&addr, sizeof(addr));
1758         if (ret == -1) {
1759                 close(fdres);
1760                 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1761                 if (fdres < 0 && fdres != -ENOENT) {
1762                         fprintf(stderr, "WARNING: failed to open status file: "
1763                                 "%s\n", strerror(-fdres));
1764                         err = 1;
1765                         goto out;
1766                 }
1767         }
1768
1769         if (fdres >= 0) {
1770                 past_scrubs = scrub_read_file(fdres, 1);
1771                 if (IS_ERR(past_scrubs))
1772                         fprintf(stderr, "WARNING: failed to read status: %s\n",
1773                                 strerror(-PTR_ERR(past_scrubs)));
1774         }
1775         in_progress = is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices);
1776
1777         printf("scrub status for %s\n", fsid);
1778
1779         if (do_stats_per_dev) {
1780                 for (i = 0; i < fi_args.num_devices; ++i) {
1781                         last_scrub = last_dev_scrub(past_scrubs,
1782                                                         di_args[i].devid);
1783                         if (!last_scrub) {
1784                                 print_scrub_dev(&di_args[i], NULL, print_raw,
1785                                                 NULL, NULL);
1786                                 continue;
1787                         }
1788                         last_scrub->stats.in_progress = in_progress;
1789                         print_scrub_dev(&di_args[i], &last_scrub->p, print_raw,
1790                                         last_scrub->stats.finished ?
1791                                                         "history" : "status",
1792                                         &last_scrub->stats);
1793                 }
1794         } else {
1795                 init_fs_stat(&fs_stat);
1796                 fs_stat.s.in_progress = in_progress;
1797                 for (i = 0; i < fi_args.num_devices; ++i) {
1798                         last_scrub = last_dev_scrub(past_scrubs,
1799                                                         di_args[i].devid);
1800                         if (!last_scrub)
1801                                 continue;
1802                         add_to_fs_stat(&last_scrub->p, &last_scrub->stats,
1803                                         &fs_stat);
1804                 }
1805                 print_fs_stat(&fs_stat, print_raw);
1806         }
1807
1808 out:
1809         free_history(past_scrubs);
1810         free(di_args);
1811         if (fdres > -1)
1812                 close(fdres);
1813         close_file_or_dir(fdmnt, dirstream);
1814
1815         return !!err;
1816 }
1817
1818 static const char scrub_cmd_group_info[] =
1819 "verify checksums of data and metadata";
1820
1821 const struct cmd_group scrub_cmd_group = {
1822         scrub_cmd_group_usage, scrub_cmd_group_info, {
1823                 { "start", cmd_scrub_start, cmd_scrub_start_usage, NULL, 0 },
1824                 { "cancel", cmd_scrub_cancel, cmd_scrub_cancel_usage, NULL, 0 },
1825                 { "resume", cmd_scrub_resume, cmd_scrub_resume_usage, NULL, 0 },
1826                 { "status", cmd_scrub_status, cmd_scrub_status_usage, NULL, 0 },
1827                 NULL_CMD_STRUCT
1828         }
1829 };
1830
1831 int cmd_scrub(int argc, char **argv)
1832 {
1833         return handle_command_group(&scrub_cmd_group, argc, argv);
1834 }