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>
47 static const char * const scrub_cmd_group_usage[] = {
48 "btrfs scrub <command> [options] <path>|<device>",
52 #define SCRUB_DATA_FILE "/var/lib/btrfs/scrub.status"
53 #define SCRUB_PROGRESS_SOCKET_PATH "/var/lib/btrfs/scrub.progress"
54 #define SCRUB_FILE_VERSION_PREFIX "scrub status"
55 #define SCRUB_FILE_VERSION "1"
66 /* TBD: replace with #include "linux/ioprio.h" in some years */
67 #if !defined (IOPRIO_H)
68 #define IOPRIO_WHO_PROCESS 1
69 #define IOPRIO_CLASS_SHIFT 13
70 #define IOPRIO_PRIO_VALUE(class, data) \
71 (((class) << IOPRIO_CLASS_SHIFT) | (data))
72 #define IOPRIO_CLASS_IDLE 3
75 struct scrub_progress {
76 struct btrfs_ioctl_scrub_args scrub_args;
80 struct scrub_stats stats;
81 struct scrub_file_record *resumed;
83 pthread_mutex_t progress_mutex;
88 struct scrub_file_record {
89 u8 fsid[BTRFS_FSID_SIZE];
91 struct scrub_stats stats;
92 struct btrfs_scrub_progress p;
95 struct scrub_progress_cycle {
99 struct btrfs_ioctl_fs_info_args *fi;
100 struct scrub_progress *progress;
101 struct scrub_progress *shared_progress;
102 pthread_mutex_t *write_mutex;
105 struct scrub_fs_stat {
106 struct btrfs_scrub_progress p;
107 struct scrub_stats s;
111 static void print_scrub_full(struct btrfs_scrub_progress *sp)
113 printf("\tdata_extents_scrubbed: %lld\n", sp->data_extents_scrubbed);
114 printf("\ttree_extents_scrubbed: %lld\n", sp->tree_extents_scrubbed);
115 printf("\tdata_bytes_scrubbed: %lld\n", sp->data_bytes_scrubbed);
116 printf("\ttree_bytes_scrubbed: %lld\n", sp->tree_bytes_scrubbed);
117 printf("\tread_errors: %lld\n", sp->read_errors);
118 printf("\tcsum_errors: %lld\n", sp->csum_errors);
119 printf("\tverify_errors: %lld\n", sp->verify_errors);
120 printf("\tno_csum: %lld\n", sp->no_csum);
121 printf("\tcsum_discards: %lld\n", sp->csum_discards);
122 printf("\tsuper_errors: %lld\n", sp->super_errors);
123 printf("\tmalloc_errors: %lld\n", sp->malloc_errors);
124 printf("\tuncorrectable_errors: %lld\n", sp->uncorrectable_errors);
125 printf("\tunverified_errors: %lld\n", sp->unverified_errors);
126 printf("\tcorrected_errors: %lld\n", sp->corrected_errors);
127 printf("\tlast_physical: %lld\n", sp->last_physical);
130 #define ERR(test, ...) do { \
132 fprintf(stderr, __VA_ARGS__); \
135 #define PRINT_SCRUB_ERROR(test, desc) do { \
137 printf(" %s=%llu", desc, test); \
140 static void print_scrub_summary(struct btrfs_scrub_progress *p)
145 err_cnt = p->read_errors +
150 err_cnt2 = p->corrected_errors + p->uncorrectable_errors;
152 if (p->malloc_errors)
153 printf("*** WARNING: memory allocation failed while scrubbing. "
154 "results may be inaccurate\n");
156 printf("\ttotal bytes scrubbed: %s with %llu errors\n",
157 pretty_size(p->data_bytes_scrubbed + p->tree_bytes_scrubbed),
158 max(err_cnt, err_cnt2));
160 if (err_cnt || err_cnt2) {
161 printf("\terror details:");
162 PRINT_SCRUB_ERROR(p->read_errors, "read");
163 PRINT_SCRUB_ERROR(p->super_errors, "super");
164 PRINT_SCRUB_ERROR(p->verify_errors, "verify");
165 PRINT_SCRUB_ERROR(p->csum_errors, "csum");
167 printf("\tcorrected errors: %llu, uncorrectable errors: %llu, "
168 "unverified errors: %llu\n", p->corrected_errors,
169 p->uncorrectable_errors, p->unverified_errors);
173 #define _SCRUB_FS_STAT(p, name, fs_stat) do { \
174 fs_stat->p.name += p->name; \
177 #define _SCRUB_FS_STAT_MIN(ss, name, fs_stat) \
179 if (fs_stat->s.name > ss->name) { \
180 fs_stat->s.name = ss->name; \
184 #define _SCRUB_FS_STAT_ZMIN(ss, name, fs_stat) \
186 if (!fs_stat->s.name || fs_stat->s.name > ss->name) { \
187 fs_stat->s.name = ss->name; \
191 #define _SCRUB_FS_STAT_ZMAX(ss, name, fs_stat) \
193 if (!(fs_stat)->s.name || (fs_stat)->s.name < (ss)->name) { \
194 (fs_stat)->s.name = (ss)->name; \
198 static void add_to_fs_stat(struct btrfs_scrub_progress *p,
199 struct scrub_stats *ss,
200 struct scrub_fs_stat *fs_stat)
202 _SCRUB_FS_STAT(p, data_extents_scrubbed, fs_stat);
203 _SCRUB_FS_STAT(p, tree_extents_scrubbed, fs_stat);
204 _SCRUB_FS_STAT(p, data_bytes_scrubbed, fs_stat);
205 _SCRUB_FS_STAT(p, tree_bytes_scrubbed, fs_stat);
206 _SCRUB_FS_STAT(p, read_errors, fs_stat);
207 _SCRUB_FS_STAT(p, csum_errors, fs_stat);
208 _SCRUB_FS_STAT(p, verify_errors, fs_stat);
209 _SCRUB_FS_STAT(p, no_csum, fs_stat);
210 _SCRUB_FS_STAT(p, csum_discards, fs_stat);
211 _SCRUB_FS_STAT(p, super_errors, fs_stat);
212 _SCRUB_FS_STAT(p, malloc_errors, fs_stat);
213 _SCRUB_FS_STAT(p, uncorrectable_errors, fs_stat);
214 _SCRUB_FS_STAT(p, corrected_errors, fs_stat);
215 _SCRUB_FS_STAT(p, last_physical, fs_stat);
216 _SCRUB_FS_STAT_ZMIN(ss, t_start, fs_stat);
217 _SCRUB_FS_STAT_ZMIN(ss, t_resumed, fs_stat);
218 _SCRUB_FS_STAT_ZMAX(ss, duration, fs_stat);
219 _SCRUB_FS_STAT_ZMAX(ss, canceled, fs_stat);
220 _SCRUB_FS_STAT_MIN(ss, finished, fs_stat);
223 static void init_fs_stat(struct scrub_fs_stat *fs_stat)
225 memset(fs_stat, 0, sizeof(*fs_stat));
226 fs_stat->s.finished = 1;
229 static void _print_scrub_ss(struct scrub_stats *ss)
236 if (!ss || !ss->t_start) {
237 printf("\tno stats available\n");
241 localtime_r(&ss->t_resumed, &tm);
242 strftime(t, sizeof(t), "%c", &tm);
243 t[sizeof(t) - 1] = '\0';
244 printf("\tscrub resumed at %s", t);
246 localtime_r(&ss->t_start, &tm);
247 strftime(t, sizeof(t), "%c", &tm);
248 t[sizeof(t) - 1] = '\0';
249 printf("\tscrub started at %s", t);
252 seconds = ss->duration;
253 hours = ss->duration / (60 * 60);
254 gmtime_r(&seconds, &tm);
255 strftime(t, sizeof(t), "%M:%S", &tm);
256 if (ss->finished && !ss->canceled) {
257 printf(" and finished after %02u:%s\n", hours, t);
258 } else if (ss->canceled) {
259 printf(" and was aborted after %02u:%s\n", hours, t);
262 printf(", running for %02u:%s\n", hours, t);
264 printf(", interrupted after %02u:%s, not running\n",
269 static void print_scrub_dev(struct btrfs_ioctl_dev_info_args *di,
270 struct btrfs_scrub_progress *p, int raw,
271 const char *append, struct scrub_stats *ss)
273 printf("scrub device %s (id %llu) %s\n", di->path, di->devid,
274 append ? append : "");
282 print_scrub_summary(p);
286 static void print_fs_stat(struct scrub_fs_stat *fs_stat, int raw)
288 _print_scrub_ss(&fs_stat->s);
291 print_scrub_full(&fs_stat->p);
293 print_scrub_summary(&fs_stat->p);
296 static void free_history(struct scrub_file_record **last_scrubs)
298 struct scrub_file_record **l = last_scrubs;
307 * cancels a running scrub and makes the master process record the current
308 * progress status before exiting.
310 static int cancel_fd = -1;
311 static void scrub_sigint_record_progress(int signal)
315 ret = ioctl(cancel_fd, BTRFS_IOC_SCRUB_CANCEL, NULL);
317 perror("Scrub cancel failed");
320 static int scrub_handle_sigint_parent(void)
322 struct sigaction sa = {
323 .sa_handler = SIG_IGN,
324 .sa_flags = SA_RESTART,
327 return sigaction(SIGINT, &sa, NULL);
330 static int scrub_handle_sigint_child(int fd)
332 struct sigaction sa = {
333 .sa_handler = fd == -1 ? SIG_DFL : scrub_sigint_record_progress,
337 return sigaction(SIGINT, &sa, NULL);
340 static int scrub_datafile(const char *fn_base, const char *fn_local,
341 const char *fn_tmp, char *datafile, int size)
346 datafile[end + 1] = '\0';
347 strncpy(datafile, fn_base, end);
348 ret = strlen(datafile);
354 strncpy(datafile + ret + 1, fn_local, end - ret - 1);
355 ret = strlen(datafile);
362 strncpy(datafile + ret + 1, fn_tmp, end - ret - 1);
363 ret = strlen(datafile);
372 static int scrub_open_file(const char *datafile, int m)
377 fd = open(datafile, m, 0600);
381 ret = flock(fd, LOCK_EX|LOCK_NB);
391 static int scrub_open_file_r(const char *fn_base, const char *fn_local)
394 char datafile[PATH_MAX];
395 ret = scrub_datafile(fn_base, fn_local, NULL,
396 datafile, sizeof(datafile));
399 return scrub_open_file(datafile, O_RDONLY);
402 static int scrub_open_file_w(const char *fn_base, const char *fn_local,
406 char datafile[PATH_MAX];
407 ret = scrub_datafile(fn_base, fn_local, tmp,
408 datafile, sizeof(datafile));
411 return scrub_open_file(datafile, O_WRONLY|O_CREAT);
414 static int scrub_rename_file(const char *fn_base, const char *fn_local,
418 char datafile_old[PATH_MAX];
419 char datafile_new[PATH_MAX];
420 ret = scrub_datafile(fn_base, fn_local, tmp,
421 datafile_old, sizeof(datafile_old));
424 ret = scrub_datafile(fn_base, fn_local, NULL,
425 datafile_new, sizeof(datafile_new));
428 ret = rename(datafile_old, datafile_new);
429 return ret ? -errno : 0;
432 #define _SCRUB_KVREAD(ret, i, name, avail, l, dest) if (ret == 0) { \
433 ret = scrub_kvread(i, sizeof(#name), avail, l, #name, dest.name); \
437 * returns 0 if the key did not match (nothing was read)
438 * 1 if the key did match (success)
439 * -1 if the key did match and an error occured
441 static int scrub_kvread(int *i, int len, int avail, const char *buf,
442 const char *key, u64 *dest)
446 if (*i + len + 1 < avail && strncmp(&buf[*i], key, len - 1) == 0) {
451 for (j = 0; isdigit(buf[*i + j]) && *i + j < avail; ++j)
455 *dest = atoll(&buf[*i]);
463 #define _SCRUB_INVALID do { \
465 fprintf(stderr, "WARNING: invalid data in line %d pos " \
466 "%d state %d (near \"%.*s\") at %s:%d\n", \
467 lineno, i, state, 20 > avail ? avail : 20, \
468 l + i, __FILE__, __LINE__); \
472 static struct scrub_file_record **scrub_read_file(int fd, int report_errors)
485 char empty_uuid[BTRFS_FSID_SIZE] = {0};
486 struct scrub_file_record **p = NULL;
489 old_avail = avail - i;
490 BUG_ON(old_avail < 0);
492 memmove(l, l + i, old_avail);
493 avail = read(fd, l + old_avail, sizeof(l) - old_avail);
496 if (avail == 0 && old_avail == 0) {
498 memcmp(p[curr]->fsid, empty_uuid, BTRFS_FSID_SIZE) == 0) {
500 } else if (curr == -1) {
501 p = ERR_PTR(-ENODATA);
507 return ERR_PTR(-errno);
516 case 0: /* start of file */
517 ret = scrub_kvread(&i,
518 sizeof(SCRUB_FILE_VERSION_PREFIX), avail, l,
519 SCRUB_FILE_VERSION_PREFIX, &version);
522 if (version != atoll(SCRUB_FILE_VERSION))
523 return ERR_PTR(-ENOTSUP);
526 case 1: /* start of line, alloc */
528 * this state makes sure we have a complete line in
529 * further processing, so we don't need wrap-tracking
532 if (!eof && !memchr(l + i, '\n', avail - i))
535 if (curr > -1 && memcmp(p[curr]->fsid, empty_uuid,
536 BTRFS_FSID_SIZE) == 0) {
542 p = realloc(p, (curr + 2) * sizeof(*p));
545 return ERR_PTR(-errno);
547 p[curr] = malloc(sizeof(**p));
550 return ERR_PTR(-errno);
552 memset(p[curr], 0, sizeof(**p));
556 case 2: /* start of line, skip space */
557 while (isspace(l[i]) && i < avail) {
563 (!eof && !memchr(l + i, '\n', avail - i)))
567 case 3: /* read fsid */
570 for (j = 0; l[i + j] != ':' && i + j < avail; ++j)
572 if (i + j + 1 >= avail)
574 if (j != BTRFS_UUID_UNPARSED_SIZE - 1)
577 ret = uuid_parse(l + i, p[curr]->fsid);
583 case 4: /* read dev id */
584 for (j = 0; isdigit(l[i + j]) && i+j < avail; ++j)
586 if (j == 0 || i + j + 1 >= avail)
588 p[curr]->devid = atoll(&l[i]);
592 case 5: /* read key/value pair */
594 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
596 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
598 _SCRUB_KVREAD(ret, &i, tree_extents_scrubbed, avail, l,
600 _SCRUB_KVREAD(ret, &i, data_bytes_scrubbed, avail, l,
602 _SCRUB_KVREAD(ret, &i, tree_bytes_scrubbed, avail, l,
604 _SCRUB_KVREAD(ret, &i, read_errors, avail, l,
606 _SCRUB_KVREAD(ret, &i, csum_errors, avail, l,
608 _SCRUB_KVREAD(ret, &i, verify_errors, avail, l,
610 _SCRUB_KVREAD(ret, &i, no_csum, avail, l,
612 _SCRUB_KVREAD(ret, &i, csum_discards, avail, l,
614 _SCRUB_KVREAD(ret, &i, super_errors, avail, l,
616 _SCRUB_KVREAD(ret, &i, malloc_errors, avail, l,
618 _SCRUB_KVREAD(ret, &i, uncorrectable_errors, avail, l,
620 _SCRUB_KVREAD(ret, &i, corrected_errors, avail, l,
622 _SCRUB_KVREAD(ret, &i, last_physical, avail, l,
624 _SCRUB_KVREAD(ret, &i, finished, avail, l,
626 _SCRUB_KVREAD(ret, &i, t_start, avail, l,
627 (u64 *)&p[curr]->stats);
628 _SCRUB_KVREAD(ret, &i, t_resumed, avail, l,
629 (u64 *)&p[curr]->stats);
630 _SCRUB_KVREAD(ret, &i, duration, avail, l,
631 (u64 *)&p[curr]->stats);
632 _SCRUB_KVREAD(ret, &i, canceled, avail, l,
638 case 6: /* after number */
641 else if (l[i] == '\n')
647 case 99: /* skip rest of line */
652 if (l[i - 1] == '\n') {
664 static int scrub_write_buf(int fd, const void *data, int len)
667 ret = write(fd, data, len);
671 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
672 __attribute__ ((format (printf, 4, 5)));
673 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
679 ret = vsnprintf(buf, max, fmt, args);
683 return scrub_write_buf(fd, buf, ret);
686 #define _SCRUB_SUM(dest, data, name) dest->scrub_args.progress.name = \
687 data->resumed->p.name + data->scrub_args.progress.name
689 static struct scrub_progress *scrub_resumed_stats(struct scrub_progress *data,
690 struct scrub_progress *dest)
692 if (!data->resumed || data->skip)
695 _SCRUB_SUM(dest, data, data_extents_scrubbed);
696 _SCRUB_SUM(dest, data, tree_extents_scrubbed);
697 _SCRUB_SUM(dest, data, data_bytes_scrubbed);
698 _SCRUB_SUM(dest, data, tree_bytes_scrubbed);
699 _SCRUB_SUM(dest, data, read_errors);
700 _SCRUB_SUM(dest, data, csum_errors);
701 _SCRUB_SUM(dest, data, verify_errors);
702 _SCRUB_SUM(dest, data, no_csum);
703 _SCRUB_SUM(dest, data, csum_discards);
704 _SCRUB_SUM(dest, data, super_errors);
705 _SCRUB_SUM(dest, data, malloc_errors);
706 _SCRUB_SUM(dest, data, uncorrectable_errors);
707 _SCRUB_SUM(dest, data, corrected_errors);
708 _SCRUB_SUM(dest, data, last_physical);
709 dest->stats.canceled = data->stats.canceled;
710 dest->stats.finished = data->stats.finished;
711 dest->stats.t_resumed = data->stats.t_start;
712 dest->stats.t_start = data->resumed->stats.t_start;
713 dest->stats.duration = data->resumed->stats.duration +
714 data->stats.duration;
715 dest->scrub_args.devid = data->scrub_args.devid;
719 #define _SCRUB_KVWRITE(fd, buf, name, use) \
720 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
721 use->scrub_args.progress.name)
723 #define _SCRUB_KVWRITE_STATS(fd, buf, name, use) \
724 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
727 static int scrub_kvwrite(int fd, char *buf, int max, const char *key, u64 val)
729 return scrub_writev(fd, buf, max, "|%s:%lld", key, val);
732 static int scrub_write_file(int fd, const char *fsid,
733 struct scrub_progress *data, int n)
738 struct scrub_progress local;
739 struct scrub_progress *use;
744 /* each -1 is to subtract one \0 byte, the + 2 is for ':' and '\n' */
745 ret = scrub_write_buf(fd, SCRUB_FILE_VERSION_PREFIX ":"
746 SCRUB_FILE_VERSION "\n",
747 (sizeof(SCRUB_FILE_VERSION_PREFIX) - 1) +
748 (sizeof(SCRUB_FILE_VERSION) - 1) + 2);
752 for (i = 0; i < n; ++i) {
753 use = scrub_resumed_stats(&data[i], &local);
754 if (scrub_write_buf(fd, fsid, strlen(fsid)) ||
755 scrub_write_buf(fd, ":", 1) ||
756 scrub_writev(fd, buf, sizeof(buf), "%lld",
757 use->scrub_args.devid) ||
758 scrub_write_buf(fd, buf, ret) ||
759 _SCRUB_KVWRITE(fd, buf, data_extents_scrubbed, use) ||
760 _SCRUB_KVWRITE(fd, buf, tree_extents_scrubbed, use) ||
761 _SCRUB_KVWRITE(fd, buf, data_bytes_scrubbed, use) ||
762 _SCRUB_KVWRITE(fd, buf, tree_bytes_scrubbed, use) ||
763 _SCRUB_KVWRITE(fd, buf, read_errors, use) ||
764 _SCRUB_KVWRITE(fd, buf, csum_errors, use) ||
765 _SCRUB_KVWRITE(fd, buf, verify_errors, use) ||
766 _SCRUB_KVWRITE(fd, buf, no_csum, use) ||
767 _SCRUB_KVWRITE(fd, buf, csum_discards, use) ||
768 _SCRUB_KVWRITE(fd, buf, super_errors, use) ||
769 _SCRUB_KVWRITE(fd, buf, malloc_errors, use) ||
770 _SCRUB_KVWRITE(fd, buf, uncorrectable_errors, use) ||
771 _SCRUB_KVWRITE(fd, buf, corrected_errors, use) ||
772 _SCRUB_KVWRITE(fd, buf, last_physical, use) ||
773 _SCRUB_KVWRITE_STATS(fd, buf, t_start, use) ||
774 _SCRUB_KVWRITE_STATS(fd, buf, t_resumed, use) ||
775 _SCRUB_KVWRITE_STATS(fd, buf, duration, use) ||
776 _SCRUB_KVWRITE_STATS(fd, buf, canceled, use) ||
777 _SCRUB_KVWRITE_STATS(fd, buf, finished, use) ||
778 scrub_write_buf(fd, "\n", 1)) {
786 static int scrub_write_progress(pthread_mutex_t *m, const char *fsid,
787 struct scrub_progress *data, int n)
794 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old);
800 ret = pthread_mutex_lock(m);
806 fd = scrub_open_file_w(SCRUB_DATA_FILE, fsid, "tmp");
811 err = scrub_write_file(fd, fsid, data, n);
814 err = scrub_rename_file(SCRUB_DATA_FILE, fsid, "tmp");
825 ret = pthread_mutex_unlock(m);
830 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old);
838 static void *scrub_one_dev(void *ctx)
840 struct scrub_progress *sp = ctx;
844 sp->stats.canceled = 0;
845 sp->stats.duration = 0;
846 sp->stats.finished = 0;
848 ret = syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0,
849 IOPRIO_PRIO_VALUE(sp->ioprio_class,
850 sp->ioprio_classdata));
853 "WARNING: setting ioprio failed: %s (ignored).\n",
856 ret = ioctl(sp->fd, BTRFS_IOC_SCRUB, &sp->scrub_args);
857 gettimeofday(&tv, NULL);
859 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
860 sp->stats.canceled = !!ret;
861 sp->ioctl_errno = errno;
862 ret = pthread_mutex_lock(&sp->progress_mutex);
864 return ERR_PTR(-ret);
865 sp->stats.finished = 1;
866 ret = pthread_mutex_unlock(&sp->progress_mutex);
868 return ERR_PTR(-ret);
873 static void *progress_one_dev(void *ctx)
875 struct scrub_progress *sp = ctx;
877 sp->ret = ioctl(sp->fd, BTRFS_IOC_SCRUB_PROGRESS, &sp->scrub_args);
878 sp->ioctl_errno = errno;
883 /* nb: returns a negative errno via ERR_PTR */
884 static void *scrub_progress_cycle(void *ctx)
887 int perr = 0; /* positive / pthread error returns */
890 char fsid[BTRFS_UUID_UNPARSED_SIZE];
891 struct scrub_progress *sp;
892 struct scrub_progress *sp_last;
893 struct scrub_progress *sp_shared;
895 struct scrub_progress_cycle *spc = ctx;
896 int ndev = spc->fi->num_devices;
900 struct pollfd accept_poll_fd = {
905 struct pollfd write_poll_fd = {
909 struct sockaddr_un peer;
910 socklen_t peer_size = sizeof(peer);
912 perr = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old);
916 uuid_unparse(spc->fi->fsid, fsid);
918 for (i = 0; i < ndev; ++i) {
919 sp = &spc->progress[i];
920 sp_last = &spc->progress[i + ndev];
921 sp_shared = &spc->shared_progress[i];
922 sp->scrub_args.devid = sp_last->scrub_args.devid =
923 sp_shared->scrub_args.devid;
924 sp->fd = sp_last->fd = spc->fdmnt;
925 sp->stats.t_start = sp_last->stats.t_start =
926 sp_shared->stats.t_start;
927 sp->resumed = sp_last->resumed = sp_shared->resumed;
928 sp->skip = sp_last->skip = sp_shared->skip;
929 sp->stats.finished = sp_last->stats.finished =
930 sp_shared->stats.finished;
934 ret = poll(&accept_poll_fd, 1, 5 * 1000);
940 peer_fd = accept(spc->prg_fd, (struct sockaddr *)&peer,
942 gettimeofday(&tv, NULL);
945 for (i = 0; i < ndev; ++i) {
946 sp = &spc->progress[this * ndev + i];
947 sp_last = &spc->progress[last * ndev + i];
948 sp_shared = &spc->shared_progress[i];
949 if (sp->stats.finished)
951 progress_one_dev(sp);
952 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
955 if (sp->ioctl_errno != ENOTCONN &&
956 sp->ioctl_errno != ENODEV) {
957 ret = -sp->ioctl_errno;
961 * scrub finished or device removed, check the
962 * finished flag. if unset, just use the last
963 * result we got for the current write and go
964 * on. flag should be set on next cycle, then.
966 perr = pthread_setcancelstate(
967 PTHREAD_CANCEL_DISABLE, &old);
970 perr = pthread_mutex_lock(&sp_shared->progress_mutex);
973 if (!sp_shared->stats.finished) {
974 perr = pthread_mutex_unlock(
975 &sp_shared->progress_mutex);
978 perr = pthread_setcancelstate(
979 PTHREAD_CANCEL_ENABLE, &old);
982 memcpy(sp, sp_last, sizeof(*sp));
985 perr = pthread_mutex_unlock(&sp_shared->progress_mutex);
988 perr = pthread_setcancelstate(
989 PTHREAD_CANCEL_ENABLE, &old);
992 memcpy(sp, sp_shared, sizeof(*sp));
993 memcpy(sp_last, sp_shared, sizeof(*sp));
996 write_poll_fd.fd = peer_fd;
997 ret = poll(&write_poll_fd, 1, 0);
1003 ret = scrub_write_file(
1005 &spc->progress[this * ndev], ndev);
1012 if (!spc->do_record)
1014 ret = scrub_write_progress(spc->write_mutex, fsid,
1015 &spc->progress[this * ndev], ndev);
1024 return ERR_PTR(ret);
1027 static struct scrub_file_record *last_dev_scrub(
1028 struct scrub_file_record *const *const past_scrubs, u64 devid)
1032 if (!past_scrubs || IS_ERR(past_scrubs))
1035 for (i = 0; past_scrubs[i]; ++i)
1036 if (past_scrubs[i]->devid == devid)
1037 return past_scrubs[i];
1042 static int mkdir_p(char *path)
1047 for (i = 1; i < strlen(path); ++i) {
1051 ret = mkdir(path, 0777);
1052 if (ret && errno != EEXIST)
1060 static int is_scrub_running_on_fs(struct btrfs_ioctl_fs_info_args *fi_args,
1061 struct btrfs_ioctl_dev_info_args *di_args,
1062 struct scrub_file_record **past_scrubs)
1066 if (!fi_args || !di_args || !past_scrubs)
1069 for (i = 0; i < fi_args->num_devices; i++) {
1070 struct scrub_file_record *sfr =
1071 last_dev_scrub(past_scrubs, di_args[i].devid);
1075 if (!(sfr->stats.finished || sfr->stats.canceled))
1081 static int is_scrub_running_in_kernel(int fd,
1082 struct btrfs_ioctl_dev_info_args *di_args, u64 max_devices)
1084 struct scrub_progress sp;
1088 for (i = 0; i < max_devices; i++) {
1089 memset(&sp, 0, sizeof(sp));
1090 sp.scrub_args.devid = di_args[i].devid;
1091 ret = ioctl(fd, BTRFS_IOC_SCRUB_PROGRESS, &sp.scrub_args);
1099 static const char * const cmd_scrub_start_usage[];
1100 static const char * const cmd_scrub_resume_usage[];
1102 static int scrub_start(int argc, char **argv, int resume)
1112 int e_uncorrectable = 0;
1113 int e_correctable = 0;
1116 int do_background = 1;
1122 int do_stats_per_dev = 0;
1123 int ioprio_class = IOPRIO_CLASS_IDLE;
1124 int ioprio_classdata = 0;
1128 struct btrfs_ioctl_fs_info_args fi_args;
1129 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1130 struct scrub_progress *sp = NULL;
1131 struct scrub_fs_stat fs_stat;
1133 struct sockaddr_un addr = {
1134 .sun_family = AF_UNIX,
1136 pthread_t *t_devs = NULL;
1138 struct scrub_file_record **past_scrubs = NULL;
1139 struct scrub_file_record *last_scrub = NULL;
1140 char *datafile = strdup(SCRUB_DATA_FILE);
1141 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1142 char sock_path[PATH_MAX] = "";
1143 struct scrub_progress_cycle spc;
1144 pthread_mutex_t spc_write_mutex = PTHREAD_MUTEX_INITIALIZER;
1147 DIR *dirstream = NULL;
1149 int nothing_to_resume = 0;
1152 while ((c = getopt(argc, argv, "BdqrRc:n:f")) != -1) {
1160 do_stats_per_dev = 1;
1172 ioprio_class = (int)strtol(optarg, NULL, 10);
1175 ioprio_classdata = (int)strtol(optarg, NULL, 10);
1182 usage(resume ? cmd_scrub_resume_usage :
1183 cmd_scrub_start_usage);
1187 /* try to catch most error cases before forking */
1189 if (check_argc_exact(argc - optind, 1)) {
1190 usage(resume ? cmd_scrub_resume_usage :
1191 cmd_scrub_start_usage);
1194 spc.progress = NULL;
1195 if (do_quiet && do_print)
1198 if (mkdir_p(datafile)) {
1199 ERR(!do_quiet, "WARNING: cannot create scrub data "
1200 "file, mkdir %s failed: %s. Status recording "
1201 "disabled\n", datafile, strerror(errno));
1206 path = argv[optind];
1208 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1211 if (errno == EINVAL)
1213 "ERROR: '%s' is not a mounted btrfs device\n",
1216 ERR(!do_quiet, "ERROR: can't access '%s': %s\n",
1217 path, strerror(errno));
1221 ret = get_fs_info(path, &fi_args, &di_args);
1223 ERR(!do_quiet, "ERROR: getting dev info for scrub failed: "
1224 "%s\n", strerror(-ret));
1228 if (!fi_args.num_devices) {
1229 ERR(!do_quiet, "ERROR: no devices found\n");
1234 uuid_unparse(fi_args.fsid, fsid);
1235 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1236 if (fdres < 0 && fdres != -ENOENT) {
1237 ERR(!do_quiet, "WARNING: failed to open status file: "
1238 "%s\n", strerror(-fdres));
1239 } else if (fdres >= 0) {
1240 past_scrubs = scrub_read_file(fdres, !do_quiet);
1241 if (IS_ERR(past_scrubs))
1242 ERR(!do_quiet, "WARNING: failed to read status file: "
1243 "%s\n", strerror(-PTR_ERR(past_scrubs)));
1248 * Check for stale information in the status file, ie. if it's
1249 * canceled=0, finished=0 but no scrub is running.
1251 if (!is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices))
1255 * check whether any involved device is already busy running a
1256 * scrub. This would cause damaged status messages and the state
1257 * "aborted" without the explanation that a scrub was already
1258 * running. Therefore check it first, prevent it and give some
1259 * feedback to the user if scrub is already running.
1260 * Note that if scrub is started with a block device as the
1261 * parameter, only that particular block device is checked. It
1262 * is a normal mode of operation to start scrub on multiple
1263 * single devices, there is no reason to prevent this.
1265 if (!force && is_scrub_running_on_fs(&fi_args, di_args, past_scrubs)) {
1267 "ERROR: scrub is already running.\n"
1268 "To cancel use 'btrfs scrub cancel %s'.\n"
1269 "To see the status use 'btrfs scrub status [-d] %s'.\n",
1275 t_devs = malloc(fi_args.num_devices * sizeof(*t_devs));
1276 sp = calloc(fi_args.num_devices, sizeof(*sp));
1277 spc.progress = calloc(fi_args.num_devices * 2, sizeof(*spc.progress));
1279 if (!t_devs || !sp || !spc.progress) {
1280 ERR(!do_quiet, "ERROR: scrub failed: %s", strerror(errno));
1285 for (i = 0; i < fi_args.num_devices; ++i) {
1286 devid = di_args[i].devid;
1287 ret = pthread_mutex_init(&sp[i].progress_mutex, NULL);
1289 ERR(!do_quiet, "ERROR: pthread_mutex_init failed: "
1290 "%s\n", strerror(ret));
1294 last_scrub = last_dev_scrub(past_scrubs, devid);
1295 sp[i].scrub_args.devid = devid;
1297 if (resume && last_scrub && (last_scrub->stats.canceled ||
1298 !last_scrub->stats.finished)) {
1300 sp[i].scrub_args.start = last_scrub->p.last_physical;
1301 sp[i].resumed = last_scrub;
1302 } else if (resume) {
1305 sp[i].resumed = last_scrub;
1309 sp[i].scrub_args.start = 0ll;
1310 sp[i].resumed = NULL;
1313 sp[i].scrub_args.end = (u64)-1ll;
1314 sp[i].scrub_args.flags = readonly ? BTRFS_SCRUB_READONLY : 0;
1315 sp[i].ioprio_class = ioprio_class;
1316 sp[i].ioprio_classdata = ioprio_classdata;
1319 if (!n_start && !n_resume) {
1321 printf("scrub: nothing to resume for %s, fsid %s\n",
1323 nothing_to_resume = 1;
1327 ret = prg_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1329 ret = scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid, NULL,
1330 sock_path, sizeof(sock_path));
1331 /* ignore EOVERFLOW, try using a shorter path for the socket */
1332 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1333 strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1);
1334 ret = bind(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1335 if (ret != -1 || errno != EADDRINUSE)
1338 * bind failed with EADDRINUSE. so let's see if anyone answers
1339 * when we make a call to the socket ...
1341 ret = connect(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1342 if (!ret || errno != ECONNREFUSED) {
1343 /* ... yes, so scrub must be running. error out */
1344 fprintf(stderr, "ERROR: scrub already running\n");
1350 * ... no, this means someone left us alone with an unused
1351 * socket in the file system. remove it and try again.
1353 ret = unlink(sock_path);
1356 ret = listen(prg_fd, 100);
1358 ERR(!do_quiet, "WARNING: failed to open the progress status "
1359 "socket at %s: %s. Progress cannot be queried\n",
1360 sock_path[0] ? sock_path : SCRUB_PROGRESS_SOCKET_PATH,
1371 /* write all-zero progress file for a start */
1372 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1373 fi_args.num_devices);
1375 ERR(!do_quiet, "WARNING: failed to write the progress "
1376 "status file: %s. Status recording disabled\n",
1382 if (do_background) {
1385 ERR(!do_quiet, "ERROR: cannot scrub, fork failed: "
1386 "%s\n", strerror(errno));
1393 scrub_handle_sigint_parent();
1395 printf("scrub %s on %s, fsid %s (pid=%d)\n",
1396 n_start ? "started" : "resumed",
1404 ERR(!do_quiet, "ERROR: wait failed: (ret=%d) "
1405 "%s\n", ret, strerror(errno));
1409 if (!WIFEXITED(stat) || WEXITSTATUS(stat)) {
1410 ERR(!do_quiet, "ERROR: scrub process failed\n");
1411 err = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
1419 scrub_handle_sigint_child(fdmnt);
1421 for (i = 0; i < fi_args.num_devices; ++i) {
1423 sp[i].scrub_args.progress = sp[i].resumed->p;
1424 sp[i].stats = sp[i].resumed->stats;
1426 sp[i].stats.finished = 1;
1429 devid = di_args[i].devid;
1430 gettimeofday(&tv, NULL);
1431 sp[i].stats.t_start = tv.tv_sec;
1432 ret = pthread_create(&t_devs[i], NULL,
1433 scrub_one_dev, &sp[i]);
1436 fprintf(stderr, "ERROR: creating "
1437 "scrub_one_dev[%llu] thread failed: "
1438 "%s\n", devid, strerror(ret));
1445 spc.prg_fd = prg_fd;
1446 spc.do_record = do_record;
1447 spc.write_mutex = &spc_write_mutex;
1448 spc.shared_progress = sp;
1450 ret = pthread_create(&t_prog, NULL, scrub_progress_cycle, &spc);
1453 fprintf(stderr, "ERROR: creating progress thread "
1454 "failed: %s\n", strerror(ret));
1460 for (i = 0; i < fi_args.num_devices; ++i) {
1463 devid = di_args[i].devid;
1464 ret = pthread_join(t_devs[i], NULL);
1467 fprintf(stderr, "ERROR: pthread_join failed "
1468 "for scrub_one_dev[%llu]: %s\n", devid,
1473 if (sp[i].ret && sp[i].ioctl_errno == ENODEV) {
1475 fprintf(stderr, "WARNING: device %lld not "
1476 "present\n", devid);
1479 if (sp[i].ret && sp[i].ioctl_errno == ECANCELED) {
1481 } else if (sp[i].ret) {
1483 fprintf(stderr, "ERROR: scrubbing %s failed "
1484 "for device id %lld (%s)\n", path,
1485 devid, strerror(sp[i].ioctl_errno));
1489 if (sp[i].scrub_args.progress.uncorrectable_errors > 0)
1491 if (sp[i].scrub_args.progress.corrected_errors > 0
1492 || sp[i].scrub_args.progress.unverified_errors > 0)
1497 const char *append = "done";
1498 if (!do_stats_per_dev)
1499 init_fs_stat(&fs_stat);
1500 for (i = 0; i < fi_args.num_devices; ++i) {
1501 if (do_stats_per_dev) {
1502 print_scrub_dev(&di_args[i],
1503 &sp[i].scrub_args.progress,
1505 sp[i].ret ? "canceled" : "done",
1509 append = "canceled";
1510 add_to_fs_stat(&sp[i].scrub_args.progress,
1511 &sp[i].stats, &fs_stat);
1514 if (!do_stats_per_dev) {
1515 printf("scrub %s for %s\n", append, fsid);
1516 print_fs_stat(&fs_stat, print_raw);
1520 ret = pthread_cancel(t_prog);
1522 ret = pthread_join(t_prog, &terr);
1524 /* check for errors from the handling of the progress thread */
1525 if (do_print && ret) {
1526 fprintf(stderr, "ERROR: progress thread handling failed: %s\n",
1530 /* check for errors returned from the progress thread itself */
1531 if (do_print && terr && terr != PTHREAD_CANCELED) {
1532 fprintf(stderr, "ERROR: recording progress "
1533 "failed: %s\n", strerror(-PTR_ERR(terr)));
1537 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1538 fi_args.num_devices);
1539 if (ret && do_print) {
1540 fprintf(stderr, "ERROR: failed to record the result: "
1541 "%s\n", strerror(-ret));
1545 scrub_handle_sigint_child(-1);
1548 free_history(past_scrubs);
1558 close_file_or_dir(fdmnt, dirstream);
1562 if (nothing_to_resume)
1564 if (e_uncorrectable) {
1565 ERR(!do_quiet, "ERROR: There are uncorrectable errors.\n");
1569 ERR(!do_quiet, "WARNING: errors detected during scrubbing, corrected.\n");
1574 static const char * const cmd_scrub_start_usage[] = {
1575 "btrfs scrub start [-BdqrRf] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1576 "Start a new scrub. If a scrub is already running, the new one fails.",
1578 "-B do not background",
1579 "-d stats per device (-B only)",
1581 "-r read only mode",
1582 "-R raw print mode, print full data instead of summary",
1583 "-c set ioprio class (see ionice(1) manpage)",
1584 "-n set ioprio classdata (see ionice(1) manpage)",
1585 "-f force starting new scrub even if a scrub is already running",
1586 " this is useful when scrub stats record file is damaged",
1590 static int cmd_scrub_start(int argc, char **argv)
1592 return scrub_start(argc, argv, 0);
1595 static const char * const cmd_scrub_cancel_usage[] = {
1596 "btrfs scrub cancel <path>|<device>",
1597 "Cancel a running scrub",
1601 static int cmd_scrub_cancel(int argc, char **argv)
1606 DIR *dirstream = NULL;
1608 if (check_argc_exact(argc, 2))
1609 usage(cmd_scrub_cancel_usage);
1613 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1615 if (errno == EINVAL)
1617 "ERROR: '%s' is not a mounted btrfs device\n",
1620 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1621 path, strerror(errno));
1626 ret = ioctl(fdmnt, BTRFS_IOC_SCRUB_CANCEL, NULL);
1629 fprintf(stderr, "ERROR: scrub cancel failed on %s: %s\n", path,
1630 errno == ENOTCONN ? "not running" : strerror(errno));
1631 if (errno == ENOTCONN)
1639 printf("scrub cancelled\n");
1642 close_file_or_dir(fdmnt, dirstream);
1646 static const char * const cmd_scrub_resume_usage[] = {
1647 "btrfs scrub resume [-BdqrR] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1648 "Resume previously canceled or interrupted scrub",
1650 "-B do not background",
1651 "-d stats per device (-B only)",
1653 "-r read only mode",
1654 "-R raw print mode, print full data instead of summary",
1655 "-c set ioprio class (see ionice(1) manpage)",
1656 "-n set ioprio classdata (see ionice(1) manpage)",
1660 static int cmd_scrub_resume(int argc, char **argv)
1662 return scrub_start(argc, argv, 1);
1665 static const char * const cmd_scrub_status_usage[] = {
1666 "btrfs scrub status [-dR] <path>|<device>",
1667 "Show status of running or finished scrub",
1669 "-d stats per device",
1670 "-R print raw stats",
1674 static int cmd_scrub_status(int argc, char **argv)
1677 struct btrfs_ioctl_fs_info_args fi_args;
1678 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1679 struct scrub_file_record **past_scrubs = NULL;
1680 struct scrub_file_record *last_scrub;
1681 struct scrub_fs_stat fs_stat;
1682 struct sockaddr_un addr = {
1683 .sun_family = AF_UNIX,
1690 int do_stats_per_dev = 0;
1692 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1695 DIR *dirstream = NULL;
1698 while ((c = getopt(argc, argv, "dR")) != -1) {
1701 do_stats_per_dev = 1;
1708 usage(cmd_scrub_status_usage);
1712 if (check_argc_exact(argc - optind, 1))
1713 usage(cmd_scrub_status_usage);
1715 path = argv[optind];
1717 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1720 if (errno == EINVAL)
1722 "ERROR: '%s' is not a mounted btrfs device\n",
1725 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1726 path, strerror(errno));
1730 ret = get_fs_info(path, &fi_args, &di_args);
1732 fprintf(stderr, "ERROR: getting dev info for scrub failed: "
1733 "%s\n", strerror(-ret));
1737 if (!fi_args.num_devices) {
1738 fprintf(stderr, "ERROR: no devices found\n");
1743 uuid_unparse(fi_args.fsid, fsid);
1745 fdres = socket(AF_UNIX, SOCK_STREAM, 0);
1747 fprintf(stderr, "ERROR: failed to create socket to "
1748 "receive progress information: %s\n",
1753 scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid,
1754 NULL, addr.sun_path, sizeof(addr.sun_path));
1755 /* ignore EOVERFLOW, just use shorter name and hope for the best */
1756 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1757 ret = connect(fdres, (struct sockaddr *)&addr, sizeof(addr));
1760 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1761 if (fdres < 0 && fdres != -ENOENT) {
1762 fprintf(stderr, "WARNING: failed to open status file: "
1763 "%s\n", strerror(-fdres));
1770 past_scrubs = scrub_read_file(fdres, 1);
1771 if (IS_ERR(past_scrubs))
1772 fprintf(stderr, "WARNING: failed to read status: %s\n",
1773 strerror(-PTR_ERR(past_scrubs)));
1775 in_progress = is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices);
1777 printf("scrub status for %s\n", fsid);
1779 if (do_stats_per_dev) {
1780 for (i = 0; i < fi_args.num_devices; ++i) {
1781 last_scrub = last_dev_scrub(past_scrubs,
1784 print_scrub_dev(&di_args[i], NULL, print_raw,
1788 last_scrub->stats.in_progress = in_progress;
1789 print_scrub_dev(&di_args[i], &last_scrub->p, print_raw,
1790 last_scrub->stats.finished ?
1791 "history" : "status",
1792 &last_scrub->stats);
1795 init_fs_stat(&fs_stat);
1796 fs_stat.s.in_progress = in_progress;
1797 for (i = 0; i < fi_args.num_devices; ++i) {
1798 last_scrub = last_dev_scrub(past_scrubs,
1802 add_to_fs_stat(&last_scrub->p, &last_scrub->stats,
1805 print_fs_stat(&fs_stat, print_raw);
1809 free_history(past_scrubs);
1813 close_file_or_dir(fdmnt, dirstream);
1818 static const char scrub_cmd_group_info[] =
1819 "verify checksums of data and metadata";
1821 const struct cmd_group scrub_cmd_group = {
1822 scrub_cmd_group_usage, scrub_cmd_group_info, {
1823 { "start", cmd_scrub_start, cmd_scrub_start_usage, NULL, 0 },
1824 { "cancel", cmd_scrub_cancel, cmd_scrub_cancel_usage, NULL, 0 },
1825 { "resume", cmd_scrub_resume, cmd_scrub_resume_usage, NULL, 0 },
1826 { "status", cmd_scrub_status, cmd_scrub_status_usage, NULL, 0 },
1831 int cmd_scrub(int argc, char **argv)
1833 return handle_command_group(&scrub_cmd_group, argc, argv);