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);
506 return ERR_PTR(-errno);
512 case 0: /* start of file */
513 ret = scrub_kvread(&i,
514 sizeof(SCRUB_FILE_VERSION_PREFIX), avail, l,
515 SCRUB_FILE_VERSION_PREFIX, &version);
518 if (version != atoll(SCRUB_FILE_VERSION))
519 return ERR_PTR(-ENOTSUP);
522 case 1: /* start of line, alloc */
524 * this state makes sure we have a complete line in
525 * further processing, so we don't need wrap-tracking
528 if (!eof && !memchr(l + i, '\n', avail - i))
531 if (curr > -1 && memcmp(p[curr]->fsid, empty_uuid,
532 BTRFS_FSID_SIZE) == 0) {
537 p = realloc(p, (curr + 2) * sizeof(*p));
539 p[curr] = malloc(sizeof(**p));
541 return ERR_PTR(-errno);
542 memset(p[curr], 0, sizeof(**p));
546 case 2: /* start of line, skip space */
547 while (isspace(l[i]) && i < avail) {
553 (!eof && !memchr(l + i, '\n', avail - i)))
557 case 3: /* read fsid */
560 for (j = 0; l[i + j] != ':' && i + j < avail; ++j)
562 if (i + j + 1 >= avail)
564 if (j != BTRFS_UUID_UNPARSED_SIZE - 1)
567 ret = uuid_parse(l + i, p[curr]->fsid);
573 case 4: /* read dev id */
574 for (j = 0; isdigit(l[i + j]) && i+j < avail; ++j)
576 if (j == 0 || i + j + 1 >= avail)
578 p[curr]->devid = atoll(&l[i]);
582 case 5: /* read key/value pair */
584 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
586 _SCRUB_KVREAD(ret, &i, data_extents_scrubbed, avail, l,
588 _SCRUB_KVREAD(ret, &i, tree_extents_scrubbed, avail, l,
590 _SCRUB_KVREAD(ret, &i, data_bytes_scrubbed, avail, l,
592 _SCRUB_KVREAD(ret, &i, tree_bytes_scrubbed, avail, l,
594 _SCRUB_KVREAD(ret, &i, read_errors, avail, l,
596 _SCRUB_KVREAD(ret, &i, csum_errors, avail, l,
598 _SCRUB_KVREAD(ret, &i, verify_errors, avail, l,
600 _SCRUB_KVREAD(ret, &i, no_csum, avail, l,
602 _SCRUB_KVREAD(ret, &i, csum_discards, avail, l,
604 _SCRUB_KVREAD(ret, &i, super_errors, avail, l,
606 _SCRUB_KVREAD(ret, &i, malloc_errors, avail, l,
608 _SCRUB_KVREAD(ret, &i, uncorrectable_errors, avail, l,
610 _SCRUB_KVREAD(ret, &i, corrected_errors, avail, l,
612 _SCRUB_KVREAD(ret, &i, last_physical, avail, l,
614 _SCRUB_KVREAD(ret, &i, finished, avail, l,
616 _SCRUB_KVREAD(ret, &i, t_start, avail, l,
617 (u64 *)&p[curr]->stats);
618 _SCRUB_KVREAD(ret, &i, t_resumed, avail, l,
619 (u64 *)&p[curr]->stats);
620 _SCRUB_KVREAD(ret, &i, duration, avail, l,
621 (u64 *)&p[curr]->stats);
622 _SCRUB_KVREAD(ret, &i, canceled, avail, l,
628 case 6: /* after number */
631 else if (l[i] == '\n')
637 case 99: /* skip rest of line */
642 if (l[i - 1] == '\n') {
654 static int scrub_write_buf(int fd, const void *data, int len)
657 ret = write(fd, data, len);
661 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
662 __attribute__ ((format (printf, 4, 5)));
663 static int scrub_writev(int fd, char *buf, int max, const char *fmt, ...)
669 ret = vsnprintf(buf, max, fmt, args);
673 return scrub_write_buf(fd, buf, ret);
676 #define _SCRUB_SUM(dest, data, name) dest->scrub_args.progress.name = \
677 data->resumed->p.name + data->scrub_args.progress.name
679 static struct scrub_progress *scrub_resumed_stats(struct scrub_progress *data,
680 struct scrub_progress *dest)
682 if (!data->resumed || data->skip)
685 _SCRUB_SUM(dest, data, data_extents_scrubbed);
686 _SCRUB_SUM(dest, data, tree_extents_scrubbed);
687 _SCRUB_SUM(dest, data, data_bytes_scrubbed);
688 _SCRUB_SUM(dest, data, tree_bytes_scrubbed);
689 _SCRUB_SUM(dest, data, read_errors);
690 _SCRUB_SUM(dest, data, csum_errors);
691 _SCRUB_SUM(dest, data, verify_errors);
692 _SCRUB_SUM(dest, data, no_csum);
693 _SCRUB_SUM(dest, data, csum_discards);
694 _SCRUB_SUM(dest, data, super_errors);
695 _SCRUB_SUM(dest, data, malloc_errors);
696 _SCRUB_SUM(dest, data, uncorrectable_errors);
697 _SCRUB_SUM(dest, data, corrected_errors);
698 _SCRUB_SUM(dest, data, last_physical);
699 dest->stats.canceled = data->stats.canceled;
700 dest->stats.finished = data->stats.finished;
701 dest->stats.t_resumed = data->stats.t_start;
702 dest->stats.t_start = data->resumed->stats.t_start;
703 dest->stats.duration = data->resumed->stats.duration +
704 data->stats.duration;
705 dest->scrub_args.devid = data->scrub_args.devid;
709 #define _SCRUB_KVWRITE(fd, buf, name, use) \
710 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
711 use->scrub_args.progress.name)
713 #define _SCRUB_KVWRITE_STATS(fd, buf, name, use) \
714 scrub_kvwrite(fd, buf, sizeof(buf), #name, \
717 static int scrub_kvwrite(int fd, char *buf, int max, const char *key, u64 val)
719 return scrub_writev(fd, buf, max, "|%s:%lld", key, val);
722 static int scrub_write_file(int fd, const char *fsid,
723 struct scrub_progress *data, int n)
728 struct scrub_progress local;
729 struct scrub_progress *use;
734 /* each -1 is to subtract one \0 byte, the + 2 is for ':' and '\n' */
735 ret = scrub_write_buf(fd, SCRUB_FILE_VERSION_PREFIX ":"
736 SCRUB_FILE_VERSION "\n",
737 (sizeof(SCRUB_FILE_VERSION_PREFIX) - 1) +
738 (sizeof(SCRUB_FILE_VERSION) - 1) + 2);
742 for (i = 0; i < n; ++i) {
743 use = scrub_resumed_stats(&data[i], &local);
744 if (scrub_write_buf(fd, fsid, strlen(fsid)) ||
745 scrub_write_buf(fd, ":", 1) ||
746 scrub_writev(fd, buf, sizeof(buf), "%lld",
747 use->scrub_args.devid) ||
748 scrub_write_buf(fd, buf, ret) ||
749 _SCRUB_KVWRITE(fd, buf, data_extents_scrubbed, use) ||
750 _SCRUB_KVWRITE(fd, buf, tree_extents_scrubbed, use) ||
751 _SCRUB_KVWRITE(fd, buf, data_bytes_scrubbed, use) ||
752 _SCRUB_KVWRITE(fd, buf, tree_bytes_scrubbed, use) ||
753 _SCRUB_KVWRITE(fd, buf, read_errors, use) ||
754 _SCRUB_KVWRITE(fd, buf, csum_errors, use) ||
755 _SCRUB_KVWRITE(fd, buf, verify_errors, use) ||
756 _SCRUB_KVWRITE(fd, buf, no_csum, use) ||
757 _SCRUB_KVWRITE(fd, buf, csum_discards, use) ||
758 _SCRUB_KVWRITE(fd, buf, super_errors, use) ||
759 _SCRUB_KVWRITE(fd, buf, malloc_errors, use) ||
760 _SCRUB_KVWRITE(fd, buf, uncorrectable_errors, use) ||
761 _SCRUB_KVWRITE(fd, buf, corrected_errors, use) ||
762 _SCRUB_KVWRITE(fd, buf, last_physical, use) ||
763 _SCRUB_KVWRITE_STATS(fd, buf, t_start, use) ||
764 _SCRUB_KVWRITE_STATS(fd, buf, t_resumed, use) ||
765 _SCRUB_KVWRITE_STATS(fd, buf, duration, use) ||
766 _SCRUB_KVWRITE_STATS(fd, buf, canceled, use) ||
767 _SCRUB_KVWRITE_STATS(fd, buf, finished, use) ||
768 scrub_write_buf(fd, "\n", 1)) {
776 static int scrub_write_progress(pthread_mutex_t *m, const char *fsid,
777 struct scrub_progress *data, int n)
784 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old);
790 ret = pthread_mutex_lock(m);
796 fd = scrub_open_file_w(SCRUB_DATA_FILE, fsid, "tmp");
801 err = scrub_write_file(fd, fsid, data, n);
804 err = scrub_rename_file(SCRUB_DATA_FILE, fsid, "tmp");
815 ret = pthread_mutex_unlock(m);
820 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old);
828 static void *scrub_one_dev(void *ctx)
830 struct scrub_progress *sp = ctx;
834 sp->stats.canceled = 0;
835 sp->stats.duration = 0;
836 sp->stats.finished = 0;
838 ret = syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0,
839 IOPRIO_PRIO_VALUE(sp->ioprio_class,
840 sp->ioprio_classdata));
843 "WARNING: setting ioprio failed: %s (ignored).\n",
846 ret = ioctl(sp->fd, BTRFS_IOC_SCRUB, &sp->scrub_args);
847 gettimeofday(&tv, NULL);
849 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
850 sp->stats.canceled = !!ret;
851 sp->ioctl_errno = errno;
852 ret = pthread_mutex_lock(&sp->progress_mutex);
854 return ERR_PTR(-ret);
855 sp->stats.finished = 1;
856 ret = pthread_mutex_unlock(&sp->progress_mutex);
858 return ERR_PTR(-ret);
863 static void *progress_one_dev(void *ctx)
865 struct scrub_progress *sp = ctx;
867 sp->ret = ioctl(sp->fd, BTRFS_IOC_SCRUB_PROGRESS, &sp->scrub_args);
868 sp->ioctl_errno = errno;
873 /* nb: returns a negative errno via ERR_PTR */
874 static void *scrub_progress_cycle(void *ctx)
877 int perr = 0; /* positive / pthread error returns */
880 char fsid[BTRFS_UUID_UNPARSED_SIZE];
881 struct scrub_progress *sp;
882 struct scrub_progress *sp_last;
883 struct scrub_progress *sp_shared;
885 struct scrub_progress_cycle *spc = ctx;
886 int ndev = spc->fi->num_devices;
890 struct pollfd accept_poll_fd = {
895 struct pollfd write_poll_fd = {
899 struct sockaddr_un peer;
900 socklen_t peer_size = sizeof(peer);
902 perr = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old);
906 uuid_unparse(spc->fi->fsid, fsid);
908 for (i = 0; i < ndev; ++i) {
909 sp = &spc->progress[i];
910 sp_last = &spc->progress[i + ndev];
911 sp_shared = &spc->shared_progress[i];
912 sp->scrub_args.devid = sp_last->scrub_args.devid =
913 sp_shared->scrub_args.devid;
914 sp->fd = sp_last->fd = spc->fdmnt;
915 sp->stats.t_start = sp_last->stats.t_start =
916 sp_shared->stats.t_start;
917 sp->resumed = sp_last->resumed = sp_shared->resumed;
918 sp->skip = sp_last->skip = sp_shared->skip;
919 sp->stats.finished = sp_last->stats.finished =
920 sp_shared->stats.finished;
924 ret = poll(&accept_poll_fd, 1, 5 * 1000);
930 peer_fd = accept(spc->prg_fd, (struct sockaddr *)&peer,
932 gettimeofday(&tv, NULL);
935 for (i = 0; i < ndev; ++i) {
936 sp = &spc->progress[this * ndev + i];
937 sp_last = &spc->progress[last * ndev + i];
938 sp_shared = &spc->shared_progress[i];
939 if (sp->stats.finished)
941 progress_one_dev(sp);
942 sp->stats.duration = tv.tv_sec - sp->stats.t_start;
945 if (sp->ioctl_errno != ENOTCONN &&
946 sp->ioctl_errno != ENODEV) {
947 ret = -sp->ioctl_errno;
951 * scrub finished or device removed, check the
952 * finished flag. if unset, just use the last
953 * result we got for the current write and go
954 * on. flag should be set on next cycle, then.
956 perr = pthread_setcancelstate(
957 PTHREAD_CANCEL_DISABLE, &old);
960 perr = pthread_mutex_lock(&sp_shared->progress_mutex);
963 if (!sp_shared->stats.finished) {
964 perr = pthread_mutex_unlock(
965 &sp_shared->progress_mutex);
968 perr = pthread_setcancelstate(
969 PTHREAD_CANCEL_ENABLE, &old);
972 memcpy(sp, sp_last, sizeof(*sp));
975 perr = pthread_mutex_unlock(&sp_shared->progress_mutex);
978 perr = pthread_setcancelstate(
979 PTHREAD_CANCEL_ENABLE, &old);
982 memcpy(sp, sp_shared, sizeof(*sp));
983 memcpy(sp_last, sp_shared, sizeof(*sp));
986 write_poll_fd.fd = peer_fd;
987 ret = poll(&write_poll_fd, 1, 0);
993 ret = scrub_write_file(
995 &spc->progress[this * ndev], ndev);
1002 if (!spc->do_record)
1004 ret = scrub_write_progress(spc->write_mutex, fsid,
1005 &spc->progress[this * ndev], ndev);
1014 return ERR_PTR(ret);
1017 static struct scrub_file_record *last_dev_scrub(
1018 struct scrub_file_record *const *const past_scrubs, u64 devid)
1022 if (!past_scrubs || IS_ERR(past_scrubs))
1025 for (i = 0; past_scrubs[i]; ++i)
1026 if (past_scrubs[i]->devid == devid)
1027 return past_scrubs[i];
1032 static int mkdir_p(char *path)
1037 for (i = 1; i < strlen(path); ++i) {
1041 ret = mkdir(path, 0777);
1042 if (ret && errno != EEXIST)
1050 static int is_scrub_running_on_fs(struct btrfs_ioctl_fs_info_args *fi_args,
1051 struct btrfs_ioctl_dev_info_args *di_args,
1052 struct scrub_file_record **past_scrubs)
1056 if (!fi_args || !di_args || !past_scrubs)
1059 for (i = 0; i < fi_args->num_devices; i++) {
1060 struct scrub_file_record *sfr =
1061 last_dev_scrub(past_scrubs, di_args[i].devid);
1065 if (!(sfr->stats.finished || sfr->stats.canceled))
1071 static int is_scrub_running_in_kernel(int fd,
1072 struct btrfs_ioctl_dev_info_args *di_args, u64 max_devices)
1074 struct scrub_progress sp;
1078 for (i = 0; i < max_devices; i++) {
1079 memset(&sp, 0, sizeof(sp));
1080 sp.scrub_args.devid = di_args[i].devid;
1081 ret = ioctl(fd, BTRFS_IOC_SCRUB_PROGRESS, &sp.scrub_args);
1089 static const char * const cmd_scrub_start_usage[];
1090 static const char * const cmd_scrub_resume_usage[];
1092 static int scrub_start(int argc, char **argv, int resume)
1102 int e_uncorrectable = 0;
1103 int e_correctable = 0;
1106 int do_background = 1;
1112 int do_stats_per_dev = 0;
1113 int ioprio_class = IOPRIO_CLASS_IDLE;
1114 int ioprio_classdata = 0;
1118 struct btrfs_ioctl_fs_info_args fi_args;
1119 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1120 struct scrub_progress *sp = NULL;
1121 struct scrub_fs_stat fs_stat;
1123 struct sockaddr_un addr = {
1124 .sun_family = AF_UNIX,
1126 pthread_t *t_devs = NULL;
1128 struct scrub_file_record **past_scrubs = NULL;
1129 struct scrub_file_record *last_scrub = NULL;
1130 char *datafile = strdup(SCRUB_DATA_FILE);
1131 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1132 char sock_path[PATH_MAX] = "";
1133 struct scrub_progress_cycle spc;
1134 pthread_mutex_t spc_write_mutex = PTHREAD_MUTEX_INITIALIZER;
1137 DIR *dirstream = NULL;
1139 int nothing_to_resume = 0;
1142 while ((c = getopt(argc, argv, "BdqrRc:n:f")) != -1) {
1150 do_stats_per_dev = 1;
1162 ioprio_class = (int)strtol(optarg, NULL, 10);
1165 ioprio_classdata = (int)strtol(optarg, NULL, 10);
1172 usage(resume ? cmd_scrub_resume_usage :
1173 cmd_scrub_start_usage);
1177 /* try to catch most error cases before forking */
1179 if (check_argc_exact(argc - optind, 1)) {
1180 usage(resume ? cmd_scrub_resume_usage :
1181 cmd_scrub_start_usage);
1184 spc.progress = NULL;
1185 if (do_quiet && do_print)
1188 if (mkdir_p(datafile)) {
1189 ERR(!do_quiet, "WARNING: cannot create scrub data "
1190 "file, mkdir %s failed: %s. Status recording "
1191 "disabled\n", datafile, strerror(errno));
1196 path = argv[optind];
1198 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1201 if (errno == EINVAL)
1203 "ERROR: '%s' is not a mounted btrfs device\n",
1206 ERR(!do_quiet, "ERROR: can't access '%s': %s\n",
1207 path, strerror(errno));
1211 ret = get_fs_info(path, &fi_args, &di_args);
1213 ERR(!do_quiet, "ERROR: getting dev info for scrub failed: "
1214 "%s\n", strerror(-ret));
1218 if (!fi_args.num_devices) {
1219 ERR(!do_quiet, "ERROR: no devices found\n");
1224 uuid_unparse(fi_args.fsid, fsid);
1225 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1226 if (fdres < 0 && fdres != -ENOENT) {
1227 ERR(!do_quiet, "WARNING: failed to open status file: "
1228 "%s\n", strerror(-fdres));
1229 } else if (fdres >= 0) {
1230 past_scrubs = scrub_read_file(fdres, !do_quiet);
1231 if (IS_ERR(past_scrubs))
1232 ERR(!do_quiet, "WARNING: failed to read status file: "
1233 "%s\n", strerror(-PTR_ERR(past_scrubs)));
1238 * Check for stale information in the status file, ie. if it's
1239 * canceled=0, finished=0 but no scrub is running.
1241 if (!is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices))
1245 * check whether any involved device is already busy running a
1246 * scrub. This would cause damaged status messages and the state
1247 * "aborted" without the explanation that a scrub was already
1248 * running. Therefore check it first, prevent it and give some
1249 * feedback to the user if scrub is already running.
1250 * Note that if scrub is started with a block device as the
1251 * parameter, only that particular block device is checked. It
1252 * is a normal mode of operation to start scrub on multiple
1253 * single devices, there is no reason to prevent this.
1255 if (!force && is_scrub_running_on_fs(&fi_args, di_args, past_scrubs)) {
1257 "ERROR: scrub is already running.\n"
1258 "To cancel use 'btrfs scrub cancel %s'.\n"
1259 "To see the status use 'btrfs scrub status [-d] %s'.\n",
1265 t_devs = malloc(fi_args.num_devices * sizeof(*t_devs));
1266 sp = calloc(fi_args.num_devices, sizeof(*sp));
1267 spc.progress = calloc(fi_args.num_devices * 2, sizeof(*spc.progress));
1269 if (!t_devs || !sp || !spc.progress) {
1270 ERR(!do_quiet, "ERROR: scrub failed: %s", strerror(errno));
1275 for (i = 0; i < fi_args.num_devices; ++i) {
1276 devid = di_args[i].devid;
1277 ret = pthread_mutex_init(&sp[i].progress_mutex, NULL);
1279 ERR(!do_quiet, "ERROR: pthread_mutex_init failed: "
1280 "%s\n", strerror(ret));
1284 last_scrub = last_dev_scrub(past_scrubs, devid);
1285 sp[i].scrub_args.devid = devid;
1287 if (resume && last_scrub && (last_scrub->stats.canceled ||
1288 !last_scrub->stats.finished)) {
1290 sp[i].scrub_args.start = last_scrub->p.last_physical;
1291 sp[i].resumed = last_scrub;
1292 } else if (resume) {
1295 sp[i].resumed = last_scrub;
1299 sp[i].scrub_args.start = 0ll;
1300 sp[i].resumed = NULL;
1303 sp[i].scrub_args.end = (u64)-1ll;
1304 sp[i].scrub_args.flags = readonly ? BTRFS_SCRUB_READONLY : 0;
1305 sp[i].ioprio_class = ioprio_class;
1306 sp[i].ioprio_classdata = ioprio_classdata;
1309 if (!n_start && !n_resume) {
1311 printf("scrub: nothing to resume for %s, fsid %s\n",
1313 nothing_to_resume = 1;
1317 ret = prg_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1319 ret = scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid, NULL,
1320 sock_path, sizeof(sock_path));
1321 /* ignore EOVERFLOW, try using a shorter path for the socket */
1322 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1323 strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1);
1324 ret = bind(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1325 if (ret != -1 || errno != EADDRINUSE)
1328 * bind failed with EADDRINUSE. so let's see if anyone answers
1329 * when we make a call to the socket ...
1331 ret = connect(prg_fd, (struct sockaddr *)&addr, sizeof(addr));
1332 if (!ret || errno != ECONNREFUSED) {
1333 /* ... yes, so scrub must be running. error out */
1334 fprintf(stderr, "ERROR: scrub already running\n");
1340 * ... no, this means someone left us alone with an unused
1341 * socket in the file system. remove it and try again.
1343 ret = unlink(sock_path);
1346 ret = listen(prg_fd, 100);
1348 ERR(!do_quiet, "WARNING: failed to open the progress status "
1349 "socket at %s: %s. Progress cannot be queried\n",
1350 sock_path[0] ? sock_path : SCRUB_PROGRESS_SOCKET_PATH,
1361 /* write all-zero progress file for a start */
1362 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1363 fi_args.num_devices);
1365 ERR(!do_quiet, "WARNING: failed to write the progress "
1366 "status file: %s. Status recording disabled\n",
1372 if (do_background) {
1375 ERR(!do_quiet, "ERROR: cannot scrub, fork failed: "
1376 "%s\n", strerror(errno));
1383 scrub_handle_sigint_parent();
1385 printf("scrub %s on %s, fsid %s (pid=%d)\n",
1386 n_start ? "started" : "resumed",
1394 ERR(!do_quiet, "ERROR: wait failed: (ret=%d) "
1395 "%s\n", ret, strerror(errno));
1399 if (!WIFEXITED(stat) || WEXITSTATUS(stat)) {
1400 ERR(!do_quiet, "ERROR: scrub process failed\n");
1401 err = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
1409 scrub_handle_sigint_child(fdmnt);
1411 for (i = 0; i < fi_args.num_devices; ++i) {
1413 sp[i].scrub_args.progress = sp[i].resumed->p;
1414 sp[i].stats = sp[i].resumed->stats;
1416 sp[i].stats.finished = 1;
1419 devid = di_args[i].devid;
1420 gettimeofday(&tv, NULL);
1421 sp[i].stats.t_start = tv.tv_sec;
1422 ret = pthread_create(&t_devs[i], NULL,
1423 scrub_one_dev, &sp[i]);
1426 fprintf(stderr, "ERROR: creating "
1427 "scrub_one_dev[%llu] thread failed: "
1428 "%s\n", devid, strerror(ret));
1435 spc.prg_fd = prg_fd;
1436 spc.do_record = do_record;
1437 spc.write_mutex = &spc_write_mutex;
1438 spc.shared_progress = sp;
1440 ret = pthread_create(&t_prog, NULL, scrub_progress_cycle, &spc);
1443 fprintf(stderr, "ERROR: creating progress thread "
1444 "failed: %s\n", strerror(ret));
1450 for (i = 0; i < fi_args.num_devices; ++i) {
1453 devid = di_args[i].devid;
1454 ret = pthread_join(t_devs[i], NULL);
1457 fprintf(stderr, "ERROR: pthread_join failed "
1458 "for scrub_one_dev[%llu]: %s\n", devid,
1463 if (sp[i].ret && sp[i].ioctl_errno == ENODEV) {
1465 fprintf(stderr, "WARNING: device %lld not "
1466 "present\n", devid);
1469 if (sp[i].ret && sp[i].ioctl_errno == ECANCELED) {
1471 } else if (sp[i].ret) {
1473 fprintf(stderr, "ERROR: scrubbing %s failed "
1474 "for device id %lld (%s)\n", path,
1475 devid, strerror(sp[i].ioctl_errno));
1479 if (sp[i].scrub_args.progress.uncorrectable_errors > 0)
1481 if (sp[i].scrub_args.progress.corrected_errors > 0
1482 || sp[i].scrub_args.progress.unverified_errors > 0)
1487 const char *append = "done";
1488 if (!do_stats_per_dev)
1489 init_fs_stat(&fs_stat);
1490 for (i = 0; i < fi_args.num_devices; ++i) {
1491 if (do_stats_per_dev) {
1492 print_scrub_dev(&di_args[i],
1493 &sp[i].scrub_args.progress,
1495 sp[i].ret ? "canceled" : "done",
1499 append = "canceled";
1500 add_to_fs_stat(&sp[i].scrub_args.progress,
1501 &sp[i].stats, &fs_stat);
1504 if (!do_stats_per_dev) {
1505 printf("scrub %s for %s\n", append, fsid);
1506 print_fs_stat(&fs_stat, print_raw);
1510 ret = pthread_cancel(t_prog);
1512 ret = pthread_join(t_prog, &terr);
1514 /* check for errors from the handling of the progress thread */
1515 if (do_print && ret) {
1516 fprintf(stderr, "ERROR: progress thread handling failed: %s\n",
1520 /* check for errors returned from the progress thread itself */
1521 if (do_print && terr && terr != PTHREAD_CANCELED) {
1522 fprintf(stderr, "ERROR: recording progress "
1523 "failed: %s\n", strerror(-PTR_ERR(terr)));
1527 ret = scrub_write_progress(&spc_write_mutex, fsid, sp,
1528 fi_args.num_devices);
1529 if (ret && do_print) {
1530 fprintf(stderr, "ERROR: failed to record the result: "
1531 "%s\n", strerror(-ret));
1535 scrub_handle_sigint_child(-1);
1538 free_history(past_scrubs);
1548 close_file_or_dir(fdmnt, dirstream);
1552 if (nothing_to_resume)
1554 if (e_uncorrectable) {
1555 ERR(!do_quiet, "ERROR: There are uncorrectable errors.\n");
1559 ERR(!do_quiet, "WARNING: errors detected during scrubbing, corrected.\n");
1564 static const char * const cmd_scrub_start_usage[] = {
1565 "btrfs scrub start [-BdqrRf] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1566 "Start a new scrub. If a scrub is already running, the new one fails.",
1568 "-B do not background",
1569 "-d stats per device (-B only)",
1571 "-r read only mode",
1572 "-R raw print mode, print full data instead of summary",
1573 "-c set ioprio class (see ionice(1) manpage)",
1574 "-n set ioprio classdata (see ionice(1) manpage)",
1575 "-f force starting new scrub even if a scrub is already running",
1576 " this is useful when scrub stats record file is damaged",
1580 static int cmd_scrub_start(int argc, char **argv)
1582 return scrub_start(argc, argv, 0);
1585 static const char * const cmd_scrub_cancel_usage[] = {
1586 "btrfs scrub cancel <path>|<device>",
1587 "Cancel a running scrub",
1591 static int cmd_scrub_cancel(int argc, char **argv)
1596 DIR *dirstream = NULL;
1598 if (check_argc_exact(argc, 2))
1599 usage(cmd_scrub_cancel_usage);
1603 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1605 if (errno == EINVAL)
1607 "ERROR: '%s' is not a mounted btrfs device\n",
1610 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1611 path, strerror(errno));
1616 ret = ioctl(fdmnt, BTRFS_IOC_SCRUB_CANCEL, NULL);
1619 fprintf(stderr, "ERROR: scrub cancel failed on %s: %s\n", path,
1620 errno == ENOTCONN ? "not running" : strerror(errno));
1621 if (errno == ENOTCONN)
1629 printf("scrub cancelled\n");
1632 close_file_or_dir(fdmnt, dirstream);
1636 static const char * const cmd_scrub_resume_usage[] = {
1637 "btrfs scrub resume [-BdqrR] [-c ioprio_class -n ioprio_classdata] <path>|<device>",
1638 "Resume previously canceled or interrupted scrub",
1640 "-B do not background",
1641 "-d stats per device (-B only)",
1643 "-r read only mode",
1644 "-R raw print mode, print full data instead of summary",
1645 "-c set ioprio class (see ionice(1) manpage)",
1646 "-n set ioprio classdata (see ionice(1) manpage)",
1650 static int cmd_scrub_resume(int argc, char **argv)
1652 return scrub_start(argc, argv, 1);
1655 static const char * const cmd_scrub_status_usage[] = {
1656 "btrfs scrub status [-dR] <path>|<device>",
1657 "Show status of running or finished scrub",
1659 "-d stats per device",
1660 "-R print raw stats",
1664 static int cmd_scrub_status(int argc, char **argv)
1667 struct btrfs_ioctl_fs_info_args fi_args;
1668 struct btrfs_ioctl_dev_info_args *di_args = NULL;
1669 struct scrub_file_record **past_scrubs = NULL;
1670 struct scrub_file_record *last_scrub;
1671 struct scrub_fs_stat fs_stat;
1672 struct sockaddr_un addr = {
1673 .sun_family = AF_UNIX,
1680 int do_stats_per_dev = 0;
1682 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1685 DIR *dirstream = NULL;
1688 while ((c = getopt(argc, argv, "dR")) != -1) {
1691 do_stats_per_dev = 1;
1698 usage(cmd_scrub_status_usage);
1702 if (check_argc_exact(argc - optind, 1))
1703 usage(cmd_scrub_status_usage);
1705 path = argv[optind];
1707 fdmnt = open_path_or_dev_mnt(path, &dirstream);
1710 if (errno == EINVAL)
1712 "ERROR: '%s' is not a mounted btrfs device\n",
1715 fprintf(stderr, "ERROR: can't access '%s': %s\n",
1716 path, strerror(errno));
1720 ret = get_fs_info(path, &fi_args, &di_args);
1722 fprintf(stderr, "ERROR: getting dev info for scrub failed: "
1723 "%s\n", strerror(-ret));
1727 if (!fi_args.num_devices) {
1728 fprintf(stderr, "ERROR: no devices found\n");
1733 uuid_unparse(fi_args.fsid, fsid);
1735 fdres = socket(AF_UNIX, SOCK_STREAM, 0);
1737 fprintf(stderr, "ERROR: failed to create socket to "
1738 "receive progress information: %s\n",
1743 scrub_datafile(SCRUB_PROGRESS_SOCKET_PATH, fsid,
1744 NULL, addr.sun_path, sizeof(addr.sun_path));
1745 /* ignore EOVERFLOW, just use shorter name and hope for the best */
1746 addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
1747 ret = connect(fdres, (struct sockaddr *)&addr, sizeof(addr));
1750 fdres = scrub_open_file_r(SCRUB_DATA_FILE, fsid);
1751 if (fdres < 0 && fdres != -ENOENT) {
1752 fprintf(stderr, "WARNING: failed to open status file: "
1753 "%s\n", strerror(-fdres));
1760 past_scrubs = scrub_read_file(fdres, 1);
1761 if (IS_ERR(past_scrubs))
1762 fprintf(stderr, "WARNING: failed to read status: %s\n",
1763 strerror(-PTR_ERR(past_scrubs)));
1765 in_progress = is_scrub_running_in_kernel(fdmnt, di_args, fi_args.num_devices);
1767 printf("scrub status for %s\n", fsid);
1769 if (do_stats_per_dev) {
1770 for (i = 0; i < fi_args.num_devices; ++i) {
1771 last_scrub = last_dev_scrub(past_scrubs,
1774 print_scrub_dev(&di_args[i], NULL, print_raw,
1778 last_scrub->stats.in_progress = in_progress;
1779 print_scrub_dev(&di_args[i], &last_scrub->p, print_raw,
1780 last_scrub->stats.finished ?
1781 "history" : "status",
1782 &last_scrub->stats);
1785 init_fs_stat(&fs_stat);
1786 fs_stat.s.in_progress = in_progress;
1787 for (i = 0; i < fi_args.num_devices; ++i) {
1788 last_scrub = last_dev_scrub(past_scrubs,
1792 add_to_fs_stat(&last_scrub->p, &last_scrub->stats,
1795 print_fs_stat(&fs_stat, print_raw);
1799 free_history(past_scrubs);
1803 close_file_or_dir(fdmnt, dirstream);
1808 static const char scrub_cmd_group_info[] =
1809 "verify checksums of data and metadata";
1811 const struct cmd_group scrub_cmd_group = {
1812 scrub_cmd_group_usage, scrub_cmd_group_info, {
1813 { "start", cmd_scrub_start, cmd_scrub_start_usage, NULL, 0 },
1814 { "cancel", cmd_scrub_cancel, cmd_scrub_cancel_usage, NULL, 0 },
1815 { "resume", cmd_scrub_resume, cmd_scrub_resume_usage, NULL, 0 },
1816 { "status", cmd_scrub_status, cmd_scrub_status_usage, NULL, 0 },
1821 int cmd_scrub(int argc, char **argv)
1823 return handle_command_group(&scrub_cmd_group, argc, argv);