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