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