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