xref: /linux/fs/btrfs/scrub.c (revision a67ff6a54095e27093ea501fb143fefe51a536c2)
1 /*
2  * Copyright (C) 2011 STRATO.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 
19 #include <linux/blkdev.h>
20 #include <linux/ratelimit.h>
21 #include "ctree.h"
22 #include "volumes.h"
23 #include "disk-io.h"
24 #include "ordered-data.h"
25 #include "transaction.h"
26 #include "backref.h"
27 #include "extent_io.h"
28 
29 /*
30  * This is only the first step towards a full-features scrub. It reads all
31  * extent and super block and verifies the checksums. In case a bad checksum
32  * is found or the extent cannot be read, good data will be written back if
33  * any can be found.
34  *
35  * Future enhancements:
36  *  - In case an unrepairable extent is encountered, track which files are
37  *    affected and report them
38  *  - In case of a read error on files with nodatasum, map the file and read
39  *    the extent to trigger a writeback of the good copy
40  *  - track and record media errors, throw out bad devices
41  *  - add a mode to also read unallocated space
42  */
43 
44 struct scrub_bio;
45 struct scrub_page;
46 struct scrub_dev;
47 static void scrub_bio_end_io(struct bio *bio, int err);
48 static void scrub_checksum(struct btrfs_work *work);
49 static int scrub_checksum_data(struct scrub_dev *sdev,
50 			       struct scrub_page *spag, void *buffer);
51 static int scrub_checksum_tree_block(struct scrub_dev *sdev,
52 				     struct scrub_page *spag, u64 logical,
53 				     void *buffer);
54 static int scrub_checksum_super(struct scrub_bio *sbio, void *buffer);
55 static int scrub_fixup_check(struct scrub_bio *sbio, int ix);
56 static void scrub_fixup_end_io(struct bio *bio, int err);
57 static int scrub_fixup_io(int rw, struct block_device *bdev, sector_t sector,
58 			  struct page *page);
59 static void scrub_fixup(struct scrub_bio *sbio, int ix);
60 
61 #define SCRUB_PAGES_PER_BIO	16	/* 64k per bio */
62 #define SCRUB_BIOS_PER_DEV	16	/* 1 MB per device in flight */
63 
64 struct scrub_page {
65 	u64			flags;  /* extent flags */
66 	u64			generation;
67 	int			mirror_num;
68 	int			have_csum;
69 	u8			csum[BTRFS_CSUM_SIZE];
70 };
71 
72 struct scrub_bio {
73 	int			index;
74 	struct scrub_dev	*sdev;
75 	struct bio		*bio;
76 	int			err;
77 	u64			logical;
78 	u64			physical;
79 	struct scrub_page	spag[SCRUB_PAGES_PER_BIO];
80 	u64			count;
81 	int			next_free;
82 	struct btrfs_work	work;
83 };
84 
85 struct scrub_dev {
86 	struct scrub_bio	*bios[SCRUB_BIOS_PER_DEV];
87 	struct btrfs_device	*dev;
88 	int			first_free;
89 	int			curr;
90 	atomic_t		in_flight;
91 	atomic_t		fixup_cnt;
92 	spinlock_t		list_lock;
93 	wait_queue_head_t	list_wait;
94 	u16			csum_size;
95 	struct list_head	csum_list;
96 	atomic_t		cancel_req;
97 	int			readonly;
98 	/*
99 	 * statistics
100 	 */
101 	struct btrfs_scrub_progress stat;
102 	spinlock_t		stat_lock;
103 };
104 
105 struct scrub_fixup_nodatasum {
106 	struct scrub_dev	*sdev;
107 	u64			logical;
108 	struct btrfs_root	*root;
109 	struct btrfs_work	work;
110 	int			mirror_num;
111 };
112 
113 struct scrub_warning {
114 	struct btrfs_path	*path;
115 	u64			extent_item_size;
116 	char			*scratch_buf;
117 	char			*msg_buf;
118 	const char		*errstr;
119 	sector_t		sector;
120 	u64			logical;
121 	struct btrfs_device	*dev;
122 	int			msg_bufsize;
123 	int			scratch_bufsize;
124 };
125 
126 static void scrub_free_csums(struct scrub_dev *sdev)
127 {
128 	while (!list_empty(&sdev->csum_list)) {
129 		struct btrfs_ordered_sum *sum;
130 		sum = list_first_entry(&sdev->csum_list,
131 				       struct btrfs_ordered_sum, list);
132 		list_del(&sum->list);
133 		kfree(sum);
134 	}
135 }
136 
137 static void scrub_free_bio(struct bio *bio)
138 {
139 	int i;
140 	struct page *last_page = NULL;
141 
142 	if (!bio)
143 		return;
144 
145 	for (i = 0; i < bio->bi_vcnt; ++i) {
146 		if (bio->bi_io_vec[i].bv_page == last_page)
147 			continue;
148 		last_page = bio->bi_io_vec[i].bv_page;
149 		__free_page(last_page);
150 	}
151 	bio_put(bio);
152 }
153 
154 static noinline_for_stack void scrub_free_dev(struct scrub_dev *sdev)
155 {
156 	int i;
157 
158 	if (!sdev)
159 		return;
160 
161 	for (i = 0; i < SCRUB_BIOS_PER_DEV; ++i) {
162 		struct scrub_bio *sbio = sdev->bios[i];
163 
164 		if (!sbio)
165 			break;
166 
167 		scrub_free_bio(sbio->bio);
168 		kfree(sbio);
169 	}
170 
171 	scrub_free_csums(sdev);
172 	kfree(sdev);
173 }
174 
175 static noinline_for_stack
176 struct scrub_dev *scrub_setup_dev(struct btrfs_device *dev)
177 {
178 	struct scrub_dev *sdev;
179 	int		i;
180 	struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
181 
182 	sdev = kzalloc(sizeof(*sdev), GFP_NOFS);
183 	if (!sdev)
184 		goto nomem;
185 	sdev->dev = dev;
186 	for (i = 0; i < SCRUB_BIOS_PER_DEV; ++i) {
187 		struct scrub_bio *sbio;
188 
189 		sbio = kzalloc(sizeof(*sbio), GFP_NOFS);
190 		if (!sbio)
191 			goto nomem;
192 		sdev->bios[i] = sbio;
193 
194 		sbio->index = i;
195 		sbio->sdev = sdev;
196 		sbio->count = 0;
197 		sbio->work.func = scrub_checksum;
198 
199 		if (i != SCRUB_BIOS_PER_DEV-1)
200 			sdev->bios[i]->next_free = i + 1;
201 		else
202 			sdev->bios[i]->next_free = -1;
203 	}
204 	sdev->first_free = 0;
205 	sdev->curr = -1;
206 	atomic_set(&sdev->in_flight, 0);
207 	atomic_set(&sdev->fixup_cnt, 0);
208 	atomic_set(&sdev->cancel_req, 0);
209 	sdev->csum_size = btrfs_super_csum_size(fs_info->super_copy);
210 	INIT_LIST_HEAD(&sdev->csum_list);
211 
212 	spin_lock_init(&sdev->list_lock);
213 	spin_lock_init(&sdev->stat_lock);
214 	init_waitqueue_head(&sdev->list_wait);
215 	return sdev;
216 
217 nomem:
218 	scrub_free_dev(sdev);
219 	return ERR_PTR(-ENOMEM);
220 }
221 
222 static int scrub_print_warning_inode(u64 inum, u64 offset, u64 root, void *ctx)
223 {
224 	u64 isize;
225 	u32 nlink;
226 	int ret;
227 	int i;
228 	struct extent_buffer *eb;
229 	struct btrfs_inode_item *inode_item;
230 	struct scrub_warning *swarn = ctx;
231 	struct btrfs_fs_info *fs_info = swarn->dev->dev_root->fs_info;
232 	struct inode_fs_paths *ipath = NULL;
233 	struct btrfs_root *local_root;
234 	struct btrfs_key root_key;
235 
236 	root_key.objectid = root;
237 	root_key.type = BTRFS_ROOT_ITEM_KEY;
238 	root_key.offset = (u64)-1;
239 	local_root = btrfs_read_fs_root_no_name(fs_info, &root_key);
240 	if (IS_ERR(local_root)) {
241 		ret = PTR_ERR(local_root);
242 		goto err;
243 	}
244 
245 	ret = inode_item_info(inum, 0, local_root, swarn->path);
246 	if (ret) {
247 		btrfs_release_path(swarn->path);
248 		goto err;
249 	}
250 
251 	eb = swarn->path->nodes[0];
252 	inode_item = btrfs_item_ptr(eb, swarn->path->slots[0],
253 					struct btrfs_inode_item);
254 	isize = btrfs_inode_size(eb, inode_item);
255 	nlink = btrfs_inode_nlink(eb, inode_item);
256 	btrfs_release_path(swarn->path);
257 
258 	ipath = init_ipath(4096, local_root, swarn->path);
259 	ret = paths_from_inode(inum, ipath);
260 
261 	if (ret < 0)
262 		goto err;
263 
264 	/*
265 	 * we deliberately ignore the bit ipath might have been too small to
266 	 * hold all of the paths here
267 	 */
268 	for (i = 0; i < ipath->fspath->elem_cnt; ++i)
269 		printk(KERN_WARNING "btrfs: %s at logical %llu on dev "
270 			"%s, sector %llu, root %llu, inode %llu, offset %llu, "
271 			"length %llu, links %u (path: %s)\n", swarn->errstr,
272 			swarn->logical, swarn->dev->name,
273 			(unsigned long long)swarn->sector, root, inum, offset,
274 			min(isize - offset, (u64)PAGE_SIZE), nlink,
275 			(char *)ipath->fspath->val[i]);
276 
277 	free_ipath(ipath);
278 	return 0;
279 
280 err:
281 	printk(KERN_WARNING "btrfs: %s at logical %llu on dev "
282 		"%s, sector %llu, root %llu, inode %llu, offset %llu: path "
283 		"resolving failed with ret=%d\n", swarn->errstr,
284 		swarn->logical, swarn->dev->name,
285 		(unsigned long long)swarn->sector, root, inum, offset, ret);
286 
287 	free_ipath(ipath);
288 	return 0;
289 }
290 
291 static void scrub_print_warning(const char *errstr, struct scrub_bio *sbio,
292 				int ix)
293 {
294 	struct btrfs_device *dev = sbio->sdev->dev;
295 	struct btrfs_fs_info *fs_info = dev->dev_root->fs_info;
296 	struct btrfs_path *path;
297 	struct btrfs_key found_key;
298 	struct extent_buffer *eb;
299 	struct btrfs_extent_item *ei;
300 	struct scrub_warning swarn;
301 	u32 item_size;
302 	int ret;
303 	u64 ref_root;
304 	u8 ref_level;
305 	unsigned long ptr = 0;
306 	const int bufsize = 4096;
307 	u64 extent_offset;
308 
309 	path = btrfs_alloc_path();
310 
311 	swarn.scratch_buf = kmalloc(bufsize, GFP_NOFS);
312 	swarn.msg_buf = kmalloc(bufsize, GFP_NOFS);
313 	swarn.sector = (sbio->physical + ix * PAGE_SIZE) >> 9;
314 	swarn.logical = sbio->logical + ix * PAGE_SIZE;
315 	swarn.errstr = errstr;
316 	swarn.dev = dev;
317 	swarn.msg_bufsize = bufsize;
318 	swarn.scratch_bufsize = bufsize;
319 
320 	if (!path || !swarn.scratch_buf || !swarn.msg_buf)
321 		goto out;
322 
323 	ret = extent_from_logical(fs_info, swarn.logical, path, &found_key);
324 	if (ret < 0)
325 		goto out;
326 
327 	extent_offset = swarn.logical - found_key.objectid;
328 	swarn.extent_item_size = found_key.offset;
329 
330 	eb = path->nodes[0];
331 	ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
332 	item_size = btrfs_item_size_nr(eb, path->slots[0]);
333 
334 	if (ret & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
335 		do {
336 			ret = tree_backref_for_extent(&ptr, eb, ei, item_size,
337 							&ref_root, &ref_level);
338 			printk(KERN_WARNING "%s at logical %llu on dev %s, "
339 				"sector %llu: metadata %s (level %d) in tree "
340 				"%llu\n", errstr, swarn.logical, dev->name,
341 				(unsigned long long)swarn.sector,
342 				ref_level ? "node" : "leaf",
343 				ret < 0 ? -1 : ref_level,
344 				ret < 0 ? -1 : ref_root);
345 		} while (ret != 1);
346 	} else {
347 		swarn.path = path;
348 		iterate_extent_inodes(fs_info, path, found_key.objectid,
349 					extent_offset,
350 					scrub_print_warning_inode, &swarn);
351 	}
352 
353 out:
354 	btrfs_free_path(path);
355 	kfree(swarn.scratch_buf);
356 	kfree(swarn.msg_buf);
357 }
358 
359 static int scrub_fixup_readpage(u64 inum, u64 offset, u64 root, void *ctx)
360 {
361 	struct page *page = NULL;
362 	unsigned long index;
363 	struct scrub_fixup_nodatasum *fixup = ctx;
364 	int ret;
365 	int corrected = 0;
366 	struct btrfs_key key;
367 	struct inode *inode = NULL;
368 	u64 end = offset + PAGE_SIZE - 1;
369 	struct btrfs_root *local_root;
370 
371 	key.objectid = root;
372 	key.type = BTRFS_ROOT_ITEM_KEY;
373 	key.offset = (u64)-1;
374 	local_root = btrfs_read_fs_root_no_name(fixup->root->fs_info, &key);
375 	if (IS_ERR(local_root))
376 		return PTR_ERR(local_root);
377 
378 	key.type = BTRFS_INODE_ITEM_KEY;
379 	key.objectid = inum;
380 	key.offset = 0;
381 	inode = btrfs_iget(fixup->root->fs_info->sb, &key, local_root, NULL);
382 	if (IS_ERR(inode))
383 		return PTR_ERR(inode);
384 
385 	index = offset >> PAGE_CACHE_SHIFT;
386 
387 	page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
388 	if (!page) {
389 		ret = -ENOMEM;
390 		goto out;
391 	}
392 
393 	if (PageUptodate(page)) {
394 		struct btrfs_mapping_tree *map_tree;
395 		if (PageDirty(page)) {
396 			/*
397 			 * we need to write the data to the defect sector. the
398 			 * data that was in that sector is not in memory,
399 			 * because the page was modified. we must not write the
400 			 * modified page to that sector.
401 			 *
402 			 * TODO: what could be done here: wait for the delalloc
403 			 *       runner to write out that page (might involve
404 			 *       COW) and see whether the sector is still
405 			 *       referenced afterwards.
406 			 *
407 			 * For the meantime, we'll treat this error
408 			 * incorrectable, although there is a chance that a
409 			 * later scrub will find the bad sector again and that
410 			 * there's no dirty page in memory, then.
411 			 */
412 			ret = -EIO;
413 			goto out;
414 		}
415 		map_tree = &BTRFS_I(inode)->root->fs_info->mapping_tree;
416 		ret = repair_io_failure(map_tree, offset, PAGE_SIZE,
417 					fixup->logical, page,
418 					fixup->mirror_num);
419 		unlock_page(page);
420 		corrected = !ret;
421 	} else {
422 		/*
423 		 * we need to get good data first. the general readpage path
424 		 * will call repair_io_failure for us, we just have to make
425 		 * sure we read the bad mirror.
426 		 */
427 		ret = set_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
428 					EXTENT_DAMAGED, GFP_NOFS);
429 		if (ret) {
430 			/* set_extent_bits should give proper error */
431 			WARN_ON(ret > 0);
432 			if (ret > 0)
433 				ret = -EFAULT;
434 			goto out;
435 		}
436 
437 		ret = extent_read_full_page(&BTRFS_I(inode)->io_tree, page,
438 						btrfs_get_extent,
439 						fixup->mirror_num);
440 		wait_on_page_locked(page);
441 
442 		corrected = !test_range_bit(&BTRFS_I(inode)->io_tree, offset,
443 						end, EXTENT_DAMAGED, 0, NULL);
444 		if (!corrected)
445 			clear_extent_bits(&BTRFS_I(inode)->io_tree, offset, end,
446 						EXTENT_DAMAGED, GFP_NOFS);
447 	}
448 
449 out:
450 	if (page)
451 		put_page(page);
452 	if (inode)
453 		iput(inode);
454 
455 	if (ret < 0)
456 		return ret;
457 
458 	if (ret == 0 && corrected) {
459 		/*
460 		 * we only need to call readpage for one of the inodes belonging
461 		 * to this extent. so make iterate_extent_inodes stop
462 		 */
463 		return 1;
464 	}
465 
466 	return -EIO;
467 }
468 
469 static void scrub_fixup_nodatasum(struct btrfs_work *work)
470 {
471 	int ret;
472 	struct scrub_fixup_nodatasum *fixup;
473 	struct scrub_dev *sdev;
474 	struct btrfs_trans_handle *trans = NULL;
475 	struct btrfs_fs_info *fs_info;
476 	struct btrfs_path *path;
477 	int uncorrectable = 0;
478 
479 	fixup = container_of(work, struct scrub_fixup_nodatasum, work);
480 	sdev = fixup->sdev;
481 	fs_info = fixup->root->fs_info;
482 
483 	path = btrfs_alloc_path();
484 	if (!path) {
485 		spin_lock(&sdev->stat_lock);
486 		++sdev->stat.malloc_errors;
487 		spin_unlock(&sdev->stat_lock);
488 		uncorrectable = 1;
489 		goto out;
490 	}
491 
492 	trans = btrfs_join_transaction(fixup->root);
493 	if (IS_ERR(trans)) {
494 		uncorrectable = 1;
495 		goto out;
496 	}
497 
498 	/*
499 	 * the idea is to trigger a regular read through the standard path. we
500 	 * read a page from the (failed) logical address by specifying the
501 	 * corresponding copynum of the failed sector. thus, that readpage is
502 	 * expected to fail.
503 	 * that is the point where on-the-fly error correction will kick in
504 	 * (once it's finished) and rewrite the failed sector if a good copy
505 	 * can be found.
506 	 */
507 	ret = iterate_inodes_from_logical(fixup->logical, fixup->root->fs_info,
508 						path, scrub_fixup_readpage,
509 						fixup);
510 	if (ret < 0) {
511 		uncorrectable = 1;
512 		goto out;
513 	}
514 	WARN_ON(ret != 1);
515 
516 	spin_lock(&sdev->stat_lock);
517 	++sdev->stat.corrected_errors;
518 	spin_unlock(&sdev->stat_lock);
519 
520 out:
521 	if (trans && !IS_ERR(trans))
522 		btrfs_end_transaction(trans, fixup->root);
523 	if (uncorrectable) {
524 		spin_lock(&sdev->stat_lock);
525 		++sdev->stat.uncorrectable_errors;
526 		spin_unlock(&sdev->stat_lock);
527 		printk_ratelimited(KERN_ERR "btrfs: unable to fixup "
528 					"(nodatasum) error at logical %llu\n",
529 					fixup->logical);
530 	}
531 
532 	btrfs_free_path(path);
533 	kfree(fixup);
534 
535 	/* see caller why we're pretending to be paused in the scrub counters */
536 	mutex_lock(&fs_info->scrub_lock);
537 	atomic_dec(&fs_info->scrubs_running);
538 	atomic_dec(&fs_info->scrubs_paused);
539 	mutex_unlock(&fs_info->scrub_lock);
540 	atomic_dec(&sdev->fixup_cnt);
541 	wake_up(&fs_info->scrub_pause_wait);
542 	wake_up(&sdev->list_wait);
543 }
544 
545 /*
546  * scrub_recheck_error gets called when either verification of the page
547  * failed or the bio failed to read, e.g. with EIO. In the latter case,
548  * recheck_error gets called for every page in the bio, even though only
549  * one may be bad
550  */
551 static int scrub_recheck_error(struct scrub_bio *sbio, int ix)
552 {
553 	struct scrub_dev *sdev = sbio->sdev;
554 	u64 sector = (sbio->physical + ix * PAGE_SIZE) >> 9;
555 	static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
556 					DEFAULT_RATELIMIT_BURST);
557 
558 	if (sbio->err) {
559 		if (scrub_fixup_io(READ, sbio->sdev->dev->bdev, sector,
560 				   sbio->bio->bi_io_vec[ix].bv_page) == 0) {
561 			if (scrub_fixup_check(sbio, ix) == 0)
562 				return 0;
563 		}
564 		if (__ratelimit(&_rs))
565 			scrub_print_warning("i/o error", sbio, ix);
566 	} else {
567 		if (__ratelimit(&_rs))
568 			scrub_print_warning("checksum error", sbio, ix);
569 	}
570 
571 	spin_lock(&sdev->stat_lock);
572 	++sdev->stat.read_errors;
573 	spin_unlock(&sdev->stat_lock);
574 
575 	scrub_fixup(sbio, ix);
576 	return 1;
577 }
578 
579 static int scrub_fixup_check(struct scrub_bio *sbio, int ix)
580 {
581 	int ret = 1;
582 	struct page *page;
583 	void *buffer;
584 	u64 flags = sbio->spag[ix].flags;
585 
586 	page = sbio->bio->bi_io_vec[ix].bv_page;
587 	buffer = kmap_atomic(page, KM_USER0);
588 	if (flags & BTRFS_EXTENT_FLAG_DATA) {
589 		ret = scrub_checksum_data(sbio->sdev,
590 					  sbio->spag + ix, buffer);
591 	} else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
592 		ret = scrub_checksum_tree_block(sbio->sdev,
593 						sbio->spag + ix,
594 						sbio->logical + ix * PAGE_SIZE,
595 						buffer);
596 	} else {
597 		WARN_ON(1);
598 	}
599 	kunmap_atomic(buffer, KM_USER0);
600 
601 	return ret;
602 }
603 
604 static void scrub_fixup_end_io(struct bio *bio, int err)
605 {
606 	complete((struct completion *)bio->bi_private);
607 }
608 
609 static void scrub_fixup(struct scrub_bio *sbio, int ix)
610 {
611 	struct scrub_dev *sdev = sbio->sdev;
612 	struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
613 	struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
614 	struct btrfs_bio *bbio = NULL;
615 	struct scrub_fixup_nodatasum *fixup;
616 	u64 logical = sbio->logical + ix * PAGE_SIZE;
617 	u64 length;
618 	int i;
619 	int ret;
620 	DECLARE_COMPLETION_ONSTACK(complete);
621 
622 	if ((sbio->spag[ix].flags & BTRFS_EXTENT_FLAG_DATA) &&
623 	    (sbio->spag[ix].have_csum == 0)) {
624 		fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
625 		if (!fixup)
626 			goto uncorrectable;
627 		fixup->sdev = sdev;
628 		fixup->logical = logical;
629 		fixup->root = fs_info->extent_root;
630 		fixup->mirror_num = sbio->spag[ix].mirror_num;
631 		/*
632 		 * increment scrubs_running to prevent cancel requests from
633 		 * completing as long as a fixup worker is running. we must also
634 		 * increment scrubs_paused to prevent deadlocking on pause
635 		 * requests used for transactions commits (as the worker uses a
636 		 * transaction context). it is safe to regard the fixup worker
637 		 * as paused for all matters practical. effectively, we only
638 		 * avoid cancellation requests from completing.
639 		 */
640 		mutex_lock(&fs_info->scrub_lock);
641 		atomic_inc(&fs_info->scrubs_running);
642 		atomic_inc(&fs_info->scrubs_paused);
643 		mutex_unlock(&fs_info->scrub_lock);
644 		atomic_inc(&sdev->fixup_cnt);
645 		fixup->work.func = scrub_fixup_nodatasum;
646 		btrfs_queue_worker(&fs_info->scrub_workers, &fixup->work);
647 		return;
648 	}
649 
650 	length = PAGE_SIZE;
651 	ret = btrfs_map_block(map_tree, REQ_WRITE, logical, &length,
652 			      &bbio, 0);
653 	if (ret || !bbio || length < PAGE_SIZE) {
654 		printk(KERN_ERR
655 		       "scrub_fixup: btrfs_map_block failed us for %llu\n",
656 		       (unsigned long long)logical);
657 		WARN_ON(1);
658 		kfree(bbio);
659 		return;
660 	}
661 
662 	if (bbio->num_stripes == 1)
663 		/* there aren't any replicas */
664 		goto uncorrectable;
665 
666 	/*
667 	 * first find a good copy
668 	 */
669 	for (i = 0; i < bbio->num_stripes; ++i) {
670 		if (i + 1 == sbio->spag[ix].mirror_num)
671 			continue;
672 
673 		if (scrub_fixup_io(READ, bbio->stripes[i].dev->bdev,
674 				   bbio->stripes[i].physical >> 9,
675 				   sbio->bio->bi_io_vec[ix].bv_page)) {
676 			/* I/O-error, this is not a good copy */
677 			continue;
678 		}
679 
680 		if (scrub_fixup_check(sbio, ix) == 0)
681 			break;
682 	}
683 	if (i == bbio->num_stripes)
684 		goto uncorrectable;
685 
686 	if (!sdev->readonly) {
687 		/*
688 		 * bi_io_vec[ix].bv_page now contains good data, write it back
689 		 */
690 		if (scrub_fixup_io(WRITE, sdev->dev->bdev,
691 				   (sbio->physical + ix * PAGE_SIZE) >> 9,
692 				   sbio->bio->bi_io_vec[ix].bv_page)) {
693 			/* I/O-error, writeback failed, give up */
694 			goto uncorrectable;
695 		}
696 	}
697 
698 	kfree(bbio);
699 	spin_lock(&sdev->stat_lock);
700 	++sdev->stat.corrected_errors;
701 	spin_unlock(&sdev->stat_lock);
702 
703 	printk_ratelimited(KERN_ERR "btrfs: fixed up error at logical %llu\n",
704 			       (unsigned long long)logical);
705 	return;
706 
707 uncorrectable:
708 	kfree(bbio);
709 	spin_lock(&sdev->stat_lock);
710 	++sdev->stat.uncorrectable_errors;
711 	spin_unlock(&sdev->stat_lock);
712 
713 	printk_ratelimited(KERN_ERR "btrfs: unable to fixup (regular) error at "
714 				"logical %llu\n", (unsigned long long)logical);
715 }
716 
717 static int scrub_fixup_io(int rw, struct block_device *bdev, sector_t sector,
718 			 struct page *page)
719 {
720 	struct bio *bio = NULL;
721 	int ret;
722 	DECLARE_COMPLETION_ONSTACK(complete);
723 
724 	bio = bio_alloc(GFP_NOFS, 1);
725 	bio->bi_bdev = bdev;
726 	bio->bi_sector = sector;
727 	bio_add_page(bio, page, PAGE_SIZE, 0);
728 	bio->bi_end_io = scrub_fixup_end_io;
729 	bio->bi_private = &complete;
730 	submit_bio(rw, bio);
731 
732 	/* this will also unplug the queue */
733 	wait_for_completion(&complete);
734 
735 	ret = !test_bit(BIO_UPTODATE, &bio->bi_flags);
736 	bio_put(bio);
737 	return ret;
738 }
739 
740 static void scrub_bio_end_io(struct bio *bio, int err)
741 {
742 	struct scrub_bio *sbio = bio->bi_private;
743 	struct scrub_dev *sdev = sbio->sdev;
744 	struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
745 
746 	sbio->err = err;
747 	sbio->bio = bio;
748 
749 	btrfs_queue_worker(&fs_info->scrub_workers, &sbio->work);
750 }
751 
752 static void scrub_checksum(struct btrfs_work *work)
753 {
754 	struct scrub_bio *sbio = container_of(work, struct scrub_bio, work);
755 	struct scrub_dev *sdev = sbio->sdev;
756 	struct page *page;
757 	void *buffer;
758 	int i;
759 	u64 flags;
760 	u64 logical;
761 	int ret;
762 
763 	if (sbio->err) {
764 		ret = 0;
765 		for (i = 0; i < sbio->count; ++i)
766 			ret |= scrub_recheck_error(sbio, i);
767 		if (!ret) {
768 			spin_lock(&sdev->stat_lock);
769 			++sdev->stat.unverified_errors;
770 			spin_unlock(&sdev->stat_lock);
771 		}
772 
773 		sbio->bio->bi_flags &= ~(BIO_POOL_MASK - 1);
774 		sbio->bio->bi_flags |= 1 << BIO_UPTODATE;
775 		sbio->bio->bi_phys_segments = 0;
776 		sbio->bio->bi_idx = 0;
777 
778 		for (i = 0; i < sbio->count; i++) {
779 			struct bio_vec *bi;
780 			bi = &sbio->bio->bi_io_vec[i];
781 			bi->bv_offset = 0;
782 			bi->bv_len = PAGE_SIZE;
783 		}
784 		goto out;
785 	}
786 	for (i = 0; i < sbio->count; ++i) {
787 		page = sbio->bio->bi_io_vec[i].bv_page;
788 		buffer = kmap_atomic(page, KM_USER0);
789 		flags = sbio->spag[i].flags;
790 		logical = sbio->logical + i * PAGE_SIZE;
791 		ret = 0;
792 		if (flags & BTRFS_EXTENT_FLAG_DATA) {
793 			ret = scrub_checksum_data(sdev, sbio->spag + i, buffer);
794 		} else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
795 			ret = scrub_checksum_tree_block(sdev, sbio->spag + i,
796 							logical, buffer);
797 		} else if (flags & BTRFS_EXTENT_FLAG_SUPER) {
798 			BUG_ON(i);
799 			(void)scrub_checksum_super(sbio, buffer);
800 		} else {
801 			WARN_ON(1);
802 		}
803 		kunmap_atomic(buffer, KM_USER0);
804 		if (ret) {
805 			ret = scrub_recheck_error(sbio, i);
806 			if (!ret) {
807 				spin_lock(&sdev->stat_lock);
808 				++sdev->stat.unverified_errors;
809 				spin_unlock(&sdev->stat_lock);
810 			}
811 		}
812 	}
813 
814 out:
815 	scrub_free_bio(sbio->bio);
816 	sbio->bio = NULL;
817 	spin_lock(&sdev->list_lock);
818 	sbio->next_free = sdev->first_free;
819 	sdev->first_free = sbio->index;
820 	spin_unlock(&sdev->list_lock);
821 	atomic_dec(&sdev->in_flight);
822 	wake_up(&sdev->list_wait);
823 }
824 
825 static int scrub_checksum_data(struct scrub_dev *sdev,
826 			       struct scrub_page *spag, void *buffer)
827 {
828 	u8 csum[BTRFS_CSUM_SIZE];
829 	u32 crc = ~(u32)0;
830 	int fail = 0;
831 	struct btrfs_root *root = sdev->dev->dev_root;
832 
833 	if (!spag->have_csum)
834 		return 0;
835 
836 	crc = btrfs_csum_data(root, buffer, crc, PAGE_SIZE);
837 	btrfs_csum_final(crc, csum);
838 	if (memcmp(csum, spag->csum, sdev->csum_size))
839 		fail = 1;
840 
841 	spin_lock(&sdev->stat_lock);
842 	++sdev->stat.data_extents_scrubbed;
843 	sdev->stat.data_bytes_scrubbed += PAGE_SIZE;
844 	if (fail)
845 		++sdev->stat.csum_errors;
846 	spin_unlock(&sdev->stat_lock);
847 
848 	return fail;
849 }
850 
851 static int scrub_checksum_tree_block(struct scrub_dev *sdev,
852 				     struct scrub_page *spag, u64 logical,
853 				     void *buffer)
854 {
855 	struct btrfs_header *h;
856 	struct btrfs_root *root = sdev->dev->dev_root;
857 	struct btrfs_fs_info *fs_info = root->fs_info;
858 	u8 csum[BTRFS_CSUM_SIZE];
859 	u32 crc = ~(u32)0;
860 	int fail = 0;
861 	int crc_fail = 0;
862 
863 	/*
864 	 * we don't use the getter functions here, as we
865 	 * a) don't have an extent buffer and
866 	 * b) the page is already kmapped
867 	 */
868 	h = (struct btrfs_header *)buffer;
869 
870 	if (logical != le64_to_cpu(h->bytenr))
871 		++fail;
872 
873 	if (spag->generation != le64_to_cpu(h->generation))
874 		++fail;
875 
876 	if (memcmp(h->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
877 		++fail;
878 
879 	if (memcmp(h->chunk_tree_uuid, fs_info->chunk_tree_uuid,
880 		   BTRFS_UUID_SIZE))
881 		++fail;
882 
883 	crc = btrfs_csum_data(root, buffer + BTRFS_CSUM_SIZE, crc,
884 			      PAGE_SIZE - BTRFS_CSUM_SIZE);
885 	btrfs_csum_final(crc, csum);
886 	if (memcmp(csum, h->csum, sdev->csum_size))
887 		++crc_fail;
888 
889 	spin_lock(&sdev->stat_lock);
890 	++sdev->stat.tree_extents_scrubbed;
891 	sdev->stat.tree_bytes_scrubbed += PAGE_SIZE;
892 	if (crc_fail)
893 		++sdev->stat.csum_errors;
894 	if (fail)
895 		++sdev->stat.verify_errors;
896 	spin_unlock(&sdev->stat_lock);
897 
898 	return fail || crc_fail;
899 }
900 
901 static int scrub_checksum_super(struct scrub_bio *sbio, void *buffer)
902 {
903 	struct btrfs_super_block *s;
904 	u64 logical;
905 	struct scrub_dev *sdev = sbio->sdev;
906 	struct btrfs_root *root = sdev->dev->dev_root;
907 	struct btrfs_fs_info *fs_info = root->fs_info;
908 	u8 csum[BTRFS_CSUM_SIZE];
909 	u32 crc = ~(u32)0;
910 	int fail = 0;
911 
912 	s = (struct btrfs_super_block *)buffer;
913 	logical = sbio->logical;
914 
915 	if (logical != le64_to_cpu(s->bytenr))
916 		++fail;
917 
918 	if (sbio->spag[0].generation != le64_to_cpu(s->generation))
919 		++fail;
920 
921 	if (memcmp(s->fsid, fs_info->fsid, BTRFS_UUID_SIZE))
922 		++fail;
923 
924 	crc = btrfs_csum_data(root, buffer + BTRFS_CSUM_SIZE, crc,
925 			      PAGE_SIZE - BTRFS_CSUM_SIZE);
926 	btrfs_csum_final(crc, csum);
927 	if (memcmp(csum, s->csum, sbio->sdev->csum_size))
928 		++fail;
929 
930 	if (fail) {
931 		/*
932 		 * if we find an error in a super block, we just report it.
933 		 * They will get written with the next transaction commit
934 		 * anyway
935 		 */
936 		spin_lock(&sdev->stat_lock);
937 		++sdev->stat.super_errors;
938 		spin_unlock(&sdev->stat_lock);
939 	}
940 
941 	return fail;
942 }
943 
944 static int scrub_submit(struct scrub_dev *sdev)
945 {
946 	struct scrub_bio *sbio;
947 	struct bio *bio;
948 	int i;
949 
950 	if (sdev->curr == -1)
951 		return 0;
952 
953 	sbio = sdev->bios[sdev->curr];
954 
955 	bio = bio_alloc(GFP_NOFS, sbio->count);
956 	if (!bio)
957 		goto nomem;
958 
959 	bio->bi_private = sbio;
960 	bio->bi_end_io = scrub_bio_end_io;
961 	bio->bi_bdev = sdev->dev->bdev;
962 	bio->bi_sector = sbio->physical >> 9;
963 
964 	for (i = 0; i < sbio->count; ++i) {
965 		struct page *page;
966 		int ret;
967 
968 		page = alloc_page(GFP_NOFS);
969 		if (!page)
970 			goto nomem;
971 
972 		ret = bio_add_page(bio, page, PAGE_SIZE, 0);
973 		if (!ret) {
974 			__free_page(page);
975 			goto nomem;
976 		}
977 	}
978 
979 	sbio->err = 0;
980 	sdev->curr = -1;
981 	atomic_inc(&sdev->in_flight);
982 
983 	submit_bio(READ, bio);
984 
985 	return 0;
986 
987 nomem:
988 	scrub_free_bio(bio);
989 
990 	return -ENOMEM;
991 }
992 
993 static int scrub_page(struct scrub_dev *sdev, u64 logical, u64 len,
994 		      u64 physical, u64 flags, u64 gen, int mirror_num,
995 		      u8 *csum, int force)
996 {
997 	struct scrub_bio *sbio;
998 
999 again:
1000 	/*
1001 	 * grab a fresh bio or wait for one to become available
1002 	 */
1003 	while (sdev->curr == -1) {
1004 		spin_lock(&sdev->list_lock);
1005 		sdev->curr = sdev->first_free;
1006 		if (sdev->curr != -1) {
1007 			sdev->first_free = sdev->bios[sdev->curr]->next_free;
1008 			sdev->bios[sdev->curr]->next_free = -1;
1009 			sdev->bios[sdev->curr]->count = 0;
1010 			spin_unlock(&sdev->list_lock);
1011 		} else {
1012 			spin_unlock(&sdev->list_lock);
1013 			wait_event(sdev->list_wait, sdev->first_free != -1);
1014 		}
1015 	}
1016 	sbio = sdev->bios[sdev->curr];
1017 	if (sbio->count == 0) {
1018 		sbio->physical = physical;
1019 		sbio->logical = logical;
1020 	} else if (sbio->physical + sbio->count * PAGE_SIZE != physical ||
1021 		   sbio->logical + sbio->count * PAGE_SIZE != logical) {
1022 		int ret;
1023 
1024 		ret = scrub_submit(sdev);
1025 		if (ret)
1026 			return ret;
1027 		goto again;
1028 	}
1029 	sbio->spag[sbio->count].flags = flags;
1030 	sbio->spag[sbio->count].generation = gen;
1031 	sbio->spag[sbio->count].have_csum = 0;
1032 	sbio->spag[sbio->count].mirror_num = mirror_num;
1033 	if (csum) {
1034 		sbio->spag[sbio->count].have_csum = 1;
1035 		memcpy(sbio->spag[sbio->count].csum, csum, sdev->csum_size);
1036 	}
1037 	++sbio->count;
1038 	if (sbio->count == SCRUB_PAGES_PER_BIO || force) {
1039 		int ret;
1040 
1041 		ret = scrub_submit(sdev);
1042 		if (ret)
1043 			return ret;
1044 	}
1045 
1046 	return 0;
1047 }
1048 
1049 static int scrub_find_csum(struct scrub_dev *sdev, u64 logical, u64 len,
1050 			   u8 *csum)
1051 {
1052 	struct btrfs_ordered_sum *sum = NULL;
1053 	int ret = 0;
1054 	unsigned long i;
1055 	unsigned long num_sectors;
1056 	u32 sectorsize = sdev->dev->dev_root->sectorsize;
1057 
1058 	while (!list_empty(&sdev->csum_list)) {
1059 		sum = list_first_entry(&sdev->csum_list,
1060 				       struct btrfs_ordered_sum, list);
1061 		if (sum->bytenr > logical)
1062 			return 0;
1063 		if (sum->bytenr + sum->len > logical)
1064 			break;
1065 
1066 		++sdev->stat.csum_discards;
1067 		list_del(&sum->list);
1068 		kfree(sum);
1069 		sum = NULL;
1070 	}
1071 	if (!sum)
1072 		return 0;
1073 
1074 	num_sectors = sum->len / sectorsize;
1075 	for (i = 0; i < num_sectors; ++i) {
1076 		if (sum->sums[i].bytenr == logical) {
1077 			memcpy(csum, &sum->sums[i].sum, sdev->csum_size);
1078 			ret = 1;
1079 			break;
1080 		}
1081 	}
1082 	if (ret && i == num_sectors - 1) {
1083 		list_del(&sum->list);
1084 		kfree(sum);
1085 	}
1086 	return ret;
1087 }
1088 
1089 /* scrub extent tries to collect up to 64 kB for each bio */
1090 static int scrub_extent(struct scrub_dev *sdev, u64 logical, u64 len,
1091 			u64 physical, u64 flags, u64 gen, int mirror_num)
1092 {
1093 	int ret;
1094 	u8 csum[BTRFS_CSUM_SIZE];
1095 
1096 	while (len) {
1097 		u64 l = min_t(u64, len, PAGE_SIZE);
1098 		int have_csum = 0;
1099 
1100 		if (flags & BTRFS_EXTENT_FLAG_DATA) {
1101 			/* push csums to sbio */
1102 			have_csum = scrub_find_csum(sdev, logical, l, csum);
1103 			if (have_csum == 0)
1104 				++sdev->stat.no_csum;
1105 		}
1106 		ret = scrub_page(sdev, logical, l, physical, flags, gen,
1107 				 mirror_num, have_csum ? csum : NULL, 0);
1108 		if (ret)
1109 			return ret;
1110 		len -= l;
1111 		logical += l;
1112 		physical += l;
1113 	}
1114 	return 0;
1115 }
1116 
1117 static noinline_for_stack int scrub_stripe(struct scrub_dev *sdev,
1118 	struct map_lookup *map, int num, u64 base, u64 length)
1119 {
1120 	struct btrfs_path *path;
1121 	struct btrfs_fs_info *fs_info = sdev->dev->dev_root->fs_info;
1122 	struct btrfs_root *root = fs_info->extent_root;
1123 	struct btrfs_root *csum_root = fs_info->csum_root;
1124 	struct btrfs_extent_item *extent;
1125 	struct blk_plug plug;
1126 	u64 flags;
1127 	int ret;
1128 	int slot;
1129 	int i;
1130 	u64 nstripes;
1131 	struct extent_buffer *l;
1132 	struct btrfs_key key;
1133 	u64 physical;
1134 	u64 logical;
1135 	u64 generation;
1136 	int mirror_num;
1137 	struct reada_control *reada1;
1138 	struct reada_control *reada2;
1139 	struct btrfs_key key_start;
1140 	struct btrfs_key key_end;
1141 
1142 	u64 increment = map->stripe_len;
1143 	u64 offset;
1144 
1145 	nstripes = length;
1146 	offset = 0;
1147 	do_div(nstripes, map->stripe_len);
1148 	if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1149 		offset = map->stripe_len * num;
1150 		increment = map->stripe_len * map->num_stripes;
1151 		mirror_num = 1;
1152 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1153 		int factor = map->num_stripes / map->sub_stripes;
1154 		offset = map->stripe_len * (num / map->sub_stripes);
1155 		increment = map->stripe_len * factor;
1156 		mirror_num = num % map->sub_stripes + 1;
1157 	} else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
1158 		increment = map->stripe_len;
1159 		mirror_num = num % map->num_stripes + 1;
1160 	} else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
1161 		increment = map->stripe_len;
1162 		mirror_num = num % map->num_stripes + 1;
1163 	} else {
1164 		increment = map->stripe_len;
1165 		mirror_num = 1;
1166 	}
1167 
1168 	path = btrfs_alloc_path();
1169 	if (!path)
1170 		return -ENOMEM;
1171 
1172 	path->search_commit_root = 1;
1173 	path->skip_locking = 1;
1174 
1175 	/*
1176 	 * trigger the readahead for extent tree csum tree and wait for
1177 	 * completion. During readahead, the scrub is officially paused
1178 	 * to not hold off transaction commits
1179 	 */
1180 	logical = base + offset;
1181 
1182 	wait_event(sdev->list_wait,
1183 		   atomic_read(&sdev->in_flight) == 0);
1184 	atomic_inc(&fs_info->scrubs_paused);
1185 	wake_up(&fs_info->scrub_pause_wait);
1186 
1187 	/* FIXME it might be better to start readahead at commit root */
1188 	key_start.objectid = logical;
1189 	key_start.type = BTRFS_EXTENT_ITEM_KEY;
1190 	key_start.offset = (u64)0;
1191 	key_end.objectid = base + offset + nstripes * increment;
1192 	key_end.type = BTRFS_EXTENT_ITEM_KEY;
1193 	key_end.offset = (u64)0;
1194 	reada1 = btrfs_reada_add(root, &key_start, &key_end);
1195 
1196 	key_start.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1197 	key_start.type = BTRFS_EXTENT_CSUM_KEY;
1198 	key_start.offset = logical;
1199 	key_end.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1200 	key_end.type = BTRFS_EXTENT_CSUM_KEY;
1201 	key_end.offset = base + offset + nstripes * increment;
1202 	reada2 = btrfs_reada_add(csum_root, &key_start, &key_end);
1203 
1204 	if (!IS_ERR(reada1))
1205 		btrfs_reada_wait(reada1);
1206 	if (!IS_ERR(reada2))
1207 		btrfs_reada_wait(reada2);
1208 
1209 	mutex_lock(&fs_info->scrub_lock);
1210 	while (atomic_read(&fs_info->scrub_pause_req)) {
1211 		mutex_unlock(&fs_info->scrub_lock);
1212 		wait_event(fs_info->scrub_pause_wait,
1213 		   atomic_read(&fs_info->scrub_pause_req) == 0);
1214 		mutex_lock(&fs_info->scrub_lock);
1215 	}
1216 	atomic_dec(&fs_info->scrubs_paused);
1217 	mutex_unlock(&fs_info->scrub_lock);
1218 	wake_up(&fs_info->scrub_pause_wait);
1219 
1220 	/*
1221 	 * collect all data csums for the stripe to avoid seeking during
1222 	 * the scrub. This might currently (crc32) end up to be about 1MB
1223 	 */
1224 	blk_start_plug(&plug);
1225 
1226 	/*
1227 	 * now find all extents for each stripe and scrub them
1228 	 */
1229 	logical = base + offset;
1230 	physical = map->stripes[num].physical;
1231 	ret = 0;
1232 	for (i = 0; i < nstripes; ++i) {
1233 		/*
1234 		 * canceled?
1235 		 */
1236 		if (atomic_read(&fs_info->scrub_cancel_req) ||
1237 		    atomic_read(&sdev->cancel_req)) {
1238 			ret = -ECANCELED;
1239 			goto out;
1240 		}
1241 		/*
1242 		 * check to see if we have to pause
1243 		 */
1244 		if (atomic_read(&fs_info->scrub_pause_req)) {
1245 			/* push queued extents */
1246 			scrub_submit(sdev);
1247 			wait_event(sdev->list_wait,
1248 				   atomic_read(&sdev->in_flight) == 0);
1249 			atomic_inc(&fs_info->scrubs_paused);
1250 			wake_up(&fs_info->scrub_pause_wait);
1251 			mutex_lock(&fs_info->scrub_lock);
1252 			while (atomic_read(&fs_info->scrub_pause_req)) {
1253 				mutex_unlock(&fs_info->scrub_lock);
1254 				wait_event(fs_info->scrub_pause_wait,
1255 				   atomic_read(&fs_info->scrub_pause_req) == 0);
1256 				mutex_lock(&fs_info->scrub_lock);
1257 			}
1258 			atomic_dec(&fs_info->scrubs_paused);
1259 			mutex_unlock(&fs_info->scrub_lock);
1260 			wake_up(&fs_info->scrub_pause_wait);
1261 		}
1262 
1263 		ret = btrfs_lookup_csums_range(csum_root, logical,
1264 					       logical + map->stripe_len - 1,
1265 					       &sdev->csum_list, 1);
1266 		if (ret)
1267 			goto out;
1268 
1269 		key.objectid = logical;
1270 		key.type = BTRFS_EXTENT_ITEM_KEY;
1271 		key.offset = (u64)0;
1272 
1273 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1274 		if (ret < 0)
1275 			goto out;
1276 		if (ret > 0) {
1277 			ret = btrfs_previous_item(root, path, 0,
1278 						  BTRFS_EXTENT_ITEM_KEY);
1279 			if (ret < 0)
1280 				goto out;
1281 			if (ret > 0) {
1282 				/* there's no smaller item, so stick with the
1283 				 * larger one */
1284 				btrfs_release_path(path);
1285 				ret = btrfs_search_slot(NULL, root, &key,
1286 							path, 0, 0);
1287 				if (ret < 0)
1288 					goto out;
1289 			}
1290 		}
1291 
1292 		while (1) {
1293 			l = path->nodes[0];
1294 			slot = path->slots[0];
1295 			if (slot >= btrfs_header_nritems(l)) {
1296 				ret = btrfs_next_leaf(root, path);
1297 				if (ret == 0)
1298 					continue;
1299 				if (ret < 0)
1300 					goto out;
1301 
1302 				break;
1303 			}
1304 			btrfs_item_key_to_cpu(l, &key, slot);
1305 
1306 			if (key.objectid + key.offset <= logical)
1307 				goto next;
1308 
1309 			if (key.objectid >= logical + map->stripe_len)
1310 				break;
1311 
1312 			if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY)
1313 				goto next;
1314 
1315 			extent = btrfs_item_ptr(l, slot,
1316 						struct btrfs_extent_item);
1317 			flags = btrfs_extent_flags(l, extent);
1318 			generation = btrfs_extent_generation(l, extent);
1319 
1320 			if (key.objectid < logical &&
1321 			    (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
1322 				printk(KERN_ERR
1323 				       "btrfs scrub: tree block %llu spanning "
1324 				       "stripes, ignored. logical=%llu\n",
1325 				       (unsigned long long)key.objectid,
1326 				       (unsigned long long)logical);
1327 				goto next;
1328 			}
1329 
1330 			/*
1331 			 * trim extent to this stripe
1332 			 */
1333 			if (key.objectid < logical) {
1334 				key.offset -= logical - key.objectid;
1335 				key.objectid = logical;
1336 			}
1337 			if (key.objectid + key.offset >
1338 			    logical + map->stripe_len) {
1339 				key.offset = logical + map->stripe_len -
1340 					     key.objectid;
1341 			}
1342 
1343 			ret = scrub_extent(sdev, key.objectid, key.offset,
1344 					   key.objectid - logical + physical,
1345 					   flags, generation, mirror_num);
1346 			if (ret)
1347 				goto out;
1348 
1349 next:
1350 			path->slots[0]++;
1351 		}
1352 		btrfs_release_path(path);
1353 		logical += increment;
1354 		physical += map->stripe_len;
1355 		spin_lock(&sdev->stat_lock);
1356 		sdev->stat.last_physical = physical;
1357 		spin_unlock(&sdev->stat_lock);
1358 	}
1359 	/* push queued extents */
1360 	scrub_submit(sdev);
1361 
1362 out:
1363 	blk_finish_plug(&plug);
1364 	btrfs_free_path(path);
1365 	return ret < 0 ? ret : 0;
1366 }
1367 
1368 static noinline_for_stack int scrub_chunk(struct scrub_dev *sdev,
1369 	u64 chunk_tree, u64 chunk_objectid, u64 chunk_offset, u64 length)
1370 {
1371 	struct btrfs_mapping_tree *map_tree =
1372 		&sdev->dev->dev_root->fs_info->mapping_tree;
1373 	struct map_lookup *map;
1374 	struct extent_map *em;
1375 	int i;
1376 	int ret = -EINVAL;
1377 
1378 	read_lock(&map_tree->map_tree.lock);
1379 	em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
1380 	read_unlock(&map_tree->map_tree.lock);
1381 
1382 	if (!em)
1383 		return -EINVAL;
1384 
1385 	map = (struct map_lookup *)em->bdev;
1386 	if (em->start != chunk_offset)
1387 		goto out;
1388 
1389 	if (em->len < length)
1390 		goto out;
1391 
1392 	for (i = 0; i < map->num_stripes; ++i) {
1393 		if (map->stripes[i].dev == sdev->dev) {
1394 			ret = scrub_stripe(sdev, map, i, chunk_offset, length);
1395 			if (ret)
1396 				goto out;
1397 		}
1398 	}
1399 out:
1400 	free_extent_map(em);
1401 
1402 	return ret;
1403 }
1404 
1405 static noinline_for_stack
1406 int scrub_enumerate_chunks(struct scrub_dev *sdev, u64 start, u64 end)
1407 {
1408 	struct btrfs_dev_extent *dev_extent = NULL;
1409 	struct btrfs_path *path;
1410 	struct btrfs_root *root = sdev->dev->dev_root;
1411 	struct btrfs_fs_info *fs_info = root->fs_info;
1412 	u64 length;
1413 	u64 chunk_tree;
1414 	u64 chunk_objectid;
1415 	u64 chunk_offset;
1416 	int ret;
1417 	int slot;
1418 	struct extent_buffer *l;
1419 	struct btrfs_key key;
1420 	struct btrfs_key found_key;
1421 	struct btrfs_block_group_cache *cache;
1422 
1423 	path = btrfs_alloc_path();
1424 	if (!path)
1425 		return -ENOMEM;
1426 
1427 	path->reada = 2;
1428 	path->search_commit_root = 1;
1429 	path->skip_locking = 1;
1430 
1431 	key.objectid = sdev->dev->devid;
1432 	key.offset = 0ull;
1433 	key.type = BTRFS_DEV_EXTENT_KEY;
1434 
1435 
1436 	while (1) {
1437 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1438 		if (ret < 0)
1439 			break;
1440 		if (ret > 0) {
1441 			if (path->slots[0] >=
1442 			    btrfs_header_nritems(path->nodes[0])) {
1443 				ret = btrfs_next_leaf(root, path);
1444 				if (ret)
1445 					break;
1446 			}
1447 		}
1448 
1449 		l = path->nodes[0];
1450 		slot = path->slots[0];
1451 
1452 		btrfs_item_key_to_cpu(l, &found_key, slot);
1453 
1454 		if (found_key.objectid != sdev->dev->devid)
1455 			break;
1456 
1457 		if (btrfs_key_type(&found_key) != BTRFS_DEV_EXTENT_KEY)
1458 			break;
1459 
1460 		if (found_key.offset >= end)
1461 			break;
1462 
1463 		if (found_key.offset < key.offset)
1464 			break;
1465 
1466 		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1467 		length = btrfs_dev_extent_length(l, dev_extent);
1468 
1469 		if (found_key.offset + length <= start) {
1470 			key.offset = found_key.offset + length;
1471 			btrfs_release_path(path);
1472 			continue;
1473 		}
1474 
1475 		chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
1476 		chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
1477 		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
1478 
1479 		/*
1480 		 * get a reference on the corresponding block group to prevent
1481 		 * the chunk from going away while we scrub it
1482 		 */
1483 		cache = btrfs_lookup_block_group(fs_info, chunk_offset);
1484 		if (!cache) {
1485 			ret = -ENOENT;
1486 			break;
1487 		}
1488 		ret = scrub_chunk(sdev, chunk_tree, chunk_objectid,
1489 				  chunk_offset, length);
1490 		btrfs_put_block_group(cache);
1491 		if (ret)
1492 			break;
1493 
1494 		key.offset = found_key.offset + length;
1495 		btrfs_release_path(path);
1496 	}
1497 
1498 	btrfs_free_path(path);
1499 
1500 	/*
1501 	 * ret can still be 1 from search_slot or next_leaf,
1502 	 * that's not an error
1503 	 */
1504 	return ret < 0 ? ret : 0;
1505 }
1506 
1507 static noinline_for_stack int scrub_supers(struct scrub_dev *sdev)
1508 {
1509 	int	i;
1510 	u64	bytenr;
1511 	u64	gen;
1512 	int	ret;
1513 	struct btrfs_device *device = sdev->dev;
1514 	struct btrfs_root *root = device->dev_root;
1515 
1516 	gen = root->fs_info->last_trans_committed;
1517 
1518 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1519 		bytenr = btrfs_sb_offset(i);
1520 		if (bytenr + BTRFS_SUPER_INFO_SIZE >= device->total_bytes)
1521 			break;
1522 
1523 		ret = scrub_page(sdev, bytenr, PAGE_SIZE, bytenr,
1524 				 BTRFS_EXTENT_FLAG_SUPER, gen, i, NULL, 1);
1525 		if (ret)
1526 			return ret;
1527 	}
1528 	wait_event(sdev->list_wait, atomic_read(&sdev->in_flight) == 0);
1529 
1530 	return 0;
1531 }
1532 
1533 /*
1534  * get a reference count on fs_info->scrub_workers. start worker if necessary
1535  */
1536 static noinline_for_stack int scrub_workers_get(struct btrfs_root *root)
1537 {
1538 	struct btrfs_fs_info *fs_info = root->fs_info;
1539 
1540 	mutex_lock(&fs_info->scrub_lock);
1541 	if (fs_info->scrub_workers_refcnt == 0) {
1542 		btrfs_init_workers(&fs_info->scrub_workers, "scrub",
1543 			   fs_info->thread_pool_size, &fs_info->generic_worker);
1544 		fs_info->scrub_workers.idle_thresh = 4;
1545 		btrfs_start_workers(&fs_info->scrub_workers, 1);
1546 	}
1547 	++fs_info->scrub_workers_refcnt;
1548 	mutex_unlock(&fs_info->scrub_lock);
1549 
1550 	return 0;
1551 }
1552 
1553 static noinline_for_stack void scrub_workers_put(struct btrfs_root *root)
1554 {
1555 	struct btrfs_fs_info *fs_info = root->fs_info;
1556 
1557 	mutex_lock(&fs_info->scrub_lock);
1558 	if (--fs_info->scrub_workers_refcnt == 0)
1559 		btrfs_stop_workers(&fs_info->scrub_workers);
1560 	WARN_ON(fs_info->scrub_workers_refcnt < 0);
1561 	mutex_unlock(&fs_info->scrub_lock);
1562 }
1563 
1564 
1565 int btrfs_scrub_dev(struct btrfs_root *root, u64 devid, u64 start, u64 end,
1566 		    struct btrfs_scrub_progress *progress, int readonly)
1567 {
1568 	struct scrub_dev *sdev;
1569 	struct btrfs_fs_info *fs_info = root->fs_info;
1570 	int ret;
1571 	struct btrfs_device *dev;
1572 
1573 	if (btrfs_fs_closing(root->fs_info))
1574 		return -EINVAL;
1575 
1576 	/*
1577 	 * check some assumptions
1578 	 */
1579 	if (root->sectorsize != PAGE_SIZE ||
1580 	    root->sectorsize != root->leafsize ||
1581 	    root->sectorsize != root->nodesize) {
1582 		printk(KERN_ERR "btrfs_scrub: size assumptions fail\n");
1583 		return -EINVAL;
1584 	}
1585 
1586 	ret = scrub_workers_get(root);
1587 	if (ret)
1588 		return ret;
1589 
1590 	mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1591 	dev = btrfs_find_device(root, devid, NULL, NULL);
1592 	if (!dev || dev->missing) {
1593 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1594 		scrub_workers_put(root);
1595 		return -ENODEV;
1596 	}
1597 	mutex_lock(&fs_info->scrub_lock);
1598 
1599 	if (!dev->in_fs_metadata) {
1600 		mutex_unlock(&fs_info->scrub_lock);
1601 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1602 		scrub_workers_put(root);
1603 		return -ENODEV;
1604 	}
1605 
1606 	if (dev->scrub_device) {
1607 		mutex_unlock(&fs_info->scrub_lock);
1608 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1609 		scrub_workers_put(root);
1610 		return -EINPROGRESS;
1611 	}
1612 	sdev = scrub_setup_dev(dev);
1613 	if (IS_ERR(sdev)) {
1614 		mutex_unlock(&fs_info->scrub_lock);
1615 		mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1616 		scrub_workers_put(root);
1617 		return PTR_ERR(sdev);
1618 	}
1619 	sdev->readonly = readonly;
1620 	dev->scrub_device = sdev;
1621 
1622 	atomic_inc(&fs_info->scrubs_running);
1623 	mutex_unlock(&fs_info->scrub_lock);
1624 	mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1625 
1626 	down_read(&fs_info->scrub_super_lock);
1627 	ret = scrub_supers(sdev);
1628 	up_read(&fs_info->scrub_super_lock);
1629 
1630 	if (!ret)
1631 		ret = scrub_enumerate_chunks(sdev, start, end);
1632 
1633 	wait_event(sdev->list_wait, atomic_read(&sdev->in_flight) == 0);
1634 	atomic_dec(&fs_info->scrubs_running);
1635 	wake_up(&fs_info->scrub_pause_wait);
1636 
1637 	wait_event(sdev->list_wait, atomic_read(&sdev->fixup_cnt) == 0);
1638 
1639 	if (progress)
1640 		memcpy(progress, &sdev->stat, sizeof(*progress));
1641 
1642 	mutex_lock(&fs_info->scrub_lock);
1643 	dev->scrub_device = NULL;
1644 	mutex_unlock(&fs_info->scrub_lock);
1645 
1646 	scrub_free_dev(sdev);
1647 	scrub_workers_put(root);
1648 
1649 	return ret;
1650 }
1651 
1652 int btrfs_scrub_pause(struct btrfs_root *root)
1653 {
1654 	struct btrfs_fs_info *fs_info = root->fs_info;
1655 
1656 	mutex_lock(&fs_info->scrub_lock);
1657 	atomic_inc(&fs_info->scrub_pause_req);
1658 	while (atomic_read(&fs_info->scrubs_paused) !=
1659 	       atomic_read(&fs_info->scrubs_running)) {
1660 		mutex_unlock(&fs_info->scrub_lock);
1661 		wait_event(fs_info->scrub_pause_wait,
1662 			   atomic_read(&fs_info->scrubs_paused) ==
1663 			   atomic_read(&fs_info->scrubs_running));
1664 		mutex_lock(&fs_info->scrub_lock);
1665 	}
1666 	mutex_unlock(&fs_info->scrub_lock);
1667 
1668 	return 0;
1669 }
1670 
1671 int btrfs_scrub_continue(struct btrfs_root *root)
1672 {
1673 	struct btrfs_fs_info *fs_info = root->fs_info;
1674 
1675 	atomic_dec(&fs_info->scrub_pause_req);
1676 	wake_up(&fs_info->scrub_pause_wait);
1677 	return 0;
1678 }
1679 
1680 int btrfs_scrub_pause_super(struct btrfs_root *root)
1681 {
1682 	down_write(&root->fs_info->scrub_super_lock);
1683 	return 0;
1684 }
1685 
1686 int btrfs_scrub_continue_super(struct btrfs_root *root)
1687 {
1688 	up_write(&root->fs_info->scrub_super_lock);
1689 	return 0;
1690 }
1691 
1692 int btrfs_scrub_cancel(struct btrfs_root *root)
1693 {
1694 	struct btrfs_fs_info *fs_info = root->fs_info;
1695 
1696 	mutex_lock(&fs_info->scrub_lock);
1697 	if (!atomic_read(&fs_info->scrubs_running)) {
1698 		mutex_unlock(&fs_info->scrub_lock);
1699 		return -ENOTCONN;
1700 	}
1701 
1702 	atomic_inc(&fs_info->scrub_cancel_req);
1703 	while (atomic_read(&fs_info->scrubs_running)) {
1704 		mutex_unlock(&fs_info->scrub_lock);
1705 		wait_event(fs_info->scrub_pause_wait,
1706 			   atomic_read(&fs_info->scrubs_running) == 0);
1707 		mutex_lock(&fs_info->scrub_lock);
1708 	}
1709 	atomic_dec(&fs_info->scrub_cancel_req);
1710 	mutex_unlock(&fs_info->scrub_lock);
1711 
1712 	return 0;
1713 }
1714 
1715 int btrfs_scrub_cancel_dev(struct btrfs_root *root, struct btrfs_device *dev)
1716 {
1717 	struct btrfs_fs_info *fs_info = root->fs_info;
1718 	struct scrub_dev *sdev;
1719 
1720 	mutex_lock(&fs_info->scrub_lock);
1721 	sdev = dev->scrub_device;
1722 	if (!sdev) {
1723 		mutex_unlock(&fs_info->scrub_lock);
1724 		return -ENOTCONN;
1725 	}
1726 	atomic_inc(&sdev->cancel_req);
1727 	while (dev->scrub_device) {
1728 		mutex_unlock(&fs_info->scrub_lock);
1729 		wait_event(fs_info->scrub_pause_wait,
1730 			   dev->scrub_device == NULL);
1731 		mutex_lock(&fs_info->scrub_lock);
1732 	}
1733 	mutex_unlock(&fs_info->scrub_lock);
1734 
1735 	return 0;
1736 }
1737 int btrfs_scrub_cancel_devid(struct btrfs_root *root, u64 devid)
1738 {
1739 	struct btrfs_fs_info *fs_info = root->fs_info;
1740 	struct btrfs_device *dev;
1741 	int ret;
1742 
1743 	/*
1744 	 * we have to hold the device_list_mutex here so the device
1745 	 * does not go away in cancel_dev. FIXME: find a better solution
1746 	 */
1747 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
1748 	dev = btrfs_find_device(root, devid, NULL, NULL);
1749 	if (!dev) {
1750 		mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1751 		return -ENODEV;
1752 	}
1753 	ret = btrfs_scrub_cancel_dev(root, dev);
1754 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
1755 
1756 	return ret;
1757 }
1758 
1759 int btrfs_scrub_progress(struct btrfs_root *root, u64 devid,
1760 			 struct btrfs_scrub_progress *progress)
1761 {
1762 	struct btrfs_device *dev;
1763 	struct scrub_dev *sdev = NULL;
1764 
1765 	mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1766 	dev = btrfs_find_device(root, devid, NULL, NULL);
1767 	if (dev)
1768 		sdev = dev->scrub_device;
1769 	if (sdev)
1770 		memcpy(progress, &sdev->stat, sizeof(*progress));
1771 	mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1772 
1773 	return dev ? (sdev ? 0 : -ENOTCONN) : -ENODEV;
1774 }
1775