2 * Copyright (C) 2011 STRATO. All rights reserved.
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.
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.
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.
19 #include "kerncompat.h"
21 #include <sys/ioctl.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <sys/syscall.h>
30 #include <uuid/uuid.h>
46 static const char * const scrub_cmd_group_usage[] = {
47 "btrfs scrub <command> [options] <path>|<device>",
51 #define SCRUB_DATA_FILE "/var/lib/btrfs/scrub.status"
52 #define SCRUB_PROGRESS_SOCKET_PATH "/var/lib/btrfs/scrub.progress"
53 #define SCRUB_FILE_VERSION_PREFIX "scrub status"
54 #define SCRUB_FILE_VERSION "1"
65 /* TBD: replace with #include "linux/ioprio.h" in some years */
66 #if !defined (IOPRIO_H)
67 #define IOPRIO_WHO_PROCESS 1
68 #define IOPRIO_CLASS_SHIFT 13
69 #define IOPRIO_PRIO_VALUE(class, data) \
70 (((class) << IOPRIO_CLASS_SHIFT) | (data))
71 #define IOPRIO_CLASS_IDLE 3
74 struct scrub_progress {
75 struct btrfs_ioctl_scrub_args scrub_args;
79 struct scrub_stats stats;
80 struct scrub_file_record *resumed;
82 pthread_mutex_t progress_mutex;
87 struct scrub_file_record {
88 u8 fsid[BTRFS_FSID_SIZE];
90 struct scrub_stats stats;
91 struct btrfs_scrub_progress p;
94 struct scrub_progress_cycle {
98 struct btrfs_ioctl_fs_info_args *fi;
99 struct scrub_progress *progress;
100 struct scrub_progress *shared_progress;
101 pthread_mutex_t *write_mutex;
104 struct scrub_fs_stat {
105 struct btrfs_scrub_progress p;
106 struct scrub_stats s;
110 static void print_scrub_full(struct btrfs_scrub_progress *sp)
112 printf("\tdata_extents_scrubbed: %lld\n", sp->data_extents_scrubbed);
113 printf("\ttree_extents_scrubbed: %lld\n", sp->tree_extents_scrubbed);
114 printf("\tdata_bytes_scrubbed: %lld\n", sp->data_bytes_scrubbed);
115 printf("\ttree_bytes_scrubbed: %lld\n", sp->tree_bytes_scrubbed);
116 printf("\tread_errors: %lld\n", sp->read_errors);
117 printf("\tcsum_errors: %lld\n", sp->csum_errors);
118 printf("\tverify_errors: %lld\n", sp->verify_errors);
119 printf("\tno_csum: %lld\n", sp->no_csum);
120 printf("\tcsum_discards: %lld\n", sp->csum_discards);
121 printf("\tsuper_errors: %lld\n", sp->super_errors);
122 printf("\tmalloc_errors: %lld\n", sp->malloc_errors);
123 printf("\tuncorrectable_errors: %lld\n", sp->uncorrectable_errors);
124 printf("\tunverified_errors: %lld\n", sp->unverified_errors);
125 printf("\tcorrected_errors: %lld\n", sp->corrected_errors);
126 printf("\tlast_physical: %lld\n", sp->last_physical);
129 #define ERR(test, ...) do { \
131 fprintf(stderr, __VA_ARGS__); \
134 #define PRINT_SCRUB_ERROR(test, desc) do { \
136 printf(" %s=%llu", desc, test); \
139 static void print_scrub_summary(struct btrfs_scrub_progress *p)
144 err_cnt = p->read_errors +
149 err_cnt2 = p->corrected_errors + p->uncorrectable_errors;
151 if (p->malloc_errors)
152 printf("*** WARNING: memory allocation failed while scrubbing. "
153 "results may be inaccurate\n");
155 printf("\ttotal bytes scrubbed: %s with %llu errors\n",
156 pretty_size(p->data_bytes_scrubbed + p->tree_bytes_scrubbed),
157 max(err_cnt, err_cnt2));
159 if (err_cnt || err_cnt2) {
160 printf("\terror details:");
161 PRINT_SCRUB_ERROR(p->read_errors, "read");
162 PRINT_SCRUB_ERROR(p->super_errors, "super");
163 PRINT_SCRUB_ERROR(p->verify_errors, "verify");
164 PRINT_SCRUB_ERROR(p->csum_errors, "csum");
166 printf("\tcorrected errors: %llu, uncorrectable errors: %llu, "
167 "unverified errors: %llu\n", p->corrected_errors,
168 p->uncorrectable_errors, p->unverified_errors);
172 #define _SCRUB_FS_STAT(p, name, fs_stat) do { \
173 fs_stat->p.name += p->name; \
176 #define _SCRUB_FS_STAT_MIN(ss, name, fs_stat) \
178 if (fs_stat->s.name > ss->name) { \
179 fs_stat->s.name = ss->name; \
183 #define _SCRUB_FS_STAT_ZMIN(ss, name, fs_stat) \
185 if (!fs_stat->s.name || fs_stat->s.name > ss->name) { \
186 fs_stat->s.name = ss->name; \
190 #define _SCRUB_FS_STAT_ZMAX(ss, name, fs_stat) \
192 if (!(fs_stat)->s.name || (fs_stat)->s.name < (ss)->name) { \
193 (fs_stat)->s.name = (ss)->name; \
197 static void add_to_fs_stat(struct btrfs_scrub_progress *p,
198 struct scrub_stats *ss,
199 struct scrub_fs_stat *fs_stat)
201 _SCRUB_FS_STAT(p, data_extents_scrubbed, fs_stat);
202 _SCRUB_FS_STAT(p, tree_extents_scrubbed, fs_stat);
203 _SCRUB_FS_STAT(p, data_bytes_scrubbed, fs_stat);
204 _SCRUB_FS_STAT(p, tree_bytes_scrubbed, fs_stat);
205 _SCRUB_FS_STAT(p, read_errors, fs_stat);
206 _SCRUB_FS_STAT(p, csum_errors, fs_stat);
207 _SCRUB_FS_STAT(p, verify_errors, fs_stat);
208 _SCRUB_FS_STAT(p, no_csum, fs_stat);
209 _SCRUB_FS_STAT(p, csum_discards, fs_stat);
210 _SCRUB_FS_STAT(p, super_errors, fs_stat);
211 _SCRUB_FS_STAT(p, malloc_errors, fs_stat);
212 _SCRUB_FS_STAT(p, uncorrectable_errors, fs_stat);
213 _SCRUB_FS_STAT(p, corrected_errors, fs_stat);
214 _SCRUB_FS_STAT(p, last_physical, fs_stat);
215 _SCRUB_FS_STAT_ZMIN(ss, t_start, fs_stat);
216 _SCRUB_FS_STAT_ZMIN(ss, t_resumed, fs_stat);
217 _SCRUB_FS_STAT_ZMAX(ss, duration, fs_stat);
218 _SCRUB_FS_STAT_ZMAX(ss, canceled, fs_stat);
219 _SCRUB_FS_STAT_MIN(ss, finished, fs_stat);
222 static void init_fs_stat(struct scrub_fs_stat *fs_stat)
224 memset(fs_stat, 0, sizeof(*fs_stat));
225 fs_stat->s.finished = 1;
228 static void _print_scrub_ss(struct scrub_stats *ss)
235 if (!ss || !ss->t_start) {
236 printf("\tno stats available\n");
240 localtime_r(&ss->t_resumed, &tm);
241 strftime(t, sizeof(t), "%c", &tm);
242 t[sizeof(t) - 1] = '\0';
243 printf("\tscrub resumed at %s", t);
245 localtime_r(&ss->t_start, &tm);
246 strftime(t, sizeof(t), "%c", &tm);
247 t[sizeof(t) - 1] = '\0';
248 printf("\tscrub started at %s", t);
251 seconds = ss->duration;
252 hours = ss->duration / (60 * 60);
253 gmtime_r(&seconds, &tm);
254 strftime(t, sizeof(t), "%M:%S", &tm);
255 if (ss->finished && !ss->canceled) {
256 printf(" and finished after %02u:%s\n", hours, t);
257 } else if (ss->canceled) {
258 printf(" and was aborted after %02u:%s\n", hours, t);
261 printf(", running for %02u:%s\n", hours, t);
263 printf(", interrupted after %02u:%s, not running\n",
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)
272 printf("scrub device %s (id %llu) %s\n", di->path, di->devid,
273 append ? append : "");
281 print_scrub_summary(p);
285 static void print_fs_stat(struct scrub_fs_stat *fs_stat, int raw)
287 _print_scrub_ss(&fs_stat->s);
290 print_scrub_full(&fs_stat->p);
292 print_scrub_summary(&fs_stat->p);
295 static void free_history(struct scrub_file_record **last_scrubs)
297 struct scrub_file_record **l = last_scrubs;
306 * cancels a running scrub and makes the master process record the current
307 * progress status before exiting.
309 static int cancel_fd = -1;
310 static void scrub_sigint_record_progress(int signal)
314 ret = ioctl(cancel_fd, BTRFS_IOC_SCRUB_CANCEL, NULL);
316 perror("Scrub cancel failed");
319 static int scrub_handle_sigint_parent(void)
321 struct sigaction sa = {
322 .sa_handler = SIG_IGN,
323 .sa_flags = SA_RESTART,
326 return sigaction(SIGINT, &sa, NULL);
329 static int scrub_handle_sigint_child(int fd)
331 struct sigaction sa = {
332 .sa_handler = fd == -1 ? SIG_DFL : scrub_sigint_record_progress,
336 return sigaction(SIGINT, &sa, NULL);
339 static int scrub_datafile(const char *fn_base, const char *fn_local,
340 const char *fn_tmp, char *datafile, int size)
345 datafile[end + 1] = '\0';
346 strncpy(datafile, fn_base, end);
347 ret = strlen(datafile);
353 strncpy(datafile + ret + 1, fn_local, end - ret - 1);
354 ret = strlen(datafile);
361 strncpy(datafile + ret + 1, fn_tmp, end - ret - 1);
362 ret = strlen(datafile);
371 static int scrub_open_file(const char *datafile, int m)
376 fd = open(datafile, m, 0600);
380 ret = flock(fd, LOCK_EX|LOCK_NB);
390 static int scrub_open_file_r(const char *fn_base, const char *fn_local)
393 char datafile[PATH_MAX];
394 ret = scrub_datafile(fn_base, fn_local, NULL,
395 datafile, sizeof(datafile));
398 return scrub_open_file(datafile, O_RDONLY);
401 static int scrub_open_file_w(const char *fn_base, const char *fn_local,
405 char datafile[PATH_MAX];
406 ret = scrub_datafile(fn_base, fn_local, tmp,
407 datafile, sizeof(datafile));
410 return scrub_open_file(datafile, O_WRONLY|O_CREAT);
413 static int scrub_rename_file(const char *fn_base, const char *fn_local,
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));
423 ret = scrub_datafile(fn_base, fn_local, NULL,
424 datafile_new, sizeof(datafile_new));
427 ret = rename(datafile_old, datafile_new);
428 return ret ? -errno : 0;
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); \
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
440 static int scrub_kvread(int *i, int len, int avail, const char *buf,
441 const char *key, u64 *dest)
445 if (*i + len + 1 < avail && strncmp(&buf[*i], key, len - 1) == 0) {
450 for (j = 0; isdigit(buf[*i + j]) && *i + j < avail; ++j)
454 *dest = atoll(&buf[*i]);
462 #define _SCRUB_INVALID do { \
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__); \
471 static struct scrub_file_record **scrub_read_file(int fd, int report_errors)
484 char empty_uuid[BTRFS_FSID_SIZE] = {0};
485 struct scrub_file_record **p = NULL;
488 old_avail = avail - i;
489 BUG_ON(old_avail < 0);
491 memmove(l, l + i, old_avail);
492 avail = read(fd, l + old_avail, sizeof(l) - old_avail);
495 if (avail == 0 && old_avail == 0) {
497 memcmp(p[curr]->fsid, empty_uuid, BTRFS_FSID_SIZE) == 0) {
499 } else if (curr == -1) {
500 p = ERR_PTR(-ENODATA);
505 return ERR_PTR(-errno);
511 case 0: /* start of file */
512 ret = scrub_kvread(&i,
513 sizeof(SCRUB_FILE_VERSION_PREFIX), avail, l,
514 SCRUB_FILE_VERSION_PREFIX, &version);
517 if (version != atoll(SCRUB_FILE_VERSION))
518 return ERR_PTR(-ENOTSUP);
521 case 1: /* start of line, alloc */
523 * this state makes sure we have a complete line in
524 * further processing, so we don't need wrap-tracking
527 if (!eof && !memchr(l + i, '\n', avail - i))
530 if (curr > -1 && memcmp(p[curr]->fsid, empty_uuid,
531 BTRFS_FSID_SIZE) == 0) {
536 p = realloc(p, (curr + 2) * sizeof(*p));
538 p[curr] = malloc(sizeof(**p));
540 return ERR_PTR(-errno);
541 memset(p[curr], 0, sizeof(**p));
545 case 2: /* start of line, skip space */
546 while (isspace(l[i]) && i < avail) {
552 (!eof && !memchr(l + i, '\n', avail - i)))
556 case 3: /* read fsid */
559 for (j = 0; l[i + j] != ':' && i + j < avail; ++j)
561 if (i + j + 1 >= avail)
563 if (j != BTRFS_UUID_UNPARSED_SIZE - 1)
566 ret = uuid_parse(l + i, p[curr]->fsid);
572 case 4: /* read dev id */
573 for (j = 0; isdigit(l[i + j]) && i+j < avail; ++j)
575 if (j == 0 || i + j + 1 >= avail)
577 p[curr]->devid = atoll(&l[i]);
581 case 5: /* read key/value pair */
583 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
585 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
587 _SCRUB_KVREAD(ret, &i, tree_extents_scrubbed, avail, l,
589 _SCRUB_KVREAD(ret, &i, data_bytes_scrubbed, avail, l,
591 _SCRUB_KVREAD(ret, &i, tree_bytes_scrubbed, avail, l,
593 _SCRUB_KVREAD(ret, &i, read_errors, avail, l,
595 _SCRUB_KVREAD(ret, &i, csum_errors, avail, l,
597 _SCRUB_KVREAD(ret, &i, verify_errors, avail, l,
599 _SCRUB_KVREAD(ret, &i, no_csum, avail, l,
601 _SCRUB_KVREAD(ret, &i, csum_discards, avail, l,
603 _SCRUB_KVREAD(ret, &i, super_errors, avail, l,
605 _SCRUB_KVREAD(ret, &i, malloc_errors, avail, l,
607 _SCRUB_KVREAD(ret, &i, uncorrectable_errors, avail, l,
609 _SCRUB_KVREAD(ret, &i, corrected_errors, avail, l,
611 _SCRUB_KVREAD(ret, &i, last_physical, avail, l,
613 _SCRUB_KVREAD(ret, &i, finished, avail, l,
615 _SCRUB_KVREAD(ret, &i, t_start, avail, l,
616 (u64 *)&p[curr]->stats);
617 _SCRUB_KVREAD(ret, &i, t_resumed, avail, l,
618 (u64 *)&p[curr]->stats);
619 _SCRUB_KVREAD(ret, &i, duration, avail, l,
620 (u64 *)&p[curr]->stats);
621 _SCRUB_KVREAD(ret, &i, canceled, avail, l,
627 case 6: /* after number */
630 else if (l[i] == '\n')
636 case 99: /* skip rest of line */
641 if (l[i - 1] == '\n') {
653 static int scrub_write_buf(int fd, const void *data, int len)
656 ret = write(fd, data, len);
660 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
661 __attribute__ ((format (printf, 4, 5)));
662 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
668 ret = vsnprintf(buf, max, fmt, args);
672 return scrub_write_buf(fd, buf, ret);
675 #define _SCRUB_SUM(dest, data, name) dest->scrub_args.progress.name = \
676 data->resumed->p.name + data->scrub_args.progress.name
678 static struct scrub_progress *scrub_resumed_stats(struct scrub_progress *data,
679 struct scrub_progress *dest)
681 if (!data->resumed || data->skip)
684 _SCRUB_SUM(dest, data, data_extents_scrubbed);
685 _SCRUB_SUM(dest, data, tree_extents_scrubbed);
686 _SCRUB_SUM(dest, data, data_bytes_scrubbed);
687 _SCRUB_SUM(dest, data, tree_bytes_scrubbed);
688 _SCRUB_SUM(dest, data, read_errors);
689 _SCRUB_SUM(dest, data, csum_errors);
690 _SCRUB_SUM(dest, data, verify_errors);
691 _SCRUB_SUM(dest, data, no_csum);
692 _SCRUB_SUM(dest, data, csum_discards);
693 _SCRUB_SUM(dest, data, super_errors);
694 _SCRUB_SUM(dest, data, malloc_errors);
695 _SCRUB_SUM(dest, data, uncorrectable_errors);
696 _SCRUB_SUM(dest, data, corrected_errors);
697 _SCRUB_SUM(dest, data, last_physical);
698 dest->stats.canceled = data->stats.canceled;
699 dest->stats.finished = data->stats.finished;
700 dest->stats.t_resumed = data->stats.t_start;
701 dest->stats.t_start = data->resumed->stats.t_start;
702 dest->stats.duration = data->resumed->stats.duration +
703 data->stats.duration;
704 dest->scrub_args.devid = data->scrub_args.devid;
708 #define _SCRUB_KVWRITE(fd, buf, name, use) \
709 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
710 use->scrub_args.progress.name)
712 #define _SCRUB_KVWRITE_STATS(fd, buf, name, use) \
713 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
716 static int scrub_kvwrite(int fd, char *buf, int max, const char *key, u64 val)
718 return scrub_writev(fd, buf, max, "|%s:%lld", key, val);
721 static int scrub_write_file(int fd, const char *fsid,
722 struct scrub_progress *data, int n)
727 struct scrub_progress local;
728 struct scrub_progress *use;
733 /* each -1 is to subtract one \0 byte, the + 2 is for ':' and '\n' */
734 ret = scrub_write_buf(fd, SCRUB_FILE_VERSION_PREFIX ":"
735 SCRUB_FILE_VERSION "\n",
736 (sizeof(SCRUB_FILE_VERSION_PREFIX) - 1) +
737 (sizeof(SCRUB_FILE_VERSION) - 1) + 2);
741 for (i = 0; i < n; ++i) {
742 use = scrub_resumed_stats(&data[i], &local);
743 if (scrub_write_buf(fd, fsid, strlen(fsid)) ||
744 scrub_write_buf(fd, ":", 1) ||
745 scrub_writev(fd, buf, sizeof(buf), "%lld",
746 use->scrub_args.devid) ||
747 scrub_write_buf(fd, buf, ret) ||
748 _SCRUB_KVWRITE(fd, buf, data_extents_scrubbed, use) ||
749 _SCRUB_KVWRITE(fd, buf, tree_extents_scrubbed, use) ||
750 _SCRUB_KVWRITE(fd, buf, data_bytes_scrubbed, use) ||
751 _SCRUB_KVWRITE(fd, buf, tree_bytes_scrubbed, use) ||
752 _SCRUB_KVWRITE(fd, buf, read_errors, use) ||
753 _SCRUB_KVWRITE(fd, buf, csum_errors, use) ||
754 _SCRUB_KVWRITE(fd, buf, verify_errors, use) ||
755 _SCRUB_KVWRITE(fd, buf, no_csum, use) ||
756 _SCRUB_KVWRITE(fd, buf, csum_discards, use) ||
757 _SCRUB_KVWRITE(fd, buf, super_errors, use) ||
758 _SCRUB_KVWRITE(fd, buf, malloc_errors, use) ||
759 _SCRUB_KVWRITE(fd, buf, uncorrectable_errors, use) ||
760 _SCRUB_KVWRITE(fd, buf, corrected_errors, use) ||
761 _SCRUB_KVWRITE(fd, buf, last_physical, use) ||
762 _SCRUB_KVWRITE_STATS(fd, buf, t_start, use) ||
763 _SCRUB_KVWRITE_STATS(fd, buf, t_resumed, use) ||
764 _SCRUB_KVWRITE_STATS(fd, buf, duration, use) ||
765 _SCRUB_KVWRITE_STATS(fd, buf, canceled, use) ||
766 _SCRUB_KVWRITE_STATS(fd, buf, finished, use) ||
767 scrub_write_buf(fd, "\n", 1)) {
775 static int scrub_write_progress(pthread_mutex_t *m, const char *fsid,
776 struct scrub_progress *data, int n)
783 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old);
789 ret = pthread_mutex_lock(m);
795 fd = scrub_open_file_w(SCRUB_DATA_FILE, fsid, "tmp");
800 err = scrub_write_file(fd, fsid, data, n);
803 err = scrub_rename_file(SCRUB_DATA_FILE, fsid, "tmp");
814 ret = pthread_mutex_unlock(m);
819 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old);
827 static void *scrub_one_dev(void *ctx)
829 struct scrub_progress *sp = ctx;
833 sp->stats.canceled = 0;
834 sp->stats.duration = 0;
835 sp->stats.finished = 0;
837 ret = syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0,
838 IOPRIO_PRIO_VALUE(sp->ioprio_class,
839 sp->ioprio_classdata));
842 "WARNING: setting ioprio failed: %s (ignored).\n",
845 ret = ioctl(sp->fd, BTRFS_IOC_SCRUB, &sp->scrub_args);
846 gettimeofday(&tv, NULL);
848 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
849 sp->stats.canceled = !!ret;
850 sp->ioctl_errno = errno;
851 ret = pthread_mutex_lock(&sp->progress_mutex);
853 return ERR_PTR(-ret);
854 sp->stats.finished = 1;
855 ret = pthread_mutex_unlock(&sp->progress_mutex);
857 return ERR_PTR(-ret);
862 static void *progress_one_dev(void *ctx)
864 struct scrub_progress *sp = ctx;
866 sp->ret = ioctl(sp->fd, BTRFS_IOC_SCRUB_PROGRESS, &sp->scrub_args);
867 sp->ioctl_errno = errno;
872 /* nb: returns a negative errno via ERR_PTR */
873 static void *scrub_progress_cycle(void *ctx)
876 int perr = 0; /* positive / pthread error returns */
879 char fsid[BTRFS_UUID_UNPARSED_SIZE];
880 struct scrub_progress *sp;
881 struct scrub_progress *sp_last;
882 struct scrub_progress *sp_shared;
884 struct scrub_progress_cycle *spc = ctx;
885 int ndev = spc->fi->num_devices;
889 struct pollfd accept_poll_fd = {
894 struct pollfd write_poll_fd = {
898 struct sockaddr_un peer;
899 socklen_t peer_size = sizeof(peer);
901 perr = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old);
905 uuid_unparse(spc->fi->fsid, fsid);
907 for (i = 0; i < ndev; ++i) {
908 sp = &spc->progress[i];
909 sp_last = &spc->progress[i + ndev];
910 sp_shared = &spc->shared_progress[i];
911 sp->scrub_args.devid = sp_last->scrub_args.devid =
912 sp_shared->scrub_args.devid;
913 sp->fd = sp_last->fd = spc->fdmnt;
914 sp->stats.t_start = sp_last->stats.t_start =
915 sp_shared->stats.t_start;
916 sp->resumed = sp_last->resumed = sp_shared->resumed;
917 sp->skip = sp_last->skip = sp_shared->skip;
918 sp->stats.finished = sp_last->stats.finished =
919 sp_shared->stats.finished;
923 ret = poll(&accept_poll_fd, 1, 5 * 1000);
929 peer_fd = accept(spc->prg_fd, (struct sockaddr *)&peer,
931 gettimeofday(&tv, NULL);
934 for (i = 0; i < ndev; ++i) {
935 sp = &spc->progress[this * ndev + i];
936 sp_last = &spc->progress[last * ndev + i];
937 sp_shared = &spc->shared_progress[i];
938 if (sp->stats.finished)
940 progress_one_dev(sp);
941 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
944 if (sp->ioctl_errno != ENOTCONN &&
945 sp->ioctl_errno != ENODEV) {
946 ret = -sp->ioctl_errno;
950 * scrub finished or device removed, check the
951 * finished flag. if unset, just use the last
952 * result we got for the current write and go
953 * on. flag should be set on next cycle, then.
955 perr = pthread_setcancelstate(
956 PTHREAD_CANCEL_DISABLE, &old);
959 perr = pthread_mutex_lock(&sp_shared->progress_mutex);
962 if (!sp_shared->stats.finished) {
963 perr = pthread_mutex_unlock(
964 &sp_shared->progress_mutex);
967 perr = pthread_setcancelstate(
968 PTHREAD_CANCEL_ENABLE, &old);
971 memcpy(sp, sp_last, sizeof(*sp));
974 perr = pthread_mutex_unlock(&sp_shared->progress_mutex);
977 perr = pthread_setcancelstate(
978 PTHREAD_CANCEL_ENABLE, &old);
981 memcpy(sp, sp_shared, sizeof(*sp));
982 memcpy(sp_last, sp_shared, sizeof(*sp));
985 write_poll_fd.fd = peer_fd;
986 ret = poll(&write_poll_fd, 1, 0);
992 ret = scrub_write_file(
994 &spc->progress[this * ndev], ndev);
1001 if (!spc->do_record)
1003 ret = scrub_write_progress(spc->write_mutex, fsid,
1004 &spc->progress[this * ndev], ndev);
1013 return ERR_PTR(ret);
1016 static struct scrub_file_record *last_dev_scrub(
1017 struct scrub_file_record *const *const past_scrubs, u64 devid)
1021 if (!past_scrubs || IS_ERR(past_scrubs))
1024 for (i = 0; past_scrubs[i]; ++i)
1025 if (past_scrubs[i]->devid == devid)
1026 return past_scrubs[i];
1031 static int mkdir_p(char *path)
1036 for (i = 1; i < strlen(path); ++i) {
1040 ret = mkdir(path, 0777);
1041 if (ret && errno != EEXIST)
1049 static int is_scrub_running_on_fs(struct btrfs_ioctl_fs_info_args *fi_args,
1050 struct btrfs_ioctl_dev_info_args *di_args,
1051 struct scrub_file_record **past_scrubs)
1055 if (!fi_args || !di_args || !past_scrubs)
1058 for (i = 0; i < fi_args->num_devices; i++) {
1059 struct scrub_file_record *sfr =
1060 last_dev_scrub(past_scrubs, di_args[i].devid);
1064 if (!(sfr->stats.finished || sfr->stats.canceled))
1070 static int is_scrub_running_in_kernel(int fd,
1071 struct btrfs_ioctl_dev_info_args *di_args, u64 max_devices)
1073 struct scrub_progress sp;
1077 for (i = 0; i < max_devices; i++) {
1078 memset(&sp, 0, sizeof(sp));
1079 sp.scrub_args.devid = di_args[i].devid;
1080 ret = ioctl(fd, BTRFS_IOC_SCRUB_PROGRESS, &sp.scrub_args);
1088 static const char * const cmd_scrub_start_usage[];
1089 static const char * const cmd_scrub_resume_usage[];
1091 static int scrub_start(int argc, char **argv, int resume)
1101 int e_uncorrectable = 0;
1102 int e_correctable = 0;
1105 int do_background = 1;
1111 int do_stats_per_dev = 0;
1112 int ioprio_class = IOPRIO_CLASS_IDLE;
1113 int ioprio_classdata = 0;
1117 struct btrfs_ioctl_fs_info_args fi_args;
1118 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1119 struct scrub_progress *sp = NULL;
1120 struct scrub_fs_stat fs_stat;
1122 struct sockaddr_un addr = {
1123 .sun_family = AF_UNIX,
1125 pthread_t *t_devs = NULL;
1127 struct scrub_file_record **past_scrubs = NULL;
1128 struct scrub_file_record *last_scrub = NULL;
1129 char *datafile = strdup(SCRUB_DATA_FILE);
1130 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1131 char sock_path[PATH_MAX] = "";
1132 struct scrub_progress_cycle spc;
1133 pthread_mutex_t spc_write_mutex = PTHREAD_MUTEX_INITIALIZER;
1136 DIR *dirstream = NULL;
1138 int nothing_to_resume = 0;
1141 while ((c = getopt(argc, argv, "BdqrRc:n:f")) != -1) {
1149 do_stats_per_dev = 1;
1161 ioprio_class = (int)strtol(optarg, NULL, 10);
1164 ioprio_classdata = (int)strtol(optarg, NULL, 10);
1171 usage(resume ? cmd_scrub_resume_usage :
1172 cmd_scrub_start_usage);
1176 /* try to catch most error cases before forking */
1178 if (check_argc_exact(argc - optind, 1)) {
1179 usage(resume ? cmd_scrub_resume_usage :
1180 cmd_scrub_start_usage);
1183 spc.progress = NULL;
1184 if (do_quiet && do_print)
1187 if (mkdir_p(datafile)) {
1188 ERR(!do_quiet, "WARNING: cannot create scrub data "
1189 "file, mkdir %s failed: %s. Status recording "
1190 "disabled\n", datafile, strerror(errno));
1195 path = argv[optind];
1197 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1200 if (errno == EINVAL)
1202 "ERROR: '%s' is not a mounted btrfs device\n",
1205 ERR(!do_quiet, "ERROR: can't access '%s': %s\n",
1206 path, strerror(errno));
1210 ret = get_fs_info(path, &fi_args, &di_args);
1212 ERR(!do_quiet, "ERROR: getting dev info for scrub failed: "
1213 "%s\n", strerror(-ret));
1217 if (!fi_args.num_devices) {
1218 ERR(!do_quiet, "ERROR: no devices found\n");
1223 uuid_unparse(fi_args.fsid, fsid);
1224 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1225 if (fdres < 0 && fdres != -ENOENT) {
1226 ERR(!do_quiet, "WARNING: failed to open status file: "
1227 "%s\n", strerror(-fdres));
1228 } else if (fdres >= 0) {
1229 past_scrubs = scrub_read_file(fdres, !do_quiet);
1230 if (IS_ERR(past_scrubs))
1231 ERR(!do_quiet, "WARNING: failed to read status file: "
1232 "%s\n", strerror(-PTR_ERR(past_scrubs)));
1237 * Check for stale information in the status file, ie. if it's
1238 * canceled=0, finished=0 but no scrub is running.
1240 if (!is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices))
1244 * check whether any involved device is already busy running a
1245 * scrub. This would cause damaged status messages and the state
1246 * "aborted" without the explanation that a scrub was already
1247 * running. Therefore check it first, prevent it and give some
1248 * feedback to the user if scrub is already running.
1249 * Note that if scrub is started with a block device as the
1250 * parameter, only that particular block device is checked. It
1251 * is a normal mode of operation to start scrub on multiple
1252 * single devices, there is no reason to prevent this.
1254 if (!force && is_scrub_running_on_fs(&fi_args, di_args, past_scrubs)) {
1256 "ERROR: scrub is already running.\n"
1257 "To cancel use 'btrfs scrub cancel %s'.\n"
1258 "To see the status use 'btrfs scrub status [-d] %s'.\n",
1264 t_devs = malloc(fi_args.num_devices * sizeof(*t_devs));
1265 sp = calloc(fi_args.num_devices, sizeof(*sp));
1266 spc.progress = calloc(fi_args.num_devices * 2, sizeof(*spc.progress));
1268 if (!t_devs || !sp || !spc.progress) {
1269 ERR(!do_quiet, "ERROR: scrub failed: %s", strerror(errno));
1274 for (i = 0; i < fi_args.num_devices; ++i) {
1275 devid = di_args[i].devid;
1276 ret = pthread_mutex_init(&sp[i].progress_mutex, NULL);
1278 ERR(!do_quiet, "ERROR: pthread_mutex_init failed: "
1279 "%s\n", strerror(ret));
1283 last_scrub = last_dev_scrub(past_scrubs, devid);
1284 sp[i].scrub_args.devid = devid;
1286 if (resume && last_scrub && (last_scrub->stats.canceled ||
1287 !last_scrub->stats.finished)) {
1289 sp[i].scrub_args.start = last_scrub->p.last_physical;
1290 sp[i].resumed = last_scrub;
1291 } else if (resume) {
1294 sp[i].resumed = last_scrub;
1298 sp[i].scrub_args.start = 0ll;
1299 sp[i].resumed = NULL;
1302 sp[i].scrub_args.end = (u64)-1ll;
1303 sp[i].scrub_args.flags = readonly ? BTRFS_SCRUB_READONLY : 0;
1304 sp[i].ioprio_class = ioprio_class;
1305 sp[i].ioprio_classdata = ioprio_classdata;
1308 if (!n_start && !n_resume) {
1310 printf("scrub: nothing to resume for %s, fsid %s\n",
1312 nothing_to_resume = 1;
1316 ret = prg_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1318 ret = scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid, NULL,
1319 sock_path, sizeof(sock_path));
1320 /* ignore EOVERFLOW, try using a shorter path for the socket */
1321 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1322 strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1);
1323 ret = bind(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1324 if (ret != -1 || errno != EADDRINUSE)
1327 * bind failed with EADDRINUSE. so let's see if anyone answers
1328 * when we make a call to the socket ...
1330 ret = connect(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1331 if (!ret || errno != ECONNREFUSED) {
1332 /* ... yes, so scrub must be running. error out */
1333 fprintf(stderr, "ERROR: scrub already running\n");
1339 * ... no, this means someone left us alone with an unused
1340 * socket in the file system. remove it and try again.
1342 ret = unlink(sock_path);
1345 ret = listen(prg_fd, 100);
1347 ERR(!do_quiet, "WARNING: failed to open the progress status "
1348 "socket at %s: %s. Progress cannot be queried\n",
1349 sock_path[0] ? sock_path : SCRUB_PROGRESS_SOCKET_PATH,
1360 /* write all-zero progress file for a start */
1361 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1362 fi_args.num_devices);
1364 ERR(!do_quiet, "WARNING: failed to write the progress "
1365 "status file: %s. Status recording disabled\n",
1371 if (do_background) {
1374 ERR(!do_quiet, "ERROR: cannot scrub, fork failed: "
1375 "%s\n", strerror(errno));
1382 scrub_handle_sigint_parent();
1384 printf("scrub %s on %s, fsid %s (pid=%d)\n",
1385 n_start ? "started" : "resumed",
1393 ERR(!do_quiet, "ERROR: wait failed: (ret=%d) "
1394 "%s\n", ret, strerror(errno));
1398 if (!WIFEXITED(stat) || WEXITSTATUS(stat)) {
1399 ERR(!do_quiet, "ERROR: scrub process failed\n");
1400 err = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
1408 scrub_handle_sigint_child(fdmnt);
1410 for (i = 0; i < fi_args.num_devices; ++i) {
1412 sp[i].scrub_args.progress = sp[i].resumed->p;
1413 sp[i].stats = sp[i].resumed->stats;
1415 sp[i].stats.finished = 1;
1418 devid = di_args[i].devid;
1419 gettimeofday(&tv, NULL);
1420 sp[i].stats.t_start = tv.tv_sec;
1421 ret = pthread_create(&t_devs[i], NULL,
1422 scrub_one_dev, &sp[i]);
1425 fprintf(stderr, "ERROR: creating "
1426 "scrub_one_dev[%llu] thread failed: "
1427 "%s\n", devid, strerror(ret));
1434 spc.prg_fd = prg_fd;
1435 spc.do_record = do_record;
1436 spc.write_mutex = &spc_write_mutex;
1437 spc.shared_progress = sp;
1439 ret = pthread_create(&t_prog, NULL, scrub_progress_cycle, &spc);
1442 fprintf(stderr, "ERROR: creating progress thread "
1443 "failed: %s\n", strerror(ret));
1449 for (i = 0; i < fi_args.num_devices; ++i) {
1452 devid = di_args[i].devid;
1453 ret = pthread_join(t_devs[i], NULL);
1456 fprintf(stderr, "ERROR: pthread_join failed "
1457 "for scrub_one_dev[%llu]: %s\n", devid,
1462 if (sp[i].ret && sp[i].ioctl_errno == ENODEV) {
1464 fprintf(stderr, "WARNING: device %lld not "
1465 "present\n", devid);
1468 if (sp[i].ret && sp[i].ioctl_errno == ECANCELED) {
1470 } else if (sp[i].ret) {
1472 fprintf(stderr, "ERROR: scrubbing %s failed "
1473 "for device id %lld (%s)\n", path,
1474 devid, strerror(sp[i].ioctl_errno));
1478 if (sp[i].scrub_args.progress.uncorrectable_errors > 0)
1480 if (sp[i].scrub_args.progress.corrected_errors > 0
1481 || sp[i].scrub_args.progress.unverified_errors > 0)
1486 const char *append = "done";
1487 if (!do_stats_per_dev)
1488 init_fs_stat(&fs_stat);
1489 for (i = 0; i < fi_args.num_devices; ++i) {
1490 if (do_stats_per_dev) {
1491 print_scrub_dev(&di_args[i],
1492 &sp[i].scrub_args.progress,
1494 sp[i].ret ? "canceled" : "done",
1498 append = "canceled";
1499 add_to_fs_stat(&sp[i].scrub_args.progress,
1500 &sp[i].stats, &fs_stat);
1503 if (!do_stats_per_dev) {
1504 printf("scrub %s for %s\n", append, fsid);
1505 print_fs_stat(&fs_stat, print_raw);
1509 ret = pthread_cancel(t_prog);
1511 ret = pthread_join(t_prog, &terr);
1513 /* check for errors from the handling of the progress thread */
1514 if (do_print && ret) {
1515 fprintf(stderr, "ERROR: progress thread handling failed: %s\n",
1519 /* check for errors returned from the progress thread itself */
1520 if (do_print && terr && terr != PTHREAD_CANCELED) {
1521 fprintf(stderr, "ERROR: recording progress "
1522 "failed: %s\n", strerror(-PTR_ERR(terr)));
1526 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1527 fi_args.num_devices);
1528 if (ret && do_print) {
1529 fprintf(stderr, "ERROR: failed to record the result: "
1530 "%s\n", strerror(-ret));
1534 scrub_handle_sigint_child(-1);
1537 free_history(past_scrubs);
1547 close_file_or_dir(fdmnt, dirstream);
1551 if (nothing_to_resume)
1553 if (e_uncorrectable) {
1554 ERR(!do_quiet, "ERROR: There are uncorrectable errors.\n");
1558 ERR(!do_quiet, "WARNING: errors detected during scrubbing, corrected.\n");
1563 static const char * const cmd_scrub_start_usage[] = {
1564 "btrfs scrub start [-BdqrRf] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1565 "Start a new scrub. If a scrub is already running, the new one fails.",
1567 "-B do not background",
1568 "-d stats per device (-B only)",
1570 "-r read only mode",
1571 "-R raw print mode, print full data instead of summary",
1572 "-c set ioprio class (see ionice(1) manpage)",
1573 "-n set ioprio classdata (see ionice(1) manpage)",
1574 "-f force starting new scrub even if a scrub is already running",
1575 " this is useful when scrub stats record file is damaged",
1579 static int cmd_scrub_start(int argc, char **argv)
1581 return scrub_start(argc, argv, 0);
1584 static const char * const cmd_scrub_cancel_usage[] = {
1585 "btrfs scrub cancel <path>|<device>",
1586 "Cancel a running scrub",
1590 static int cmd_scrub_cancel(int argc, char **argv)
1595 DIR *dirstream = NULL;
1597 if (check_argc_exact(argc, 2))
1598 usage(cmd_scrub_cancel_usage);
1602 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1604 if (errno == EINVAL)
1606 "ERROR: '%s' is not a mounted btrfs device\n",
1609 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1610 path, strerror(errno));
1615 ret = ioctl(fdmnt, BTRFS_IOC_SCRUB_CANCEL, NULL);
1618 fprintf(stderr, "ERROR: scrub cancel failed on %s: %s\n", path,
1619 errno == ENOTCONN ? "not running" : strerror(errno));
1620 if (errno == ENOTCONN)
1628 printf("scrub cancelled\n");
1631 close_file_or_dir(fdmnt, dirstream);
1635 static const char * const cmd_scrub_resume_usage[] = {
1636 "btrfs scrub resume [-BdqrR] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1637 "Resume previously canceled or interrupted scrub",
1639 "-B do not background",
1640 "-d stats per device (-B only)",
1642 "-r read only mode",
1643 "-R raw print mode, print full data instead of summary",
1644 "-c set ioprio class (see ionice(1) manpage)",
1645 "-n set ioprio classdata (see ionice(1) manpage)",
1649 static int cmd_scrub_resume(int argc, char **argv)
1651 return scrub_start(argc, argv, 1);
1654 static const char * const cmd_scrub_status_usage[] = {
1655 "btrfs scrub status [-dR] <path>|<device>",
1656 "Show status of running or finished scrub",
1658 "-d stats per device",
1659 "-R print raw stats",
1663 static int cmd_scrub_status(int argc, char **argv)
1666 struct btrfs_ioctl_fs_info_args fi_args;
1667 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1668 struct scrub_file_record **past_scrubs = NULL;
1669 struct scrub_file_record *last_scrub;
1670 struct scrub_fs_stat fs_stat;
1671 struct sockaddr_un addr = {
1672 .sun_family = AF_UNIX,
1679 int do_stats_per_dev = 0;
1681 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1684 DIR *dirstream = NULL;
1687 while ((c = getopt(argc, argv, "dR")) != -1) {
1690 do_stats_per_dev = 1;
1697 usage(cmd_scrub_status_usage);
1701 if (check_argc_exact(argc - optind, 1))
1702 usage(cmd_scrub_status_usage);
1704 path = argv[optind];
1706 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1709 if (errno == EINVAL)
1711 "ERROR: '%s' is not a mounted btrfs device\n",
1714 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1715 path, strerror(errno));
1719 ret = get_fs_info(path, &fi_args, &di_args);
1721 fprintf(stderr, "ERROR: getting dev info for scrub failed: "
1722 "%s\n", strerror(-ret));
1726 if (!fi_args.num_devices) {
1727 fprintf(stderr, "ERROR: no devices found\n");
1732 uuid_unparse(fi_args.fsid, fsid);
1734 fdres = socket(AF_UNIX, SOCK_STREAM, 0);
1736 fprintf(stderr, "ERROR: failed to create socket to "
1737 "receive progress information: %s\n",
1742 scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid,
1743 NULL, addr.sun_path, sizeof(addr.sun_path));
1744 /* ignore EOVERFLOW, just use shorter name and hope for the best */
1745 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1746 ret = connect(fdres, (struct sockaddr *)&addr, sizeof(addr));
1749 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1750 if (fdres < 0 && fdres != -ENOENT) {
1751 fprintf(stderr, "WARNING: failed to open status file: "
1752 "%s\n", strerror(-fdres));
1759 past_scrubs = scrub_read_file(fdres, 1);
1760 if (IS_ERR(past_scrubs))
1761 fprintf(stderr, "WARNING: failed to read status: %s\n",
1762 strerror(-PTR_ERR(past_scrubs)));
1764 in_progress = is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices);
1766 printf("scrub status for %s\n", fsid);
1768 if (do_stats_per_dev) {
1769 for (i = 0; i < fi_args.num_devices; ++i) {
1770 last_scrub = last_dev_scrub(past_scrubs,
1773 print_scrub_dev(&di_args[i], NULL, print_raw,
1777 last_scrub->stats.in_progress = in_progress;
1778 print_scrub_dev(&di_args[i], &last_scrub->p, print_raw,
1779 last_scrub->stats.finished ?
1780 "history" : "status",
1781 &last_scrub->stats);
1784 init_fs_stat(&fs_stat);
1785 fs_stat.s.in_progress = in_progress;
1786 for (i = 0; i < fi_args.num_devices; ++i) {
1787 last_scrub = last_dev_scrub(past_scrubs,
1791 add_to_fs_stat(&last_scrub->p, &last_scrub->stats,
1794 print_fs_stat(&fs_stat, print_raw);
1798 free_history(past_scrubs);
1802 close_file_or_dir(fdmnt, dirstream);
1807 static const char scrub_cmd_group_info[] =
1808 "verify checksums of data and metadata";
1810 const struct cmd_group scrub_cmd_group = {
1811 scrub_cmd_group_usage, scrub_cmd_group_info, {
1812 { "start", cmd_scrub_start, cmd_scrub_start_usage, NULL, 0 },
1813 { "cancel", cmd_scrub_cancel, cmd_scrub_cancel_usage, NULL, 0 },
1814 { "resume", cmd_scrub_resume, cmd_scrub_resume_usage, NULL, 0 },
1815 { "status", cmd_scrub_status, cmd_scrub_status_usage, NULL, 0 },
1820 int cmd_scrub(int argc, char **argv)
1822 return handle_command_group(&scrub_cmd_group, argc, argv);