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