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