• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
5 #include <linux/bio.h>
6 #include <linux/mm.h>
7 #include <linux/pagemap.h>
8 #include <linux/page-flags.h>
9 #include <linux/sched/mm.h>
10 #include <linux/spinlock.h>
11 #include <linux/blkdev.h>
12 #include <linux/swap.h>
13 #include <linux/writeback.h>
14 #include <linux/pagevec.h>
15 #include <linux/prefetch.h>
16 #include <linux/cleancache.h>
17 #include <linux/fsverity.h>
18 #include "misc.h"
19 #include "extent_io.h"
20 #include "extent-io-tree.h"
21 #include "extent_map.h"
22 #include "ctree.h"
23 #include "btrfs_inode.h"
24 #include "volumes.h"
25 #include "check-integrity.h"
26 #include "locking.h"
27 #include "rcu-string.h"
28 #include "backref.h"
29 #include "disk-io.h"
30 #include "subpage.h"
31 #include "zoned.h"
32 #include "block-group.h"
33 #include "compression.h"
34 
35 static struct kmem_cache *extent_buffer_cache;
36 
37 #ifdef CONFIG_BTRFS_DEBUG
btrfs_leak_debug_add_eb(struct extent_buffer * eb)38 static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
39 {
40 	struct btrfs_fs_info *fs_info = eb->fs_info;
41 	unsigned long flags;
42 
43 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
44 	list_add(&eb->leak_list, &fs_info->allocated_ebs);
45 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
46 }
47 
btrfs_leak_debug_del_eb(struct extent_buffer * eb)48 static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
49 {
50 	struct btrfs_fs_info *fs_info = eb->fs_info;
51 	unsigned long flags;
52 
53 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
54 	list_del(&eb->leak_list);
55 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
56 }
57 
btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info * fs_info)58 void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
59 {
60 	struct extent_buffer *eb;
61 	unsigned long flags;
62 
63 	/*
64 	 * If we didn't get into open_ctree our allocated_ebs will not be
65 	 * initialized, so just skip this.
66 	 */
67 	if (!fs_info->allocated_ebs.next)
68 		return;
69 
70 	WARN_ON(!list_empty(&fs_info->allocated_ebs));
71 	spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
72 	while (!list_empty(&fs_info->allocated_ebs)) {
73 		eb = list_first_entry(&fs_info->allocated_ebs,
74 				      struct extent_buffer, leak_list);
75 		pr_err(
76 	"BTRFS: buffer leak start %llu len %lu refs %d bflags %lu owner %llu\n",
77 		       eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
78 		       btrfs_header_owner(eb));
79 		list_del(&eb->leak_list);
80 		kmem_cache_free(extent_buffer_cache, eb);
81 	}
82 	spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
83 }
84 #else
85 #define btrfs_leak_debug_add_eb(eb)			do {} while (0)
86 #define btrfs_leak_debug_del_eb(eb)			do {} while (0)
87 #endif
88 
89 /*
90  * Structure to record info about the bio being assembled, and other info like
91  * how many bytes are there before stripe/ordered extent boundary.
92  */
93 struct btrfs_bio_ctrl {
94 	struct bio *bio;
95 	int mirror_num;
96 	enum btrfs_compression_type compress_type;
97 	u32 len_to_stripe_boundary;
98 	u32 len_to_oe_boundary;
99 	btrfs_bio_end_io_t end_io_func;
100 };
101 
102 struct extent_page_data {
103 	struct btrfs_bio_ctrl bio_ctrl;
104 	/* tells writepage not to lock the state bits for this range
105 	 * it still does the unlocking
106 	 */
107 	unsigned int extent_locked:1;
108 
109 	/* tells the submit_bio code to use REQ_SYNC */
110 	unsigned int sync_io:1;
111 };
112 
submit_one_bio(struct btrfs_bio_ctrl * bio_ctrl)113 static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
114 {
115 	struct bio *bio;
116 	struct bio_vec *bv;
117 	struct inode *inode;
118 	int mirror_num;
119 
120 	if (!bio_ctrl->bio)
121 		return;
122 
123 	bio = bio_ctrl->bio;
124 	bv = bio_first_bvec_all(bio);
125 	inode = bv->bv_page->mapping->host;
126 	mirror_num = bio_ctrl->mirror_num;
127 
128 	/* Caller should ensure the bio has at least some range added */
129 	ASSERT(bio->bi_iter.bi_size);
130 
131 	btrfs_bio(bio)->file_offset = page_offset(bv->bv_page) + bv->bv_offset;
132 
133 	if (!is_data_inode(inode))
134 		btrfs_submit_metadata_bio(inode, bio, mirror_num);
135 	else if (btrfs_op(bio) == BTRFS_MAP_WRITE)
136 		btrfs_submit_data_write_bio(inode, bio, mirror_num);
137 	else
138 		btrfs_submit_data_read_bio(inode, bio, mirror_num,
139 					   bio_ctrl->compress_type);
140 
141 	/* The bio is owned by the end_io handler now */
142 	bio_ctrl->bio = NULL;
143 }
144 
145 /*
146  * Submit or fail the current bio in an extent_page_data structure.
147  */
submit_write_bio(struct extent_page_data * epd,int ret)148 static void submit_write_bio(struct extent_page_data *epd, int ret)
149 {
150 	struct bio *bio = epd->bio_ctrl.bio;
151 
152 	if (!bio)
153 		return;
154 
155 	if (ret) {
156 		ASSERT(ret < 0);
157 		btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
158 		/* The bio is owned by the end_io handler now */
159 		epd->bio_ctrl.bio = NULL;
160 	} else {
161 		submit_one_bio(&epd->bio_ctrl);
162 	}
163 }
164 
extent_buffer_init_cachep(void)165 int __init extent_buffer_init_cachep(void)
166 {
167 	extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
168 			sizeof(struct extent_buffer), 0,
169 			SLAB_MEM_SPREAD, NULL);
170 	if (!extent_buffer_cache)
171 		return -ENOMEM;
172 
173 	return 0;
174 }
175 
extent_buffer_free_cachep(void)176 void __cold extent_buffer_free_cachep(void)
177 {
178 	/*
179 	 * Make sure all delayed rcu free are flushed before we
180 	 * destroy caches.
181 	 */
182 	rcu_barrier();
183 	kmem_cache_destroy(extent_buffer_cache);
184 }
185 
extent_range_clear_dirty_for_io(struct inode * inode,u64 start,u64 end)186 void extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
187 {
188 	unsigned long index = start >> PAGE_SHIFT;
189 	unsigned long end_index = end >> PAGE_SHIFT;
190 	struct page *page;
191 
192 	while (index <= end_index) {
193 		page = find_get_page(inode->i_mapping, index);
194 		BUG_ON(!page); /* Pages should be in the extent_io_tree */
195 		clear_page_dirty_for_io(page);
196 		put_page(page);
197 		index++;
198 	}
199 }
200 
extent_range_redirty_for_io(struct inode * inode,u64 start,u64 end)201 void extent_range_redirty_for_io(struct inode *inode, u64 start, u64 end)
202 {
203 	struct address_space *mapping = inode->i_mapping;
204 	unsigned long index = start >> PAGE_SHIFT;
205 	unsigned long end_index = end >> PAGE_SHIFT;
206 	struct folio *folio;
207 
208 	while (index <= end_index) {
209 		folio = filemap_get_folio(mapping, index);
210 		filemap_dirty_folio(mapping, folio);
211 		folio_account_redirty(folio);
212 		index += folio_nr_pages(folio);
213 		folio_put(folio);
214 	}
215 }
216 
217 /*
218  * Process one page for __process_pages_contig().
219  *
220  * Return >0 if we hit @page == @locked_page.
221  * Return 0 if we updated the page status.
222  * Return -EGAIN if the we need to try again.
223  * (For PAGE_LOCK case but got dirty page or page not belong to mapping)
224  */
process_one_page(struct btrfs_fs_info * fs_info,struct address_space * mapping,struct page * page,struct page * locked_page,unsigned long page_ops,u64 start,u64 end)225 static int process_one_page(struct btrfs_fs_info *fs_info,
226 			    struct address_space *mapping,
227 			    struct page *page, struct page *locked_page,
228 			    unsigned long page_ops, u64 start, u64 end)
229 {
230 	u32 len;
231 
232 	ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
233 	len = end + 1 - start;
234 
235 	if (page_ops & PAGE_SET_ORDERED)
236 		btrfs_page_clamp_set_ordered(fs_info, page, start, len);
237 	if (page_ops & PAGE_SET_ERROR)
238 		btrfs_page_clamp_set_error(fs_info, page, start, len);
239 	if (page_ops & PAGE_START_WRITEBACK) {
240 		btrfs_page_clamp_clear_dirty(fs_info, page, start, len);
241 		btrfs_page_clamp_set_writeback(fs_info, page, start, len);
242 	}
243 	if (page_ops & PAGE_END_WRITEBACK)
244 		btrfs_page_clamp_clear_writeback(fs_info, page, start, len);
245 
246 	if (page == locked_page)
247 		return 1;
248 
249 	if (page_ops & PAGE_LOCK) {
250 		int ret;
251 
252 		ret = btrfs_page_start_writer_lock(fs_info, page, start, len);
253 		if (ret)
254 			return ret;
255 		if (!PageDirty(page) || page->mapping != mapping) {
256 			btrfs_page_end_writer_lock(fs_info, page, start, len);
257 			return -EAGAIN;
258 		}
259 	}
260 	if (page_ops & PAGE_UNLOCK)
261 		btrfs_page_end_writer_lock(fs_info, page, start, len);
262 	return 0;
263 }
264 
__process_pages_contig(struct address_space * mapping,struct page * locked_page,u64 start,u64 end,unsigned long page_ops,u64 * processed_end)265 static int __process_pages_contig(struct address_space *mapping,
266 				  struct page *locked_page,
267 				  u64 start, u64 end, unsigned long page_ops,
268 				  u64 *processed_end)
269 {
270 	struct btrfs_fs_info *fs_info = btrfs_sb(mapping->host->i_sb);
271 	pgoff_t start_index = start >> PAGE_SHIFT;
272 	pgoff_t end_index = end >> PAGE_SHIFT;
273 	pgoff_t index = start_index;
274 	unsigned long pages_processed = 0;
275 	struct folio_batch fbatch;
276 	int err = 0;
277 	int i;
278 
279 	if (page_ops & PAGE_LOCK) {
280 		ASSERT(page_ops == PAGE_LOCK);
281 		ASSERT(processed_end && *processed_end == start);
282 	}
283 
284 	if ((page_ops & PAGE_SET_ERROR) && start_index <= end_index)
285 		mapping_set_error(mapping, -EIO);
286 
287 	folio_batch_init(&fbatch);
288 	while (index <= end_index) {
289 		int found_folios;
290 
291 		found_folios = filemap_get_folios_contig(mapping, &index,
292 				end_index, &fbatch);
293 
294 		if (found_folios == 0) {
295 			/*
296 			 * Only if we're going to lock these pages, we can find
297 			 * nothing at @index.
298 			 */
299 			ASSERT(page_ops & PAGE_LOCK);
300 			err = -EAGAIN;
301 			goto out;
302 		}
303 
304 		for (i = 0; i < found_folios; i++) {
305 			int process_ret;
306 			struct folio *folio = fbatch.folios[i];
307 			process_ret = process_one_page(fs_info, mapping,
308 					&folio->page, locked_page, page_ops,
309 					start, end);
310 			if (process_ret < 0) {
311 				err = -EAGAIN;
312 				folio_batch_release(&fbatch);
313 				goto out;
314 			}
315 			pages_processed += folio_nr_pages(folio);
316 		}
317 		folio_batch_release(&fbatch);
318 		cond_resched();
319 	}
320 out:
321 	if (err && processed_end) {
322 		/*
323 		 * Update @processed_end. I know this is awful since it has
324 		 * two different return value patterns (inclusive vs exclusive).
325 		 *
326 		 * But the exclusive pattern is necessary if @start is 0, or we
327 		 * underflow and check against processed_end won't work as
328 		 * expected.
329 		 */
330 		if (pages_processed)
331 			*processed_end = min(end,
332 			((u64)(start_index + pages_processed) << PAGE_SHIFT) - 1);
333 		else
334 			*processed_end = start;
335 	}
336 	return err;
337 }
338 
__unlock_for_delalloc(struct inode * inode,struct page * locked_page,u64 start,u64 end)339 static noinline void __unlock_for_delalloc(struct inode *inode,
340 					   struct page *locked_page,
341 					   u64 start, u64 end)
342 {
343 	unsigned long index = start >> PAGE_SHIFT;
344 	unsigned long end_index = end >> PAGE_SHIFT;
345 
346 	ASSERT(locked_page);
347 	if (index == locked_page->index && end_index == index)
348 		return;
349 
350 	__process_pages_contig(inode->i_mapping, locked_page, start, end,
351 			       PAGE_UNLOCK, NULL);
352 }
353 
lock_delalloc_pages(struct inode * inode,struct page * locked_page,u64 delalloc_start,u64 delalloc_end)354 static noinline int lock_delalloc_pages(struct inode *inode,
355 					struct page *locked_page,
356 					u64 delalloc_start,
357 					u64 delalloc_end)
358 {
359 	unsigned long index = delalloc_start >> PAGE_SHIFT;
360 	unsigned long end_index = delalloc_end >> PAGE_SHIFT;
361 	u64 processed_end = delalloc_start;
362 	int ret;
363 
364 	ASSERT(locked_page);
365 	if (index == locked_page->index && index == end_index)
366 		return 0;
367 
368 	ret = __process_pages_contig(inode->i_mapping, locked_page, delalloc_start,
369 				     delalloc_end, PAGE_LOCK, &processed_end);
370 	if (ret == -EAGAIN && processed_end > delalloc_start)
371 		__unlock_for_delalloc(inode, locked_page, delalloc_start,
372 				      processed_end);
373 	return ret;
374 }
375 
376 /*
377  * Find and lock a contiguous range of bytes in the file marked as delalloc, no
378  * more than @max_bytes.
379  *
380  * @start:	The original start bytenr to search.
381  *		Will store the extent range start bytenr.
382  * @end:	The original end bytenr of the search range
383  *		Will store the extent range end bytenr.
384  *
385  * Return true if we find a delalloc range which starts inside the original
386  * range, and @start/@end will store the delalloc range start/end.
387  *
388  * Return false if we can't find any delalloc range which starts inside the
389  * original range, and @start/@end will be the non-delalloc range start/end.
390  */
391 EXPORT_FOR_TESTS
find_lock_delalloc_range(struct inode * inode,struct page * locked_page,u64 * start,u64 * end)392 noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
393 				    struct page *locked_page, u64 *start,
394 				    u64 *end)
395 {
396 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
397 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
398 	const u64 orig_start = *start;
399 	const u64 orig_end = *end;
400 	/* The sanity tests may not set a valid fs_info. */
401 	u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
402 	u64 delalloc_start;
403 	u64 delalloc_end;
404 	bool found;
405 	struct extent_state *cached_state = NULL;
406 	int ret;
407 	int loops = 0;
408 
409 	/* Caller should pass a valid @end to indicate the search range end */
410 	ASSERT(orig_end > orig_start);
411 
412 	/* The range should at least cover part of the page */
413 	ASSERT(!(orig_start >= page_offset(locked_page) + PAGE_SIZE ||
414 		 orig_end <= page_offset(locked_page)));
415 again:
416 	/* step one, find a bunch of delalloc bytes starting at start */
417 	delalloc_start = *start;
418 	delalloc_end = 0;
419 	found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
420 					  max_bytes, &cached_state);
421 	if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
422 		*start = delalloc_start;
423 
424 		/* @delalloc_end can be -1, never go beyond @orig_end */
425 		*end = min(delalloc_end, orig_end);
426 		free_extent_state(cached_state);
427 		return false;
428 	}
429 
430 	/*
431 	 * start comes from the offset of locked_page.  We have to lock
432 	 * pages in order, so we can't process delalloc bytes before
433 	 * locked_page
434 	 */
435 	if (delalloc_start < *start)
436 		delalloc_start = *start;
437 
438 	/*
439 	 * make sure to limit the number of pages we try to lock down
440 	 */
441 	if (delalloc_end + 1 - delalloc_start > max_bytes)
442 		delalloc_end = delalloc_start + max_bytes - 1;
443 
444 	/* step two, lock all the pages after the page that has start */
445 	ret = lock_delalloc_pages(inode, locked_page,
446 				  delalloc_start, delalloc_end);
447 	ASSERT(!ret || ret == -EAGAIN);
448 	if (ret == -EAGAIN) {
449 		/* some of the pages are gone, lets avoid looping by
450 		 * shortening the size of the delalloc range we're searching
451 		 */
452 		free_extent_state(cached_state);
453 		cached_state = NULL;
454 		if (!loops) {
455 			max_bytes = PAGE_SIZE;
456 			loops = 1;
457 			goto again;
458 		} else {
459 			found = false;
460 			goto out_failed;
461 		}
462 	}
463 
464 	/* step three, lock the state bits for the whole range */
465 	lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
466 
467 	/* then test to make sure it is all still delalloc */
468 	ret = test_range_bit(tree, delalloc_start, delalloc_end,
469 			     EXTENT_DELALLOC, 1, cached_state);
470 	if (!ret) {
471 		unlock_extent(tree, delalloc_start, delalloc_end,
472 			      &cached_state);
473 		__unlock_for_delalloc(inode, locked_page,
474 			      delalloc_start, delalloc_end);
475 		cond_resched();
476 		goto again;
477 	}
478 	free_extent_state(cached_state);
479 	*start = delalloc_start;
480 	*end = delalloc_end;
481 out_failed:
482 	return found;
483 }
484 
extent_clear_unlock_delalloc(struct btrfs_inode * inode,u64 start,u64 end,struct page * locked_page,u32 clear_bits,unsigned long page_ops)485 void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
486 				  struct page *locked_page,
487 				  u32 clear_bits, unsigned long page_ops)
488 {
489 	clear_extent_bit(&inode->io_tree, start, end, clear_bits, NULL);
490 
491 	__process_pages_contig(inode->vfs_inode.i_mapping, locked_page,
492 			       start, end, page_ops, NULL);
493 }
494 
insert_failrec(struct btrfs_inode * inode,struct io_failure_record * failrec)495 static int insert_failrec(struct btrfs_inode *inode,
496 			  struct io_failure_record *failrec)
497 {
498 	struct rb_node *exist;
499 
500 	spin_lock(&inode->io_failure_lock);
501 	exist = rb_simple_insert(&inode->io_failure_tree, failrec->bytenr,
502 				 &failrec->rb_node);
503 	spin_unlock(&inode->io_failure_lock);
504 
505 	return (exist == NULL) ? 0 : -EEXIST;
506 }
507 
get_failrec(struct btrfs_inode * inode,u64 start)508 static struct io_failure_record *get_failrec(struct btrfs_inode *inode, u64 start)
509 {
510 	struct rb_node *node;
511 	struct io_failure_record *failrec = ERR_PTR(-ENOENT);
512 
513 	spin_lock(&inode->io_failure_lock);
514 	node = rb_simple_search(&inode->io_failure_tree, start);
515 	if (node)
516 		failrec = rb_entry(node, struct io_failure_record, rb_node);
517 	spin_unlock(&inode->io_failure_lock);
518 	return failrec;
519 }
520 
free_io_failure(struct btrfs_inode * inode,struct io_failure_record * rec)521 static void free_io_failure(struct btrfs_inode *inode,
522 			    struct io_failure_record *rec)
523 {
524 	spin_lock(&inode->io_failure_lock);
525 	rb_erase(&rec->rb_node, &inode->io_failure_tree);
526 	spin_unlock(&inode->io_failure_lock);
527 
528 	kfree(rec);
529 }
530 
531 /*
532  * this bypasses the standard btrfs submit functions deliberately, as
533  * the standard behavior is to write all copies in a raid setup. here we only
534  * want to write the one bad copy. so we do the mapping for ourselves and issue
535  * submit_bio directly.
536  * to avoid any synchronization issues, wait for the data after writing, which
537  * actually prevents the read that triggered the error from finishing.
538  * currently, there can be no more than two copies of every data bit. thus,
539  * exactly one rewrite is required.
540  */
repair_io_failure(struct btrfs_fs_info * fs_info,u64 ino,u64 start,u64 length,u64 logical,struct page * page,unsigned int pg_offset,int mirror_num)541 static int repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 start,
542 			     u64 length, u64 logical, struct page *page,
543 			     unsigned int pg_offset, int mirror_num)
544 {
545 	struct btrfs_device *dev;
546 	struct bio_vec bvec;
547 	struct bio bio;
548 	u64 map_length = 0;
549 	u64 sector;
550 	struct btrfs_io_context *bioc = NULL;
551 	int ret = 0;
552 
553 	ASSERT(!(fs_info->sb->s_flags & SB_RDONLY));
554 	BUG_ON(!mirror_num);
555 
556 	if (btrfs_repair_one_zone(fs_info, logical))
557 		return 0;
558 
559 	map_length = length;
560 
561 	/*
562 	 * Avoid races with device replace and make sure our bioc has devices
563 	 * associated to its stripes that don't go away while we are doing the
564 	 * read repair operation.
565 	 */
566 	btrfs_bio_counter_inc_blocked(fs_info);
567 	if (btrfs_is_parity_mirror(fs_info, logical, length)) {
568 		/*
569 		 * Note that we don't use BTRFS_MAP_WRITE because it's supposed
570 		 * to update all raid stripes, but here we just want to correct
571 		 * bad stripe, thus BTRFS_MAP_READ is abused to only get the bad
572 		 * stripe's dev and sector.
573 		 */
574 		ret = btrfs_map_block(fs_info, BTRFS_MAP_READ, logical,
575 				      &map_length, &bioc, 0);
576 		if (ret)
577 			goto out_counter_dec;
578 		ASSERT(bioc->mirror_num == 1);
579 	} else {
580 		ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical,
581 				      &map_length, &bioc, mirror_num);
582 		if (ret)
583 			goto out_counter_dec;
584 		/*
585 		 * This happens when dev-replace is also running, and the
586 		 * mirror_num indicates the dev-replace target.
587 		 *
588 		 * In this case, we don't need to do anything, as the read
589 		 * error just means the replace progress hasn't reached our
590 		 * read range, and later replace routine would handle it well.
591 		 */
592 		if (mirror_num != bioc->mirror_num)
593 			goto out_counter_dec;
594 	}
595 
596 	sector = bioc->stripes[bioc->mirror_num - 1].physical >> 9;
597 	dev = bioc->stripes[bioc->mirror_num - 1].dev;
598 	btrfs_put_bioc(bioc);
599 
600 	if (!dev || !dev->bdev ||
601 	    !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state)) {
602 		ret = -EIO;
603 		goto out_counter_dec;
604 	}
605 
606 	bio_init(&bio, dev->bdev, &bvec, 1, REQ_OP_WRITE | REQ_SYNC);
607 	bio.bi_iter.bi_sector = sector;
608 	__bio_add_page(&bio, page, length, pg_offset);
609 
610 	btrfsic_check_bio(&bio);
611 	ret = submit_bio_wait(&bio);
612 	if (ret) {
613 		/* try to remap that extent elsewhere? */
614 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_WRITE_ERRS);
615 		goto out_bio_uninit;
616 	}
617 
618 	btrfs_info_rl_in_rcu(fs_info,
619 		"read error corrected: ino %llu off %llu (dev %s sector %llu)",
620 				  ino, start,
621 				  rcu_str_deref(dev->name), sector);
622 	ret = 0;
623 
624 out_bio_uninit:
625 	bio_uninit(&bio);
626 out_counter_dec:
627 	btrfs_bio_counter_dec(fs_info);
628 	return ret;
629 }
630 
btrfs_repair_eb_io_failure(const struct extent_buffer * eb,int mirror_num)631 int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num)
632 {
633 	struct btrfs_fs_info *fs_info = eb->fs_info;
634 	u64 start = eb->start;
635 	int i, num_pages = num_extent_pages(eb);
636 	int ret = 0;
637 
638 	if (sb_rdonly(fs_info->sb))
639 		return -EROFS;
640 
641 	for (i = 0; i < num_pages; i++) {
642 		struct page *p = eb->pages[i];
643 
644 		ret = repair_io_failure(fs_info, 0, start, PAGE_SIZE, start, p,
645 					start - page_offset(p), mirror_num);
646 		if (ret)
647 			break;
648 		start += PAGE_SIZE;
649 	}
650 
651 	return ret;
652 }
653 
next_mirror(const struct io_failure_record * failrec,int cur_mirror)654 static int next_mirror(const struct io_failure_record *failrec, int cur_mirror)
655 {
656 	if (cur_mirror == failrec->num_copies)
657 		return cur_mirror + 1 - failrec->num_copies;
658 	return cur_mirror + 1;
659 }
660 
prev_mirror(const struct io_failure_record * failrec,int cur_mirror)661 static int prev_mirror(const struct io_failure_record *failrec, int cur_mirror)
662 {
663 	if (cur_mirror == 1)
664 		return failrec->num_copies;
665 	return cur_mirror - 1;
666 }
667 
668 /*
669  * each time an IO finishes, we do a fast check in the IO failure tree
670  * to see if we need to process or clean up an io_failure_record
671  */
btrfs_clean_io_failure(struct btrfs_inode * inode,u64 start,struct page * page,unsigned int pg_offset)672 int btrfs_clean_io_failure(struct btrfs_inode *inode, u64 start,
673 			   struct page *page, unsigned int pg_offset)
674 {
675 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
676 	struct extent_io_tree *io_tree = &inode->io_tree;
677 	u64 ino = btrfs_ino(inode);
678 	u64 locked_start, locked_end;
679 	struct io_failure_record *failrec;
680 	int mirror;
681 	int ret;
682 
683 	failrec = get_failrec(inode, start);
684 	if (IS_ERR(failrec))
685 		return 0;
686 
687 	BUG_ON(!failrec->this_mirror);
688 
689 	if (sb_rdonly(fs_info->sb))
690 		goto out;
691 
692 	ret = find_first_extent_bit(io_tree, failrec->bytenr, &locked_start,
693 				    &locked_end, EXTENT_LOCKED, NULL);
694 	if (ret || locked_start > failrec->bytenr ||
695 	    locked_end < failrec->bytenr + failrec->len - 1)
696 		goto out;
697 
698 	mirror = failrec->this_mirror;
699 	do {
700 		mirror = prev_mirror(failrec, mirror);
701 		repair_io_failure(fs_info, ino, start, failrec->len,
702 				  failrec->logical, page, pg_offset, mirror);
703 	} while (mirror != failrec->failed_mirror);
704 
705 out:
706 	free_io_failure(inode, failrec);
707 	return 0;
708 }
709 
710 /*
711  * Can be called when
712  * - hold extent lock
713  * - under ordered extent
714  * - the inode is freeing
715  */
btrfs_free_io_failure_record(struct btrfs_inode * inode,u64 start,u64 end)716 void btrfs_free_io_failure_record(struct btrfs_inode *inode, u64 start, u64 end)
717 {
718 	struct io_failure_record *failrec;
719 	struct rb_node *node, *next;
720 
721 	if (RB_EMPTY_ROOT(&inode->io_failure_tree))
722 		return;
723 
724 	spin_lock(&inode->io_failure_lock);
725 	node = rb_simple_search_first(&inode->io_failure_tree, start);
726 	while (node) {
727 		failrec = rb_entry(node, struct io_failure_record, rb_node);
728 		if (failrec->bytenr > end)
729 			break;
730 
731 		next = rb_next(node);
732 		rb_erase(&failrec->rb_node, &inode->io_failure_tree);
733 		kfree(failrec);
734 
735 		node = next;
736 	}
737 	spin_unlock(&inode->io_failure_lock);
738 }
739 
btrfs_get_io_failure_record(struct inode * inode,struct btrfs_bio * bbio,unsigned int bio_offset)740 static struct io_failure_record *btrfs_get_io_failure_record(struct inode *inode,
741 							     struct btrfs_bio *bbio,
742 							     unsigned int bio_offset)
743 {
744 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
745 	u64 start = bbio->file_offset + bio_offset;
746 	struct io_failure_record *failrec;
747 	const u32 sectorsize = fs_info->sectorsize;
748 	int ret;
749 
750 	failrec = get_failrec(BTRFS_I(inode), start);
751 	if (!IS_ERR(failrec)) {
752 		btrfs_debug(fs_info,
753 	"Get IO Failure Record: (found) logical=%llu, start=%llu, len=%llu",
754 			failrec->logical, failrec->bytenr, failrec->len);
755 		/*
756 		 * when data can be on disk more than twice, add to failrec here
757 		 * (e.g. with a list for failed_mirror) to make
758 		 * clean_io_failure() clean all those errors at once.
759 		 */
760 		ASSERT(failrec->this_mirror == bbio->mirror_num);
761 		ASSERT(failrec->len == fs_info->sectorsize);
762 		return failrec;
763 	}
764 
765 	failrec = kzalloc(sizeof(*failrec), GFP_NOFS);
766 	if (!failrec)
767 		return ERR_PTR(-ENOMEM);
768 
769 	RB_CLEAR_NODE(&failrec->rb_node);
770 	failrec->bytenr = start;
771 	failrec->len = sectorsize;
772 	failrec->failed_mirror = bbio->mirror_num;
773 	failrec->this_mirror = bbio->mirror_num;
774 	failrec->logical = (bbio->iter.bi_sector << SECTOR_SHIFT) + bio_offset;
775 
776 	btrfs_debug(fs_info,
777 		    "new io failure record logical %llu start %llu",
778 		    failrec->logical, start);
779 
780 	failrec->num_copies = btrfs_num_copies(fs_info, failrec->logical, sectorsize);
781 	if (failrec->num_copies == 1) {
782 		/*
783 		 * We only have a single copy of the data, so don't bother with
784 		 * all the retry and error correction code that follows. No
785 		 * matter what the error is, it is very likely to persist.
786 		 */
787 		btrfs_debug(fs_info,
788 			"cannot repair logical %llu num_copies %d",
789 			failrec->logical, failrec->num_copies);
790 		kfree(failrec);
791 		return ERR_PTR(-EIO);
792 	}
793 
794 	/* Set the bits in the private failure tree */
795 	ret = insert_failrec(BTRFS_I(inode), failrec);
796 	if (ret) {
797 		kfree(failrec);
798 		return ERR_PTR(ret);
799 	}
800 
801 	return failrec;
802 }
803 
btrfs_repair_one_sector(struct inode * inode,struct btrfs_bio * failed_bbio,u32 bio_offset,struct page * page,unsigned int pgoff,submit_bio_hook_t * submit_bio_hook)804 int btrfs_repair_one_sector(struct inode *inode, struct btrfs_bio *failed_bbio,
805 			    u32 bio_offset, struct page *page, unsigned int pgoff,
806 			    submit_bio_hook_t *submit_bio_hook)
807 {
808 	u64 start = failed_bbio->file_offset + bio_offset;
809 	struct io_failure_record *failrec;
810 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
811 	struct bio *failed_bio = &failed_bbio->bio;
812 	const int icsum = bio_offset >> fs_info->sectorsize_bits;
813 	struct bio *repair_bio;
814 	struct btrfs_bio *repair_bbio;
815 
816 	btrfs_debug(fs_info,
817 		   "repair read error: read error at %llu", start);
818 
819 	BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
820 
821 	failrec = btrfs_get_io_failure_record(inode, failed_bbio, bio_offset);
822 	if (IS_ERR(failrec))
823 		return PTR_ERR(failrec);
824 
825 	/*
826 	 * There are two premises:
827 	 * a) deliver good data to the caller
828 	 * b) correct the bad sectors on disk
829 	 *
830 	 * Since we're only doing repair for one sector, we only need to get
831 	 * a good copy of the failed sector and if we succeed, we have setup
832 	 * everything for repair_io_failure to do the rest for us.
833 	 */
834 	failrec->this_mirror = next_mirror(failrec, failrec->this_mirror);
835 	if (failrec->this_mirror == failrec->failed_mirror) {
836 		btrfs_debug(fs_info,
837 			"failed to repair num_copies %d this_mirror %d failed_mirror %d",
838 			failrec->num_copies, failrec->this_mirror, failrec->failed_mirror);
839 		free_io_failure(BTRFS_I(inode), failrec);
840 		return -EIO;
841 	}
842 
843 	repair_bio = btrfs_bio_alloc(1, REQ_OP_READ, failed_bbio->end_io,
844 				     failed_bbio->private);
845 	repair_bbio = btrfs_bio(repair_bio);
846 	repair_bbio->file_offset = start;
847 	repair_bio->bi_iter.bi_sector = failrec->logical >> 9;
848 
849 	if (failed_bbio->csum) {
850 		const u32 csum_size = fs_info->csum_size;
851 
852 		repair_bbio->csum = repair_bbio->csum_inline;
853 		memcpy(repair_bbio->csum,
854 		       failed_bbio->csum + csum_size * icsum, csum_size);
855 	}
856 
857 	bio_add_page(repair_bio, page, failrec->len, pgoff);
858 	repair_bbio->iter = repair_bio->bi_iter;
859 
860 	btrfs_debug(btrfs_sb(inode->i_sb),
861 		    "repair read error: submitting new read to mirror %d",
862 		    failrec->this_mirror);
863 
864 	/*
865 	 * At this point we have a bio, so any errors from submit_bio_hook()
866 	 * will be handled by the endio on the repair_bio, so we can't return an
867 	 * error here.
868 	 */
869 	submit_bio_hook(inode, repair_bio, failrec->this_mirror, 0);
870 	return BLK_STS_OK;
871 }
872 
end_page_read(struct page * page,bool uptodate,u64 start,u32 len)873 static void end_page_read(struct page *page, bool uptodate, u64 start, u32 len)
874 {
875 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
876 
877 	ASSERT(page_offset(page) <= start &&
878 	       start + len <= page_offset(page) + PAGE_SIZE);
879 
880 	if (uptodate) {
881 		if (fsverity_active(page->mapping->host) &&
882 		    !PageError(page) &&
883 		    !PageUptodate(page) &&
884 		    start < i_size_read(page->mapping->host) &&
885 		    !fsverity_verify_page(page)) {
886 			btrfs_page_set_error(fs_info, page, start, len);
887 		} else {
888 			btrfs_page_set_uptodate(fs_info, page, start, len);
889 		}
890 	} else {
891 		btrfs_page_clear_uptodate(fs_info, page, start, len);
892 		btrfs_page_set_error(fs_info, page, start, len);
893 	}
894 
895 	if (!btrfs_is_subpage(fs_info, page))
896 		unlock_page(page);
897 	else
898 		btrfs_subpage_end_reader(fs_info, page, start, len);
899 }
900 
end_sector_io(struct page * page,u64 offset,bool uptodate)901 static void end_sector_io(struct page *page, u64 offset, bool uptodate)
902 {
903 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
904 	const u32 sectorsize = inode->root->fs_info->sectorsize;
905 	struct extent_state *cached = NULL;
906 
907 	end_page_read(page, uptodate, offset, sectorsize);
908 	if (uptodate)
909 		set_extent_uptodate(&inode->io_tree, offset,
910 				    offset + sectorsize - 1, &cached, GFP_ATOMIC);
911 	unlock_extent_atomic(&inode->io_tree, offset, offset + sectorsize - 1,
912 			     &cached);
913 }
914 
submit_data_read_repair(struct inode * inode,struct btrfs_bio * failed_bbio,u32 bio_offset,const struct bio_vec * bvec,unsigned int error_bitmap)915 static void submit_data_read_repair(struct inode *inode,
916 				    struct btrfs_bio *failed_bbio,
917 				    u32 bio_offset, const struct bio_vec *bvec,
918 				    unsigned int error_bitmap)
919 {
920 	const unsigned int pgoff = bvec->bv_offset;
921 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
922 	struct page *page = bvec->bv_page;
923 	const u64 start = page_offset(bvec->bv_page) + bvec->bv_offset;
924 	const u64 end = start + bvec->bv_len - 1;
925 	const u32 sectorsize = fs_info->sectorsize;
926 	const int nr_bits = (end + 1 - start) >> fs_info->sectorsize_bits;
927 	int i;
928 
929 	BUG_ON(bio_op(&failed_bbio->bio) == REQ_OP_WRITE);
930 
931 	/* This repair is only for data */
932 	ASSERT(is_data_inode(inode));
933 
934 	/* We're here because we had some read errors or csum mismatch */
935 	ASSERT(error_bitmap);
936 
937 	/*
938 	 * We only get called on buffered IO, thus page must be mapped and bio
939 	 * must not be cloned.
940 	 */
941 	ASSERT(page->mapping && !bio_flagged(&failed_bbio->bio, BIO_CLONED));
942 
943 	/* Iterate through all the sectors in the range */
944 	for (i = 0; i < nr_bits; i++) {
945 		const unsigned int offset = i * sectorsize;
946 		bool uptodate = false;
947 		int ret;
948 
949 		if (!(error_bitmap & (1U << i))) {
950 			/*
951 			 * This sector has no error, just end the page read
952 			 * and unlock the range.
953 			 */
954 			uptodate = true;
955 			goto next;
956 		}
957 
958 		ret = btrfs_repair_one_sector(inode, failed_bbio,
959 				bio_offset + offset, page, pgoff + offset,
960 				btrfs_submit_data_read_bio);
961 		if (!ret) {
962 			/*
963 			 * We have submitted the read repair, the page release
964 			 * will be handled by the endio function of the
965 			 * submitted repair bio.
966 			 * Thus we don't need to do any thing here.
967 			 */
968 			continue;
969 		}
970 		/*
971 		 * Continue on failed repair, otherwise the remaining sectors
972 		 * will not be properly unlocked.
973 		 */
974 next:
975 		end_sector_io(page, start + offset, uptodate);
976 	}
977 }
978 
979 /* lots and lots of room for performance fixes in the end_bio funcs */
980 
end_extent_writepage(struct page * page,int err,u64 start,u64 end)981 void end_extent_writepage(struct page *page, int err, u64 start, u64 end)
982 {
983 	struct btrfs_inode *inode;
984 	const bool uptodate = (err == 0);
985 	int ret = 0;
986 
987 	ASSERT(page && page->mapping);
988 	inode = BTRFS_I(page->mapping->host);
989 	btrfs_writepage_endio_finish_ordered(inode, page, start, end, uptodate);
990 
991 	if (!uptodate) {
992 		const struct btrfs_fs_info *fs_info = inode->root->fs_info;
993 		u32 len;
994 
995 		ASSERT(end + 1 - start <= U32_MAX);
996 		len = end + 1 - start;
997 
998 		btrfs_page_clear_uptodate(fs_info, page, start, len);
999 		btrfs_page_set_error(fs_info, page, start, len);
1000 		ret = err < 0 ? err : -EIO;
1001 		mapping_set_error(page->mapping, ret);
1002 	}
1003 }
1004 
1005 /*
1006  * after a writepage IO is done, we need to:
1007  * clear the uptodate bits on error
1008  * clear the writeback bits in the extent tree for this IO
1009  * end_page_writeback if the page has no more pending IO
1010  *
1011  * Scheduling is not allowed, so the extent state tree is expected
1012  * to have one and only one object corresponding to this IO.
1013  */
end_bio_extent_writepage(struct btrfs_bio * bbio)1014 static void end_bio_extent_writepage(struct btrfs_bio *bbio)
1015 {
1016 	struct bio *bio = &bbio->bio;
1017 	int error = blk_status_to_errno(bio->bi_status);
1018 	struct bio_vec *bvec;
1019 	u64 start;
1020 	u64 end;
1021 	struct bvec_iter_all iter_all;
1022 	bool first_bvec = true;
1023 
1024 	ASSERT(!bio_flagged(bio, BIO_CLONED));
1025 	bio_for_each_segment_all(bvec, bio, iter_all) {
1026 		struct page *page = bvec->bv_page;
1027 		struct inode *inode = page->mapping->host;
1028 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1029 		const u32 sectorsize = fs_info->sectorsize;
1030 
1031 		/* Our read/write should always be sector aligned. */
1032 		if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1033 			btrfs_err(fs_info,
1034 		"partial page write in btrfs with offset %u and length %u",
1035 				  bvec->bv_offset, bvec->bv_len);
1036 		else if (!IS_ALIGNED(bvec->bv_len, sectorsize))
1037 			btrfs_info(fs_info,
1038 		"incomplete page write with offset %u and length %u",
1039 				   bvec->bv_offset, bvec->bv_len);
1040 
1041 		start = page_offset(page) + bvec->bv_offset;
1042 		end = start + bvec->bv_len - 1;
1043 
1044 		if (first_bvec) {
1045 			btrfs_record_physical_zoned(inode, start, bio);
1046 			first_bvec = false;
1047 		}
1048 
1049 		end_extent_writepage(page, error, start, end);
1050 
1051 		btrfs_page_clear_writeback(fs_info, page, start, bvec->bv_len);
1052 	}
1053 
1054 	bio_put(bio);
1055 }
1056 
1057 /*
1058  * Record previously processed extent range
1059  *
1060  * For endio_readpage_release_extent() to handle a full extent range, reducing
1061  * the extent io operations.
1062  */
1063 struct processed_extent {
1064 	struct btrfs_inode *inode;
1065 	/* Start of the range in @inode */
1066 	u64 start;
1067 	/* End of the range in @inode */
1068 	u64 end;
1069 	bool uptodate;
1070 };
1071 
1072 /*
1073  * Try to release processed extent range
1074  *
1075  * May not release the extent range right now if the current range is
1076  * contiguous to processed extent.
1077  *
1078  * Will release processed extent when any of @inode, @uptodate, the range is
1079  * no longer contiguous to the processed range.
1080  *
1081  * Passing @inode == NULL will force processed extent to be released.
1082  */
endio_readpage_release_extent(struct processed_extent * processed,struct btrfs_inode * inode,u64 start,u64 end,bool uptodate)1083 static void endio_readpage_release_extent(struct processed_extent *processed,
1084 			      struct btrfs_inode *inode, u64 start, u64 end,
1085 			      bool uptodate)
1086 {
1087 	struct extent_state *cached = NULL;
1088 	struct extent_io_tree *tree;
1089 
1090 	/* The first extent, initialize @processed */
1091 	if (!processed->inode)
1092 		goto update;
1093 
1094 	/*
1095 	 * Contiguous to processed extent, just uptodate the end.
1096 	 *
1097 	 * Several things to notice:
1098 	 *
1099 	 * - bio can be merged as long as on-disk bytenr is contiguous
1100 	 *   This means we can have page belonging to other inodes, thus need to
1101 	 *   check if the inode still matches.
1102 	 * - bvec can contain range beyond current page for multi-page bvec
1103 	 *   Thus we need to do processed->end + 1 >= start check
1104 	 */
1105 	if (processed->inode == inode && processed->uptodate == uptodate &&
1106 	    processed->end + 1 >= start && end >= processed->end) {
1107 		processed->end = end;
1108 		return;
1109 	}
1110 
1111 	tree = &processed->inode->io_tree;
1112 	/*
1113 	 * Now we don't have range contiguous to the processed range, release
1114 	 * the processed range now.
1115 	 */
1116 	unlock_extent_atomic(tree, processed->start, processed->end, &cached);
1117 
1118 update:
1119 	/* Update processed to current range */
1120 	processed->inode = inode;
1121 	processed->start = start;
1122 	processed->end = end;
1123 	processed->uptodate = uptodate;
1124 }
1125 
begin_page_read(struct btrfs_fs_info * fs_info,struct page * page)1126 static void begin_page_read(struct btrfs_fs_info *fs_info, struct page *page)
1127 {
1128 	ASSERT(PageLocked(page));
1129 	if (!btrfs_is_subpage(fs_info, page))
1130 		return;
1131 
1132 	ASSERT(PagePrivate(page));
1133 	btrfs_subpage_start_reader(fs_info, page, page_offset(page), PAGE_SIZE);
1134 }
1135 
1136 /*
1137  * Find extent buffer for a givne bytenr.
1138  *
1139  * This is for end_bio_extent_readpage(), thus we can't do any unsafe locking
1140  * in endio context.
1141  */
find_extent_buffer_readpage(struct btrfs_fs_info * fs_info,struct page * page,u64 bytenr)1142 static struct extent_buffer *find_extent_buffer_readpage(
1143 		struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
1144 {
1145 	struct extent_buffer *eb;
1146 
1147 	/*
1148 	 * For regular sectorsize, we can use page->private to grab extent
1149 	 * buffer
1150 	 */
1151 	if (fs_info->nodesize >= PAGE_SIZE) {
1152 		ASSERT(PagePrivate(page) && page->private);
1153 		return (struct extent_buffer *)page->private;
1154 	}
1155 
1156 	/* For subpage case, we need to lookup buffer radix tree */
1157 	rcu_read_lock();
1158 	eb = radix_tree_lookup(&fs_info->buffer_radix,
1159 			       bytenr >> fs_info->sectorsize_bits);
1160 	rcu_read_unlock();
1161 	ASSERT(eb);
1162 	return eb;
1163 }
1164 
1165 /*
1166  * after a readpage IO is done, we need to:
1167  * clear the uptodate bits on error
1168  * set the uptodate bits if things worked
1169  * set the page up to date if all extents in the tree are uptodate
1170  * clear the lock bit in the extent tree
1171  * unlock the page if there are no other extents locked for it
1172  *
1173  * Scheduling is not allowed, so the extent state tree is expected
1174  * to have one and only one object corresponding to this IO.
1175  */
end_bio_extent_readpage(struct btrfs_bio * bbio)1176 static void end_bio_extent_readpage(struct btrfs_bio *bbio)
1177 {
1178 	struct bio *bio = &bbio->bio;
1179 	struct bio_vec *bvec;
1180 	struct processed_extent processed = { 0 };
1181 	/*
1182 	 * The offset to the beginning of a bio, since one bio can never be
1183 	 * larger than UINT_MAX, u32 here is enough.
1184 	 */
1185 	u32 bio_offset = 0;
1186 	int mirror;
1187 	struct bvec_iter_all iter_all;
1188 
1189 	ASSERT(!bio_flagged(bio, BIO_CLONED));
1190 	bio_for_each_segment_all(bvec, bio, iter_all) {
1191 		bool uptodate = !bio->bi_status;
1192 		struct page *page = bvec->bv_page;
1193 		struct inode *inode = page->mapping->host;
1194 		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1195 		const u32 sectorsize = fs_info->sectorsize;
1196 		unsigned int error_bitmap = (unsigned int)-1;
1197 		bool repair = false;
1198 		u64 start;
1199 		u64 end;
1200 		u32 len;
1201 
1202 		btrfs_debug(fs_info,
1203 			"end_bio_extent_readpage: bi_sector=%llu, err=%d, mirror=%u",
1204 			bio->bi_iter.bi_sector, bio->bi_status,
1205 			bbio->mirror_num);
1206 
1207 		/*
1208 		 * We always issue full-sector reads, but if some block in a
1209 		 * page fails to read, blk_update_request() will advance
1210 		 * bv_offset and adjust bv_len to compensate.  Print a warning
1211 		 * for unaligned offsets, and an error if they don't add up to
1212 		 * a full sector.
1213 		 */
1214 		if (!IS_ALIGNED(bvec->bv_offset, sectorsize))
1215 			btrfs_err(fs_info,
1216 		"partial page read in btrfs with offset %u and length %u",
1217 				  bvec->bv_offset, bvec->bv_len);
1218 		else if (!IS_ALIGNED(bvec->bv_offset + bvec->bv_len,
1219 				     sectorsize))
1220 			btrfs_info(fs_info,
1221 		"incomplete page read with offset %u and length %u",
1222 				   bvec->bv_offset, bvec->bv_len);
1223 
1224 		start = page_offset(page) + bvec->bv_offset;
1225 		end = start + bvec->bv_len - 1;
1226 		len = bvec->bv_len;
1227 
1228 		mirror = bbio->mirror_num;
1229 		if (likely(uptodate)) {
1230 			if (is_data_inode(inode)) {
1231 				error_bitmap = btrfs_verify_data_csum(bbio,
1232 						bio_offset, page, start, end);
1233 				if (error_bitmap)
1234 					uptodate = false;
1235 			} else {
1236 				if (btrfs_validate_metadata_buffer(bbio,
1237 						page, start, end, mirror))
1238 					uptodate = false;
1239 			}
1240 		}
1241 
1242 		if (likely(uptodate)) {
1243 			loff_t i_size = i_size_read(inode);
1244 			pgoff_t end_index = i_size >> PAGE_SHIFT;
1245 
1246 			btrfs_clean_io_failure(BTRFS_I(inode), start, page, 0);
1247 
1248 			/*
1249 			 * Zero out the remaining part if this range straddles
1250 			 * i_size.
1251 			 *
1252 			 * Here we should only zero the range inside the bvec,
1253 			 * not touch anything else.
1254 			 *
1255 			 * NOTE: i_size is exclusive while end is inclusive.
1256 			 */
1257 			if (page->index == end_index && i_size <= end) {
1258 				u32 zero_start = max(offset_in_page(i_size),
1259 						     offset_in_page(start));
1260 
1261 				zero_user_segment(page, zero_start,
1262 						  offset_in_page(end) + 1);
1263 			}
1264 		} else if (is_data_inode(inode)) {
1265 			/*
1266 			 * Only try to repair bios that actually made it to a
1267 			 * device.  If the bio failed to be submitted mirror
1268 			 * is 0 and we need to fail it without retrying.
1269 			 *
1270 			 * This also includes the high level bios for compressed
1271 			 * extents - these never make it to a device and repair
1272 			 * is already handled on the lower compressed bio.
1273 			 */
1274 			if (mirror > 0)
1275 				repair = true;
1276 		} else {
1277 			struct extent_buffer *eb;
1278 
1279 			eb = find_extent_buffer_readpage(fs_info, page, start);
1280 			set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
1281 			eb->read_mirror = mirror;
1282 			atomic_dec(&eb->io_pages);
1283 		}
1284 
1285 		if (repair) {
1286 			/*
1287 			 * submit_data_read_repair() will handle all the good
1288 			 * and bad sectors, we just continue to the next bvec.
1289 			 */
1290 			submit_data_read_repair(inode, bbio, bio_offset, bvec,
1291 						error_bitmap);
1292 		} else {
1293 			/* Update page status and unlock */
1294 			end_page_read(page, uptodate, start, len);
1295 			endio_readpage_release_extent(&processed, BTRFS_I(inode),
1296 					start, end, PageUptodate(page));
1297 		}
1298 
1299 		ASSERT(bio_offset + len > bio_offset);
1300 		bio_offset += len;
1301 
1302 	}
1303 	/* Release the last extent */
1304 	endio_readpage_release_extent(&processed, NULL, 0, 0, false);
1305 	btrfs_bio_free_csum(bbio);
1306 	bio_put(bio);
1307 }
1308 
1309 /**
1310  * Populate every free slot in a provided array with pages.
1311  *
1312  * @nr_pages:   number of pages to allocate
1313  * @page_array: the array to fill with pages; any existing non-null entries in
1314  * 		the array will be skipped
1315  *
1316  * Return: 0        if all pages were able to be allocated;
1317  *         -ENOMEM  otherwise, and the caller is responsible for freeing all
1318  *                  non-null page pointers in the array.
1319  */
btrfs_alloc_page_array(unsigned int nr_pages,struct page ** page_array)1320 int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array)
1321 {
1322 	unsigned int allocated;
1323 
1324 	for (allocated = 0; allocated < nr_pages;) {
1325 		unsigned int last = allocated;
1326 
1327 		allocated = alloc_pages_bulk_array(GFP_NOFS, nr_pages, page_array);
1328 
1329 		if (allocated == nr_pages)
1330 			return 0;
1331 
1332 		/*
1333 		 * During this iteration, no page could be allocated, even
1334 		 * though alloc_pages_bulk_array() falls back to alloc_page()
1335 		 * if  it could not bulk-allocate. So we must be out of memory.
1336 		 */
1337 		if (allocated == last)
1338 			return -ENOMEM;
1339 
1340 		memalloc_retry_wait(GFP_NOFS);
1341 	}
1342 	return 0;
1343 }
1344 
1345 /**
1346  * Attempt to add a page to bio
1347  *
1348  * @bio_ctrl:	record both the bio, and its bio_flags
1349  * @page:	page to add to the bio
1350  * @disk_bytenr:  offset of the new bio or to check whether we are adding
1351  *                a contiguous page to the previous one
1352  * @size:	portion of page that we want to write
1353  * @pg_offset:	starting offset in the page
1354  * @compress_type:   compression type of the current bio to see if we can merge them
1355  *
1356  * Attempt to add a page to bio considering stripe alignment etc.
1357  *
1358  * Return >= 0 for the number of bytes added to the bio.
1359  * Can return 0 if the current bio is already at stripe/zone boundary.
1360  * Return <0 for error.
1361  */
btrfs_bio_add_page(struct btrfs_bio_ctrl * bio_ctrl,struct page * page,u64 disk_bytenr,unsigned int size,unsigned int pg_offset,enum btrfs_compression_type compress_type)1362 static int btrfs_bio_add_page(struct btrfs_bio_ctrl *bio_ctrl,
1363 			      struct page *page,
1364 			      u64 disk_bytenr, unsigned int size,
1365 			      unsigned int pg_offset,
1366 			      enum btrfs_compression_type compress_type)
1367 {
1368 	struct bio *bio = bio_ctrl->bio;
1369 	u32 bio_size = bio->bi_iter.bi_size;
1370 	u32 real_size;
1371 	const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
1372 	bool contig = false;
1373 	int ret;
1374 
1375 	ASSERT(bio);
1376 	/* The limit should be calculated when bio_ctrl->bio is allocated */
1377 	ASSERT(bio_ctrl->len_to_oe_boundary && bio_ctrl->len_to_stripe_boundary);
1378 	if (bio_ctrl->compress_type != compress_type)
1379 		return 0;
1380 
1381 
1382 	if (bio->bi_iter.bi_size == 0) {
1383 		/* We can always add a page into an empty bio. */
1384 		contig = true;
1385 	} else if (bio_ctrl->compress_type == BTRFS_COMPRESS_NONE) {
1386 		struct bio_vec *bvec = bio_last_bvec_all(bio);
1387 
1388 		/*
1389 		 * The contig check requires the following conditions to be met:
1390 		 * 1) The pages are belonging to the same inode
1391 		 *    This is implied by the call chain.
1392 		 *
1393 		 * 2) The range has adjacent logical bytenr
1394 		 *
1395 		 * 3) The range has adjacent file offset
1396 		 *    This is required for the usage of btrfs_bio->file_offset.
1397 		 */
1398 		if (bio_end_sector(bio) == sector &&
1399 		    page_offset(bvec->bv_page) + bvec->bv_offset +
1400 		    bvec->bv_len == page_offset(page) + pg_offset)
1401 			contig = true;
1402 	} else {
1403 		/*
1404 		 * For compression, all IO should have its logical bytenr
1405 		 * set to the starting bytenr of the compressed extent.
1406 		 */
1407 		contig = bio->bi_iter.bi_sector == sector;
1408 	}
1409 
1410 	if (!contig)
1411 		return 0;
1412 
1413 	real_size = min(bio_ctrl->len_to_oe_boundary,
1414 			bio_ctrl->len_to_stripe_boundary) - bio_size;
1415 	real_size = min(real_size, size);
1416 
1417 	/*
1418 	 * If real_size is 0, never call bio_add_*_page(), as even size is 0,
1419 	 * bio will still execute its endio function on the page!
1420 	 */
1421 	if (real_size == 0)
1422 		return 0;
1423 
1424 	if (bio_op(bio) == REQ_OP_ZONE_APPEND)
1425 		ret = bio_add_zone_append_page(bio, page, real_size, pg_offset);
1426 	else
1427 		ret = bio_add_page(bio, page, real_size, pg_offset);
1428 
1429 	return ret;
1430 }
1431 
calc_bio_boundaries(struct btrfs_bio_ctrl * bio_ctrl,struct btrfs_inode * inode,u64 file_offset)1432 static int calc_bio_boundaries(struct btrfs_bio_ctrl *bio_ctrl,
1433 			       struct btrfs_inode *inode, u64 file_offset)
1434 {
1435 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1436 	struct btrfs_io_geometry geom;
1437 	struct btrfs_ordered_extent *ordered;
1438 	struct extent_map *em;
1439 	u64 logical = (bio_ctrl->bio->bi_iter.bi_sector << SECTOR_SHIFT);
1440 	int ret;
1441 
1442 	/*
1443 	 * Pages for compressed extent are never submitted to disk directly,
1444 	 * thus it has no real boundary, just set them to U32_MAX.
1445 	 *
1446 	 * The split happens for real compressed bio, which happens in
1447 	 * btrfs_submit_compressed_read/write().
1448 	 */
1449 	if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
1450 		bio_ctrl->len_to_oe_boundary = U32_MAX;
1451 		bio_ctrl->len_to_stripe_boundary = U32_MAX;
1452 		return 0;
1453 	}
1454 	em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
1455 	if (IS_ERR(em))
1456 		return PTR_ERR(em);
1457 	ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio_ctrl->bio),
1458 				    logical, &geom);
1459 	free_extent_map(em);
1460 	if (ret < 0) {
1461 		return ret;
1462 	}
1463 	if (geom.len > U32_MAX)
1464 		bio_ctrl->len_to_stripe_boundary = U32_MAX;
1465 	else
1466 		bio_ctrl->len_to_stripe_boundary = (u32)geom.len;
1467 
1468 	if (bio_op(bio_ctrl->bio) != REQ_OP_ZONE_APPEND) {
1469 		bio_ctrl->len_to_oe_boundary = U32_MAX;
1470 		return 0;
1471 	}
1472 
1473 	/* Ordered extent not yet created, so we're good */
1474 	ordered = btrfs_lookup_ordered_extent(inode, file_offset);
1475 	if (!ordered) {
1476 		bio_ctrl->len_to_oe_boundary = U32_MAX;
1477 		return 0;
1478 	}
1479 
1480 	bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
1481 		ordered->disk_bytenr + ordered->disk_num_bytes - logical);
1482 	btrfs_put_ordered_extent(ordered);
1483 	return 0;
1484 }
1485 
alloc_new_bio(struct btrfs_inode * inode,struct btrfs_bio_ctrl * bio_ctrl,struct writeback_control * wbc,blk_opf_t opf,u64 disk_bytenr,u32 offset,u64 file_offset,enum btrfs_compression_type compress_type)1486 static int alloc_new_bio(struct btrfs_inode *inode,
1487 			 struct btrfs_bio_ctrl *bio_ctrl,
1488 			 struct writeback_control *wbc,
1489 			 blk_opf_t opf,
1490 			 u64 disk_bytenr, u32 offset, u64 file_offset,
1491 			 enum btrfs_compression_type compress_type)
1492 {
1493 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1494 	struct bio *bio;
1495 	int ret;
1496 
1497 	ASSERT(bio_ctrl->end_io_func);
1498 
1499 	bio = btrfs_bio_alloc(BIO_MAX_VECS, opf, bio_ctrl->end_io_func, NULL);
1500 	/*
1501 	 * For compressed page range, its disk_bytenr is always @disk_bytenr
1502 	 * passed in, no matter if we have added any range into previous bio.
1503 	 */
1504 	if (compress_type != BTRFS_COMPRESS_NONE)
1505 		bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
1506 	else
1507 		bio->bi_iter.bi_sector = (disk_bytenr + offset) >> SECTOR_SHIFT;
1508 	bio_ctrl->bio = bio;
1509 	bio_ctrl->compress_type = compress_type;
1510 	ret = calc_bio_boundaries(bio_ctrl, inode, file_offset);
1511 	if (ret < 0)
1512 		goto error;
1513 
1514 	if (wbc) {
1515 		/*
1516 		 * For Zone append we need the correct block_device that we are
1517 		 * going to write to set in the bio to be able to respect the
1518 		 * hardware limitation.  Look it up here:
1519 		 */
1520 		if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
1521 			struct btrfs_device *dev;
1522 
1523 			dev = btrfs_zoned_get_device(fs_info, disk_bytenr,
1524 						     fs_info->sectorsize);
1525 			if (IS_ERR(dev)) {
1526 				ret = PTR_ERR(dev);
1527 				goto error;
1528 			}
1529 
1530 			bio_set_dev(bio, dev->bdev);
1531 		} else {
1532 			/*
1533 			 * Otherwise pick the last added device to support
1534 			 * cgroup writeback.  For multi-device file systems this
1535 			 * means blk-cgroup policies have to always be set on the
1536 			 * last added/replaced device.  This is a bit odd but has
1537 			 * been like that for a long time.
1538 			 */
1539 			bio_set_dev(bio, fs_info->fs_devices->latest_dev->bdev);
1540 		}
1541 		wbc_init_bio(wbc, bio);
1542 	} else {
1543 		ASSERT(bio_op(bio) != REQ_OP_ZONE_APPEND);
1544 	}
1545 	return 0;
1546 error:
1547 	bio_ctrl->bio = NULL;
1548 	btrfs_bio_end_io(btrfs_bio(bio), errno_to_blk_status(ret));
1549 	return ret;
1550 }
1551 
1552 /*
1553  * @opf:	bio REQ_OP_* and REQ_* flags as one value
1554  * @wbc:	optional writeback control for io accounting
1555  * @disk_bytenr: logical bytenr where the write will be
1556  * @page:	page to add to the bio
1557  * @size:	portion of page that we want to write to
1558  * @pg_offset:	offset of the new bio or to check whether we are adding
1559  *              a contiguous page to the previous one
1560  * @compress_type:   compress type for current bio
1561  *
1562  * The will either add the page into the existing @bio_ctrl->bio, or allocate a
1563  * new one in @bio_ctrl->bio.
1564  * The mirror number for this IO should already be initizlied in
1565  * @bio_ctrl->mirror_num.
1566  */
submit_extent_page(blk_opf_t opf,struct writeback_control * wbc,struct btrfs_bio_ctrl * bio_ctrl,u64 disk_bytenr,struct page * page,size_t size,unsigned long pg_offset,enum btrfs_compression_type compress_type,bool force_bio_submit)1567 static int submit_extent_page(blk_opf_t opf,
1568 			      struct writeback_control *wbc,
1569 			      struct btrfs_bio_ctrl *bio_ctrl,
1570 			      u64 disk_bytenr, struct page *page,
1571 			      size_t size, unsigned long pg_offset,
1572 			      enum btrfs_compression_type compress_type,
1573 			      bool force_bio_submit)
1574 {
1575 	int ret = 0;
1576 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1577 	unsigned int cur = pg_offset;
1578 
1579 	ASSERT(bio_ctrl);
1580 
1581 	ASSERT(pg_offset < PAGE_SIZE && size <= PAGE_SIZE &&
1582 	       pg_offset + size <= PAGE_SIZE);
1583 
1584 	ASSERT(bio_ctrl->end_io_func);
1585 
1586 	if (force_bio_submit)
1587 		submit_one_bio(bio_ctrl);
1588 
1589 	while (cur < pg_offset + size) {
1590 		u32 offset = cur - pg_offset;
1591 		int added;
1592 
1593 		/* Allocate new bio if needed */
1594 		if (!bio_ctrl->bio) {
1595 			ret = alloc_new_bio(inode, bio_ctrl, wbc, opf,
1596 					    disk_bytenr, offset,
1597 					    page_offset(page) + cur,
1598 					    compress_type);
1599 			if (ret < 0)
1600 				return ret;
1601 		}
1602 		/*
1603 		 * We must go through btrfs_bio_add_page() to ensure each
1604 		 * page range won't cross various boundaries.
1605 		 */
1606 		if (compress_type != BTRFS_COMPRESS_NONE)
1607 			added = btrfs_bio_add_page(bio_ctrl, page, disk_bytenr,
1608 					size - offset, pg_offset + offset,
1609 					compress_type);
1610 		else
1611 			added = btrfs_bio_add_page(bio_ctrl, page,
1612 					disk_bytenr + offset, size - offset,
1613 					pg_offset + offset, compress_type);
1614 
1615 		/* Metadata page range should never be split */
1616 		if (!is_data_inode(&inode->vfs_inode))
1617 			ASSERT(added == 0 || added == size - offset);
1618 
1619 		/* At least we added some page, update the account */
1620 		if (wbc && added)
1621 			wbc_account_cgroup_owner(wbc, page, added);
1622 
1623 		/* We have reached boundary, submit right now */
1624 		if (added < size - offset) {
1625 			/* The bio should contain some page(s) */
1626 			ASSERT(bio_ctrl->bio->bi_iter.bi_size);
1627 			submit_one_bio(bio_ctrl);
1628 		}
1629 		cur += added;
1630 	}
1631 	return 0;
1632 }
1633 
attach_extent_buffer_page(struct extent_buffer * eb,struct page * page,struct btrfs_subpage * prealloc)1634 static int attach_extent_buffer_page(struct extent_buffer *eb,
1635 				     struct page *page,
1636 				     struct btrfs_subpage *prealloc)
1637 {
1638 	struct btrfs_fs_info *fs_info = eb->fs_info;
1639 	int ret = 0;
1640 
1641 	/*
1642 	 * If the page is mapped to btree inode, we should hold the private
1643 	 * lock to prevent race.
1644 	 * For cloned or dummy extent buffers, their pages are not mapped and
1645 	 * will not race with any other ebs.
1646 	 */
1647 	if (page->mapping)
1648 		lockdep_assert_held(&page->mapping->private_lock);
1649 
1650 	if (fs_info->nodesize >= PAGE_SIZE) {
1651 		if (!PagePrivate(page))
1652 			attach_page_private(page, eb);
1653 		else
1654 			WARN_ON(page->private != (unsigned long)eb);
1655 		return 0;
1656 	}
1657 
1658 	/* Already mapped, just free prealloc */
1659 	if (PagePrivate(page)) {
1660 		btrfs_free_subpage(prealloc);
1661 		return 0;
1662 	}
1663 
1664 	if (prealloc)
1665 		/* Has preallocated memory for subpage */
1666 		attach_page_private(page, prealloc);
1667 	else
1668 		/* Do new allocation to attach subpage */
1669 		ret = btrfs_attach_subpage(fs_info, page,
1670 					   BTRFS_SUBPAGE_METADATA);
1671 	return ret;
1672 }
1673 
set_page_extent_mapped(struct page * page)1674 int set_page_extent_mapped(struct page *page)
1675 {
1676 	struct btrfs_fs_info *fs_info;
1677 
1678 	ASSERT(page->mapping);
1679 
1680 	if (PagePrivate(page))
1681 		return 0;
1682 
1683 	fs_info = btrfs_sb(page->mapping->host->i_sb);
1684 
1685 	if (btrfs_is_subpage(fs_info, page))
1686 		return btrfs_attach_subpage(fs_info, page, BTRFS_SUBPAGE_DATA);
1687 
1688 	attach_page_private(page, (void *)EXTENT_PAGE_PRIVATE);
1689 	return 0;
1690 }
1691 
clear_page_extent_mapped(struct page * page)1692 void clear_page_extent_mapped(struct page *page)
1693 {
1694 	struct btrfs_fs_info *fs_info;
1695 
1696 	ASSERT(page->mapping);
1697 
1698 	if (!PagePrivate(page))
1699 		return;
1700 
1701 	fs_info = btrfs_sb(page->mapping->host->i_sb);
1702 	if (btrfs_is_subpage(fs_info, page))
1703 		return btrfs_detach_subpage(fs_info, page);
1704 
1705 	detach_page_private(page);
1706 }
1707 
1708 static struct extent_map *
__get_extent_map(struct inode * inode,struct page * page,size_t pg_offset,u64 start,u64 len,struct extent_map ** em_cached)1709 __get_extent_map(struct inode *inode, struct page *page, size_t pg_offset,
1710 		 u64 start, u64 len, struct extent_map **em_cached)
1711 {
1712 	struct extent_map *em;
1713 
1714 	if (em_cached && *em_cached) {
1715 		em = *em_cached;
1716 		if (extent_map_in_tree(em) && start >= em->start &&
1717 		    start < extent_map_end(em)) {
1718 			refcount_inc(&em->refs);
1719 			return em;
1720 		}
1721 
1722 		free_extent_map(em);
1723 		*em_cached = NULL;
1724 	}
1725 
1726 	em = btrfs_get_extent(BTRFS_I(inode), page, pg_offset, start, len);
1727 	if (em_cached && !IS_ERR(em)) {
1728 		BUG_ON(*em_cached);
1729 		refcount_inc(&em->refs);
1730 		*em_cached = em;
1731 	}
1732 	return em;
1733 }
1734 /*
1735  * basic readpage implementation.  Locked extent state structs are inserted
1736  * into the tree that are removed when the IO is done (by the end_io
1737  * handlers)
1738  * XXX JDM: This needs looking at to ensure proper page locking
1739  * return 0 on success, otherwise return error
1740  */
btrfs_do_readpage(struct page * page,struct extent_map ** em_cached,struct btrfs_bio_ctrl * bio_ctrl,blk_opf_t read_flags,u64 * prev_em_start)1741 static int btrfs_do_readpage(struct page *page, struct extent_map **em_cached,
1742 		      struct btrfs_bio_ctrl *bio_ctrl,
1743 		      blk_opf_t read_flags, u64 *prev_em_start)
1744 {
1745 	struct inode *inode = page->mapping->host;
1746 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1747 	u64 start = page_offset(page);
1748 	const u64 end = start + PAGE_SIZE - 1;
1749 	u64 cur = start;
1750 	u64 extent_offset;
1751 	u64 last_byte = i_size_read(inode);
1752 	u64 block_start;
1753 	struct extent_map *em;
1754 	int ret = 0;
1755 	size_t pg_offset = 0;
1756 	size_t iosize;
1757 	size_t blocksize = inode->i_sb->s_blocksize;
1758 	struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
1759 
1760 	ret = set_page_extent_mapped(page);
1761 	if (ret < 0) {
1762 		unlock_extent(tree, start, end, NULL);
1763 		btrfs_page_set_error(fs_info, page, start, PAGE_SIZE);
1764 		unlock_page(page);
1765 		goto out;
1766 	}
1767 
1768 	if (!PageUptodate(page)) {
1769 		if (cleancache_get_page(page) == 0) {
1770 			BUG_ON(blocksize != PAGE_SIZE);
1771 			unlock_extent(tree, start, end, NULL);
1772 			unlock_page(page);
1773 			goto out;
1774 		}
1775 	}
1776 
1777 	if (page->index == last_byte >> PAGE_SHIFT) {
1778 		size_t zero_offset = offset_in_page(last_byte);
1779 
1780 		if (zero_offset) {
1781 			iosize = PAGE_SIZE - zero_offset;
1782 			memzero_page(page, zero_offset, iosize);
1783 		}
1784 	}
1785 	bio_ctrl->end_io_func = end_bio_extent_readpage;
1786 	begin_page_read(fs_info, page);
1787 	while (cur <= end) {
1788 		unsigned long this_bio_flag = 0;
1789 		bool force_bio_submit = false;
1790 		u64 disk_bytenr;
1791 
1792 		ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
1793 		if (cur >= last_byte) {
1794 			struct extent_state *cached = NULL;
1795 
1796 			iosize = PAGE_SIZE - pg_offset;
1797 			memzero_page(page, pg_offset, iosize);
1798 			set_extent_uptodate(tree, cur, cur + iosize - 1,
1799 					    &cached, GFP_NOFS);
1800 			unlock_extent(tree, cur, cur + iosize - 1, &cached);
1801 			end_page_read(page, true, cur, iosize);
1802 			break;
1803 		}
1804 		em = __get_extent_map(inode, page, pg_offset, cur,
1805 				      end - cur + 1, em_cached);
1806 		if (IS_ERR(em)) {
1807 			unlock_extent(tree, cur, end, NULL);
1808 			end_page_read(page, false, cur, end + 1 - cur);
1809 			ret = PTR_ERR(em);
1810 			break;
1811 		}
1812 		extent_offset = cur - em->start;
1813 		BUG_ON(extent_map_end(em) <= cur);
1814 		BUG_ON(end < cur);
1815 
1816 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
1817 			this_bio_flag = em->compress_type;
1818 
1819 		iosize = min(extent_map_end(em) - cur, end - cur + 1);
1820 		iosize = ALIGN(iosize, blocksize);
1821 		if (this_bio_flag != BTRFS_COMPRESS_NONE)
1822 			disk_bytenr = em->block_start;
1823 		else
1824 			disk_bytenr = em->block_start + extent_offset;
1825 		block_start = em->block_start;
1826 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
1827 			block_start = EXTENT_MAP_HOLE;
1828 
1829 		/*
1830 		 * If we have a file range that points to a compressed extent
1831 		 * and it's followed by a consecutive file range that points
1832 		 * to the same compressed extent (possibly with a different
1833 		 * offset and/or length, so it either points to the whole extent
1834 		 * or only part of it), we must make sure we do not submit a
1835 		 * single bio to populate the pages for the 2 ranges because
1836 		 * this makes the compressed extent read zero out the pages
1837 		 * belonging to the 2nd range. Imagine the following scenario:
1838 		 *
1839 		 *  File layout
1840 		 *  [0 - 8K]                     [8K - 24K]
1841 		 *    |                               |
1842 		 *    |                               |
1843 		 * points to extent X,         points to extent X,
1844 		 * offset 4K, length of 8K     offset 0, length 16K
1845 		 *
1846 		 * [extent X, compressed length = 4K uncompressed length = 16K]
1847 		 *
1848 		 * If the bio to read the compressed extent covers both ranges,
1849 		 * it will decompress extent X into the pages belonging to the
1850 		 * first range and then it will stop, zeroing out the remaining
1851 		 * pages that belong to the other range that points to extent X.
1852 		 * So here we make sure we submit 2 bios, one for the first
1853 		 * range and another one for the third range. Both will target
1854 		 * the same physical extent from disk, but we can't currently
1855 		 * make the compressed bio endio callback populate the pages
1856 		 * for both ranges because each compressed bio is tightly
1857 		 * coupled with a single extent map, and each range can have
1858 		 * an extent map with a different offset value relative to the
1859 		 * uncompressed data of our extent and different lengths. This
1860 		 * is a corner case so we prioritize correctness over
1861 		 * non-optimal behavior (submitting 2 bios for the same extent).
1862 		 */
1863 		if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) &&
1864 		    prev_em_start && *prev_em_start != (u64)-1 &&
1865 		    *prev_em_start != em->start)
1866 			force_bio_submit = true;
1867 
1868 		if (prev_em_start)
1869 			*prev_em_start = em->start;
1870 
1871 		free_extent_map(em);
1872 		em = NULL;
1873 
1874 		/* we've found a hole, just zero and go on */
1875 		if (block_start == EXTENT_MAP_HOLE) {
1876 			struct extent_state *cached = NULL;
1877 
1878 			memzero_page(page, pg_offset, iosize);
1879 
1880 			set_extent_uptodate(tree, cur, cur + iosize - 1,
1881 					    &cached, GFP_NOFS);
1882 			unlock_extent(tree, cur, cur + iosize - 1, &cached);
1883 			end_page_read(page, true, cur, iosize);
1884 			cur = cur + iosize;
1885 			pg_offset += iosize;
1886 			continue;
1887 		}
1888 		/* the get_extent function already copied into the page */
1889 		if (block_start == EXTENT_MAP_INLINE) {
1890 			unlock_extent(tree, cur, cur + iosize - 1, NULL);
1891 			end_page_read(page, true, cur, iosize);
1892 			cur = cur + iosize;
1893 			pg_offset += iosize;
1894 			continue;
1895 		}
1896 
1897 		ret = submit_extent_page(REQ_OP_READ | read_flags, NULL,
1898 					 bio_ctrl, disk_bytenr, page, iosize,
1899 					 pg_offset, this_bio_flag,
1900 					 force_bio_submit);
1901 		if (ret) {
1902 			/*
1903 			 * We have to unlock the remaining range, or the page
1904 			 * will never be unlocked.
1905 			 */
1906 			unlock_extent(tree, cur, end, NULL);
1907 			end_page_read(page, false, cur, end + 1 - cur);
1908 			goto out;
1909 		}
1910 		cur = cur + iosize;
1911 		pg_offset += iosize;
1912 	}
1913 out:
1914 	return ret;
1915 }
1916 
btrfs_read_folio(struct file * file,struct folio * folio)1917 int btrfs_read_folio(struct file *file, struct folio *folio)
1918 {
1919 	struct page *page = &folio->page;
1920 	struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
1921 	u64 start = page_offset(page);
1922 	u64 end = start + PAGE_SIZE - 1;
1923 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
1924 	int ret;
1925 
1926 	btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1927 
1928 	ret = btrfs_do_readpage(page, NULL, &bio_ctrl, 0, NULL);
1929 	/*
1930 	 * If btrfs_do_readpage() failed we will want to submit the assembled
1931 	 * bio to do the cleanup.
1932 	 */
1933 	submit_one_bio(&bio_ctrl);
1934 	return ret;
1935 }
1936 
contiguous_readpages(struct page * pages[],int nr_pages,u64 start,u64 end,struct extent_map ** em_cached,struct btrfs_bio_ctrl * bio_ctrl,u64 * prev_em_start)1937 static inline void contiguous_readpages(struct page *pages[], int nr_pages,
1938 					u64 start, u64 end,
1939 					struct extent_map **em_cached,
1940 					struct btrfs_bio_ctrl *bio_ctrl,
1941 					u64 *prev_em_start)
1942 {
1943 	struct btrfs_inode *inode = BTRFS_I(pages[0]->mapping->host);
1944 	int index;
1945 
1946 	btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
1947 
1948 	for (index = 0; index < nr_pages; index++) {
1949 		btrfs_do_readpage(pages[index], em_cached, bio_ctrl,
1950 				  REQ_RAHEAD, prev_em_start);
1951 		put_page(pages[index]);
1952 	}
1953 }
1954 
1955 /*
1956  * helper for __extent_writepage, doing all of the delayed allocation setup.
1957  *
1958  * This returns 1 if btrfs_run_delalloc_range function did all the work required
1959  * to write the page (copy into inline extent).  In this case the IO has
1960  * been started and the page is already unlocked.
1961  *
1962  * This returns 0 if all went well (page still locked)
1963  * This returns < 0 if there were errors (page still locked)
1964  */
writepage_delalloc(struct btrfs_inode * inode,struct page * page,struct writeback_control * wbc)1965 static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
1966 		struct page *page, struct writeback_control *wbc)
1967 {
1968 	const u64 page_end = page_offset(page) + PAGE_SIZE - 1;
1969 	u64 delalloc_start = page_offset(page);
1970 	u64 delalloc_to_write = 0;
1971 	/* How many pages are started by btrfs_run_delalloc_range() */
1972 	unsigned long nr_written = 0;
1973 	int ret;
1974 	int page_started = 0;
1975 
1976 	while (delalloc_start < page_end) {
1977 		u64 delalloc_end = page_end;
1978 		bool found;
1979 
1980 		found = find_lock_delalloc_range(&inode->vfs_inode, page,
1981 					       &delalloc_start,
1982 					       &delalloc_end);
1983 		if (!found) {
1984 			delalloc_start = delalloc_end + 1;
1985 			continue;
1986 		}
1987 		ret = btrfs_run_delalloc_range(inode, page, delalloc_start,
1988 				delalloc_end, &page_started, &nr_written, wbc);
1989 		if (ret) {
1990 			btrfs_page_set_error(inode->root->fs_info, page,
1991 					     page_offset(page), PAGE_SIZE);
1992 			return ret;
1993 		}
1994 		/*
1995 		 * delalloc_end is already one less than the total length, so
1996 		 * we don't subtract one from PAGE_SIZE
1997 		 */
1998 		delalloc_to_write += (delalloc_end - delalloc_start +
1999 				      PAGE_SIZE) >> PAGE_SHIFT;
2000 		delalloc_start = delalloc_end + 1;
2001 	}
2002 	if (wbc->nr_to_write < delalloc_to_write) {
2003 		int thresh = 8192;
2004 
2005 		if (delalloc_to_write < thresh * 2)
2006 			thresh = delalloc_to_write;
2007 		wbc->nr_to_write = min_t(u64, delalloc_to_write,
2008 					 thresh);
2009 	}
2010 
2011 	/* Did btrfs_run_dealloc_range() already unlock and start the IO? */
2012 	if (page_started) {
2013 		/*
2014 		 * We've unlocked the page, so we can't update the mapping's
2015 		 * writeback index, just update nr_to_write.
2016 		 */
2017 		wbc->nr_to_write -= nr_written;
2018 		return 1;
2019 	}
2020 
2021 	return 0;
2022 }
2023 
2024 /*
2025  * Find the first byte we need to write.
2026  *
2027  * For subpage, one page can contain several sectors, and
2028  * __extent_writepage_io() will just grab all extent maps in the page
2029  * range and try to submit all non-inline/non-compressed extents.
2030  *
2031  * This is a big problem for subpage, we shouldn't re-submit already written
2032  * data at all.
2033  * This function will lookup subpage dirty bit to find which range we really
2034  * need to submit.
2035  *
2036  * Return the next dirty range in [@start, @end).
2037  * If no dirty range is found, @start will be page_offset(page) + PAGE_SIZE.
2038  */
find_next_dirty_byte(struct btrfs_fs_info * fs_info,struct page * page,u64 * start,u64 * end)2039 static void find_next_dirty_byte(struct btrfs_fs_info *fs_info,
2040 				 struct page *page, u64 *start, u64 *end)
2041 {
2042 	struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2043 	struct btrfs_subpage_info *spi = fs_info->subpage_info;
2044 	u64 orig_start = *start;
2045 	/* Declare as unsigned long so we can use bitmap ops */
2046 	unsigned long flags;
2047 	int range_start_bit;
2048 	int range_end_bit;
2049 
2050 	/*
2051 	 * For regular sector size == page size case, since one page only
2052 	 * contains one sector, we return the page offset directly.
2053 	 */
2054 	if (!btrfs_is_subpage(fs_info, page)) {
2055 		*start = page_offset(page);
2056 		*end = page_offset(page) + PAGE_SIZE;
2057 		return;
2058 	}
2059 
2060 	range_start_bit = spi->dirty_offset +
2061 			  (offset_in_page(orig_start) >> fs_info->sectorsize_bits);
2062 
2063 	/* We should have the page locked, but just in case */
2064 	spin_lock_irqsave(&subpage->lock, flags);
2065 	bitmap_next_set_region(subpage->bitmaps, &range_start_bit, &range_end_bit,
2066 			       spi->dirty_offset + spi->bitmap_nr_bits);
2067 	spin_unlock_irqrestore(&subpage->lock, flags);
2068 
2069 	range_start_bit -= spi->dirty_offset;
2070 	range_end_bit -= spi->dirty_offset;
2071 
2072 	*start = page_offset(page) + range_start_bit * fs_info->sectorsize;
2073 	*end = page_offset(page) + range_end_bit * fs_info->sectorsize;
2074 }
2075 
2076 /*
2077  * helper for __extent_writepage.  This calls the writepage start hooks,
2078  * and does the loop to map the page into extents and bios.
2079  *
2080  * We return 1 if the IO is started and the page is unlocked,
2081  * 0 if all went well (page still locked)
2082  * < 0 if there were errors (page still locked)
2083  */
__extent_writepage_io(struct btrfs_inode * inode,struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,loff_t i_size,int * nr_ret)2084 static noinline_for_stack int __extent_writepage_io(struct btrfs_inode *inode,
2085 				 struct page *page,
2086 				 struct writeback_control *wbc,
2087 				 struct extent_page_data *epd,
2088 				 loff_t i_size,
2089 				 int *nr_ret)
2090 {
2091 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2092 	u64 cur = page_offset(page);
2093 	u64 end = cur + PAGE_SIZE - 1;
2094 	u64 extent_offset;
2095 	u64 block_start;
2096 	struct extent_map *em;
2097 	int saved_ret = 0;
2098 	int ret = 0;
2099 	int nr = 0;
2100 	enum req_op op = REQ_OP_WRITE;
2101 	const blk_opf_t write_flags = wbc_to_write_flags(wbc);
2102 	bool has_error = false;
2103 	bool compressed;
2104 
2105 	ret = btrfs_writepage_cow_fixup(page);
2106 	if (ret) {
2107 		/* Fixup worker will requeue */
2108 		redirty_page_for_writepage(wbc, page);
2109 		unlock_page(page);
2110 		return 1;
2111 	}
2112 
2113 	/*
2114 	 * we don't want to touch the inode after unlocking the page,
2115 	 * so we update the mapping writeback index now
2116 	 */
2117 	wbc->nr_to_write--;
2118 
2119 	epd->bio_ctrl.end_io_func = end_bio_extent_writepage;
2120 	while (cur <= end) {
2121 		u64 disk_bytenr;
2122 		u64 em_end;
2123 		u64 dirty_range_start = cur;
2124 		u64 dirty_range_end;
2125 		u32 iosize;
2126 
2127 		if (cur >= i_size) {
2128 			btrfs_writepage_endio_finish_ordered(inode, page, cur,
2129 							     end, true);
2130 			/*
2131 			 * This range is beyond i_size, thus we don't need to
2132 			 * bother writing back.
2133 			 * But we still need to clear the dirty subpage bit, or
2134 			 * the next time the page gets dirtied, we will try to
2135 			 * writeback the sectors with subpage dirty bits,
2136 			 * causing writeback without ordered extent.
2137 			 */
2138 			btrfs_page_clear_dirty(fs_info, page, cur, end + 1 - cur);
2139 			break;
2140 		}
2141 
2142 		find_next_dirty_byte(fs_info, page, &dirty_range_start,
2143 				     &dirty_range_end);
2144 		if (cur < dirty_range_start) {
2145 			cur = dirty_range_start;
2146 			continue;
2147 		}
2148 
2149 		em = btrfs_get_extent(inode, NULL, 0, cur, end - cur + 1);
2150 		if (IS_ERR(em)) {
2151 			btrfs_page_set_error(fs_info, page, cur, end - cur + 1);
2152 			ret = PTR_ERR_OR_ZERO(em);
2153 			has_error = true;
2154 			if (!saved_ret)
2155 				saved_ret = ret;
2156 			break;
2157 		}
2158 
2159 		extent_offset = cur - em->start;
2160 		em_end = extent_map_end(em);
2161 		ASSERT(cur <= em_end);
2162 		ASSERT(cur < end);
2163 		ASSERT(IS_ALIGNED(em->start, fs_info->sectorsize));
2164 		ASSERT(IS_ALIGNED(em->len, fs_info->sectorsize));
2165 		block_start = em->block_start;
2166 		compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
2167 		disk_bytenr = em->block_start + extent_offset;
2168 
2169 		/*
2170 		 * Note that em_end from extent_map_end() and dirty_range_end from
2171 		 * find_next_dirty_byte() are all exclusive
2172 		 */
2173 		iosize = min(min(em_end, end + 1), dirty_range_end) - cur;
2174 
2175 		if (btrfs_use_zone_append(inode, em->block_start))
2176 			op = REQ_OP_ZONE_APPEND;
2177 
2178 		free_extent_map(em);
2179 		em = NULL;
2180 
2181 		/*
2182 		 * compressed and inline extents are written through other
2183 		 * paths in the FS
2184 		 */
2185 		if (compressed || block_start == EXTENT_MAP_HOLE ||
2186 		    block_start == EXTENT_MAP_INLINE) {
2187 			if (compressed)
2188 				nr++;
2189 			else
2190 				btrfs_writepage_endio_finish_ordered(inode,
2191 						page, cur, cur + iosize - 1, true);
2192 			btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2193 			cur += iosize;
2194 			continue;
2195 		}
2196 
2197 		btrfs_set_range_writeback(inode, cur, cur + iosize - 1);
2198 		if (!PageWriteback(page)) {
2199 			btrfs_err(inode->root->fs_info,
2200 				   "page %lu not writeback, cur %llu end %llu",
2201 			       page->index, cur, end);
2202 		}
2203 
2204 		/*
2205 		 * Although the PageDirty bit is cleared before entering this
2206 		 * function, subpage dirty bit is not cleared.
2207 		 * So clear subpage dirty bit here so next time we won't submit
2208 		 * page for range already written to disk.
2209 		 */
2210 		btrfs_page_clear_dirty(fs_info, page, cur, iosize);
2211 
2212 		ret = submit_extent_page(op | write_flags, wbc,
2213 					 &epd->bio_ctrl, disk_bytenr,
2214 					 page, iosize,
2215 					 cur - page_offset(page),
2216 					 0, false);
2217 		if (ret) {
2218 			has_error = true;
2219 			if (!saved_ret)
2220 				saved_ret = ret;
2221 
2222 			btrfs_page_set_error(fs_info, page, cur, iosize);
2223 			if (PageWriteback(page))
2224 				btrfs_page_clear_writeback(fs_info, page, cur,
2225 							   iosize);
2226 		}
2227 
2228 		cur += iosize;
2229 		nr++;
2230 	}
2231 	/*
2232 	 * If we finish without problem, we should not only clear page dirty,
2233 	 * but also empty subpage dirty bits
2234 	 */
2235 	if (!has_error)
2236 		btrfs_page_assert_not_dirty(fs_info, page);
2237 	else
2238 		ret = saved_ret;
2239 	*nr_ret = nr;
2240 	return ret;
2241 }
2242 
2243 /*
2244  * the writepage semantics are similar to regular writepage.  extent
2245  * records are inserted to lock ranges in the tree, and as dirty areas
2246  * are found, they are marked writeback.  Then the lock bits are removed
2247  * and the end_io handler clears the writeback ranges
2248  *
2249  * Return 0 if everything goes well.
2250  * Return <0 for error.
2251  */
__extent_writepage(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd)2252 static int __extent_writepage(struct page *page, struct writeback_control *wbc,
2253 			      struct extent_page_data *epd)
2254 {
2255 	struct folio *folio = page_folio(page);
2256 	struct inode *inode = page->mapping->host;
2257 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2258 	const u64 page_start = page_offset(page);
2259 	const u64 page_end = page_start + PAGE_SIZE - 1;
2260 	int ret;
2261 	int nr = 0;
2262 	size_t pg_offset;
2263 	loff_t i_size = i_size_read(inode);
2264 	unsigned long end_index = i_size >> PAGE_SHIFT;
2265 
2266 	trace___extent_writepage(page, inode, wbc);
2267 
2268 	WARN_ON(!PageLocked(page));
2269 
2270 	btrfs_page_clear_error(btrfs_sb(inode->i_sb), page,
2271 			       page_offset(page), PAGE_SIZE);
2272 
2273 	pg_offset = offset_in_page(i_size);
2274 	if (page->index > end_index ||
2275 	   (page->index == end_index && !pg_offset)) {
2276 		folio_invalidate(folio, 0, folio_size(folio));
2277 		folio_unlock(folio);
2278 		return 0;
2279 	}
2280 
2281 	if (page->index == end_index)
2282 		memzero_page(page, pg_offset, PAGE_SIZE - pg_offset);
2283 
2284 	ret = set_page_extent_mapped(page);
2285 	if (ret < 0) {
2286 		SetPageError(page);
2287 		goto done;
2288 	}
2289 
2290 	if (!epd->extent_locked) {
2291 		ret = writepage_delalloc(BTRFS_I(inode), page, wbc);
2292 		if (ret == 1)
2293 			return 0;
2294 		if (ret)
2295 			goto done;
2296 	}
2297 
2298 	ret = __extent_writepage_io(BTRFS_I(inode), page, wbc, epd, i_size,
2299 				    &nr);
2300 	if (ret == 1)
2301 		return 0;
2302 
2303 done:
2304 	if (nr == 0) {
2305 		/* make sure the mapping tag for page dirty gets cleared */
2306 		set_page_writeback(page);
2307 		end_page_writeback(page);
2308 	}
2309 	/*
2310 	 * Here we used to have a check for PageError() and then set @ret and
2311 	 * call end_extent_writepage().
2312 	 *
2313 	 * But in fact setting @ret here will cause different error paths
2314 	 * between subpage and regular sectorsize.
2315 	 *
2316 	 * For regular page size, we never submit current page, but only add
2317 	 * current page to current bio.
2318 	 * The bio submission can only happen in next page.
2319 	 * Thus if we hit the PageError() branch, @ret is already set to
2320 	 * non-zero value and will not get updated for regular sectorsize.
2321 	 *
2322 	 * But for subpage case, it's possible we submit part of current page,
2323 	 * thus can get PageError() set by submitted bio of the same page,
2324 	 * while our @ret is still 0.
2325 	 *
2326 	 * So here we unify the behavior and don't set @ret.
2327 	 * Error can still be properly passed to higher layer as page will
2328 	 * be set error, here we just don't handle the IO failure.
2329 	 *
2330 	 * NOTE: This is just a hotfix for subpage.
2331 	 * The root fix will be properly ending ordered extent when we hit
2332 	 * an error during writeback.
2333 	 *
2334 	 * But that needs a bigger refactoring, as we not only need to grab the
2335 	 * submitted OE, but also need to know exactly at which bytenr we hit
2336 	 * the error.
2337 	 * Currently the full page based __extent_writepage_io() is not
2338 	 * capable of that.
2339 	 */
2340 	if (PageError(page))
2341 		end_extent_writepage(page, ret, page_start, page_end);
2342 	if (epd->extent_locked) {
2343 		/*
2344 		 * If epd->extent_locked, it's from extent_write_locked_range(),
2345 		 * the page can either be locked by lock_page() or
2346 		 * process_one_page().
2347 		 * Let btrfs_page_unlock_writer() handle both cases.
2348 		 */
2349 		ASSERT(wbc);
2350 		btrfs_page_unlock_writer(fs_info, page, wbc->range_start,
2351 					 wbc->range_end + 1 - wbc->range_start);
2352 	} else {
2353 		unlock_page(page);
2354 	}
2355 	ASSERT(ret <= 0);
2356 	return ret;
2357 }
2358 
wait_on_extent_buffer_writeback(struct extent_buffer * eb)2359 void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
2360 {
2361 	wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
2362 		       TASK_UNINTERRUPTIBLE);
2363 }
2364 
end_extent_buffer_writeback(struct extent_buffer * eb)2365 static void end_extent_buffer_writeback(struct extent_buffer *eb)
2366 {
2367 	clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2368 	smp_mb__after_atomic();
2369 	wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
2370 }
2371 
2372 /*
2373  * Lock extent buffer status and pages for writeback.
2374  *
2375  * May try to flush write bio if we can't get the lock.
2376  *
2377  * Return  0 if the extent buffer doesn't need to be submitted.
2378  *           (E.g. the extent buffer is not dirty)
2379  * Return >0 is the extent buffer is submitted to bio.
2380  * Return <0 if something went wrong, no page is locked.
2381  */
lock_extent_buffer_for_io(struct extent_buffer * eb,struct extent_page_data * epd)2382 static noinline_for_stack int lock_extent_buffer_for_io(struct extent_buffer *eb,
2383 			  struct extent_page_data *epd)
2384 {
2385 	struct btrfs_fs_info *fs_info = eb->fs_info;
2386 	int i, num_pages;
2387 	int flush = 0;
2388 	int ret = 0;
2389 
2390 	if (!btrfs_try_tree_write_lock(eb)) {
2391 		submit_write_bio(epd, 0);
2392 		flush = 1;
2393 		btrfs_tree_lock(eb);
2394 	}
2395 
2396 	if (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
2397 		btrfs_tree_unlock(eb);
2398 		if (!epd->sync_io)
2399 			return 0;
2400 		if (!flush) {
2401 			submit_write_bio(epd, 0);
2402 			flush = 1;
2403 		}
2404 		while (1) {
2405 			wait_on_extent_buffer_writeback(eb);
2406 			btrfs_tree_lock(eb);
2407 			if (!test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags))
2408 				break;
2409 			btrfs_tree_unlock(eb);
2410 		}
2411 	}
2412 
2413 	/*
2414 	 * We need to do this to prevent races in people who check if the eb is
2415 	 * under IO since we can end up having no IO bits set for a short period
2416 	 * of time.
2417 	 */
2418 	spin_lock(&eb->refs_lock);
2419 	if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
2420 		set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
2421 		spin_unlock(&eb->refs_lock);
2422 		btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
2423 		percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2424 					 -eb->len,
2425 					 fs_info->dirty_metadata_batch);
2426 		ret = 1;
2427 	} else {
2428 		spin_unlock(&eb->refs_lock);
2429 	}
2430 
2431 	btrfs_tree_unlock(eb);
2432 
2433 	/*
2434 	 * Either we don't need to submit any tree block, or we're submitting
2435 	 * subpage eb.
2436 	 * Subpage metadata doesn't use page locking at all, so we can skip
2437 	 * the page locking.
2438 	 */
2439 	if (!ret || fs_info->nodesize < PAGE_SIZE)
2440 		return ret;
2441 
2442 	num_pages = num_extent_pages(eb);
2443 	for (i = 0; i < num_pages; i++) {
2444 		struct page *p = eb->pages[i];
2445 
2446 		if (!trylock_page(p)) {
2447 			if (!flush) {
2448 				submit_write_bio(epd, 0);
2449 				flush = 1;
2450 			}
2451 			lock_page(p);
2452 		}
2453 	}
2454 
2455 	return ret;
2456 }
2457 
set_btree_ioerr(struct page * page,struct extent_buffer * eb)2458 static void set_btree_ioerr(struct page *page, struct extent_buffer *eb)
2459 {
2460 	struct btrfs_fs_info *fs_info = eb->fs_info;
2461 
2462 	btrfs_page_set_error(fs_info, page, eb->start, eb->len);
2463 	if (test_and_set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
2464 		return;
2465 
2466 	/*
2467 	 * A read may stumble upon this buffer later, make sure that it gets an
2468 	 * error and knows there was an error.
2469 	 */
2470 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
2471 
2472 	/*
2473 	 * We need to set the mapping with the io error as well because a write
2474 	 * error will flip the file system readonly, and then syncfs() will
2475 	 * return a 0 because we are readonly if we don't modify the err seq for
2476 	 * the superblock.
2477 	 */
2478 	mapping_set_error(page->mapping, -EIO);
2479 
2480 	/*
2481 	 * If we error out, we should add back the dirty_metadata_bytes
2482 	 * to make it consistent.
2483 	 */
2484 	percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
2485 				 eb->len, fs_info->dirty_metadata_batch);
2486 
2487 	/*
2488 	 * If writeback for a btree extent that doesn't belong to a log tree
2489 	 * failed, increment the counter transaction->eb_write_errors.
2490 	 * We do this because while the transaction is running and before it's
2491 	 * committing (when we call filemap_fdata[write|wait]_range against
2492 	 * the btree inode), we might have
2493 	 * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
2494 	 * returns an error or an error happens during writeback, when we're
2495 	 * committing the transaction we wouldn't know about it, since the pages
2496 	 * can be no longer dirty nor marked anymore for writeback (if a
2497 	 * subsequent modification to the extent buffer didn't happen before the
2498 	 * transaction commit), which makes filemap_fdata[write|wait]_range not
2499 	 * able to find the pages tagged with SetPageError at transaction
2500 	 * commit time. So if this happens we must abort the transaction,
2501 	 * otherwise we commit a super block with btree roots that point to
2502 	 * btree nodes/leafs whose content on disk is invalid - either garbage
2503 	 * or the content of some node/leaf from a past generation that got
2504 	 * cowed or deleted and is no longer valid.
2505 	 *
2506 	 * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
2507 	 * not be enough - we need to distinguish between log tree extents vs
2508 	 * non-log tree extents, and the next filemap_fdatawait_range() call
2509 	 * will catch and clear such errors in the mapping - and that call might
2510 	 * be from a log sync and not from a transaction commit. Also, checking
2511 	 * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
2512 	 * not done and would not be reliable - the eb might have been released
2513 	 * from memory and reading it back again means that flag would not be
2514 	 * set (since it's a runtime flag, not persisted on disk).
2515 	 *
2516 	 * Using the flags below in the btree inode also makes us achieve the
2517 	 * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
2518 	 * writeback for all dirty pages and before filemap_fdatawait_range()
2519 	 * is called, the writeback for all dirty pages had already finished
2520 	 * with errors - because we were not using AS_EIO/AS_ENOSPC,
2521 	 * filemap_fdatawait_range() would return success, as it could not know
2522 	 * that writeback errors happened (the pages were no longer tagged for
2523 	 * writeback).
2524 	 */
2525 	switch (eb->log_index) {
2526 	case -1:
2527 		set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
2528 		break;
2529 	case 0:
2530 		set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2531 		break;
2532 	case 1:
2533 		set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2534 		break;
2535 	default:
2536 		BUG(); /* unexpected, logic error */
2537 	}
2538 }
2539 
2540 /*
2541  * The endio specific version which won't touch any unsafe spinlock in endio
2542  * context.
2543  */
find_extent_buffer_nolock(struct btrfs_fs_info * fs_info,u64 start)2544 static struct extent_buffer *find_extent_buffer_nolock(
2545 		struct btrfs_fs_info *fs_info, u64 start)
2546 {
2547 	struct extent_buffer *eb;
2548 
2549 	rcu_read_lock();
2550 	eb = radix_tree_lookup(&fs_info->buffer_radix,
2551 			       start >> fs_info->sectorsize_bits);
2552 	if (eb && atomic_inc_not_zero(&eb->refs)) {
2553 		rcu_read_unlock();
2554 		return eb;
2555 	}
2556 	rcu_read_unlock();
2557 	return NULL;
2558 }
2559 
2560 /*
2561  * The endio function for subpage extent buffer write.
2562  *
2563  * Unlike end_bio_extent_buffer_writepage(), we only call end_page_writeback()
2564  * after all extent buffers in the page has finished their writeback.
2565  */
end_bio_subpage_eb_writepage(struct btrfs_bio * bbio)2566 static void end_bio_subpage_eb_writepage(struct btrfs_bio *bbio)
2567 {
2568 	struct bio *bio = &bbio->bio;
2569 	struct btrfs_fs_info *fs_info;
2570 	struct bio_vec *bvec;
2571 	struct bvec_iter_all iter_all;
2572 
2573 	fs_info = btrfs_sb(bio_first_page_all(bio)->mapping->host->i_sb);
2574 	ASSERT(fs_info->nodesize < PAGE_SIZE);
2575 
2576 	ASSERT(!bio_flagged(bio, BIO_CLONED));
2577 	bio_for_each_segment_all(bvec, bio, iter_all) {
2578 		struct page *page = bvec->bv_page;
2579 		u64 bvec_start = page_offset(page) + bvec->bv_offset;
2580 		u64 bvec_end = bvec_start + bvec->bv_len - 1;
2581 		u64 cur_bytenr = bvec_start;
2582 
2583 		ASSERT(IS_ALIGNED(bvec->bv_len, fs_info->nodesize));
2584 
2585 		/* Iterate through all extent buffers in the range */
2586 		while (cur_bytenr <= bvec_end) {
2587 			struct extent_buffer *eb;
2588 			int done;
2589 
2590 			/*
2591 			 * Here we can't use find_extent_buffer(), as it may
2592 			 * try to lock eb->refs_lock, which is not safe in endio
2593 			 * context.
2594 			 */
2595 			eb = find_extent_buffer_nolock(fs_info, cur_bytenr);
2596 			ASSERT(eb);
2597 
2598 			cur_bytenr = eb->start + eb->len;
2599 
2600 			ASSERT(test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags));
2601 			done = atomic_dec_and_test(&eb->io_pages);
2602 			ASSERT(done);
2603 
2604 			if (bio->bi_status ||
2605 			    test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2606 				ClearPageUptodate(page);
2607 				set_btree_ioerr(page, eb);
2608 			}
2609 
2610 			btrfs_subpage_clear_writeback(fs_info, page, eb->start,
2611 						      eb->len);
2612 			end_extent_buffer_writeback(eb);
2613 			/*
2614 			 * free_extent_buffer() will grab spinlock which is not
2615 			 * safe in endio context. Thus here we manually dec
2616 			 * the ref.
2617 			 */
2618 			atomic_dec(&eb->refs);
2619 		}
2620 	}
2621 	bio_put(bio);
2622 }
2623 
end_bio_extent_buffer_writepage(struct btrfs_bio * bbio)2624 static void end_bio_extent_buffer_writepage(struct btrfs_bio *bbio)
2625 {
2626 	struct bio *bio = &bbio->bio;
2627 	struct bio_vec *bvec;
2628 	struct extent_buffer *eb;
2629 	int done;
2630 	struct bvec_iter_all iter_all;
2631 
2632 	ASSERT(!bio_flagged(bio, BIO_CLONED));
2633 	bio_for_each_segment_all(bvec, bio, iter_all) {
2634 		struct page *page = bvec->bv_page;
2635 
2636 		eb = (struct extent_buffer *)page->private;
2637 		BUG_ON(!eb);
2638 		done = atomic_dec_and_test(&eb->io_pages);
2639 
2640 		if (bio->bi_status ||
2641 		    test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)) {
2642 			ClearPageUptodate(page);
2643 			set_btree_ioerr(page, eb);
2644 		}
2645 
2646 		end_page_writeback(page);
2647 
2648 		if (!done)
2649 			continue;
2650 
2651 		end_extent_buffer_writeback(eb);
2652 	}
2653 
2654 	bio_put(bio);
2655 }
2656 
prepare_eb_write(struct extent_buffer * eb)2657 static void prepare_eb_write(struct extent_buffer *eb)
2658 {
2659 	u32 nritems;
2660 	unsigned long start;
2661 	unsigned long end;
2662 
2663 	clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
2664 	atomic_set(&eb->io_pages, num_extent_pages(eb));
2665 
2666 	/* Set btree blocks beyond nritems with 0 to avoid stale content */
2667 	nritems = btrfs_header_nritems(eb);
2668 	if (btrfs_header_level(eb) > 0) {
2669 		end = btrfs_node_key_ptr_offset(nritems);
2670 		memzero_extent_buffer(eb, end, eb->len - end);
2671 	} else {
2672 		/*
2673 		 * Leaf:
2674 		 * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
2675 		 */
2676 		start = btrfs_item_nr_offset(nritems);
2677 		end = BTRFS_LEAF_DATA_OFFSET + leaf_data_end(eb);
2678 		memzero_extent_buffer(eb, start, end - start);
2679 	}
2680 }
2681 
2682 /*
2683  * Unlike the work in write_one_eb(), we rely completely on extent locking.
2684  * Page locking is only utilized at minimum to keep the VMM code happy.
2685  */
write_one_subpage_eb(struct extent_buffer * eb,struct writeback_control * wbc,struct extent_page_data * epd)2686 static int write_one_subpage_eb(struct extent_buffer *eb,
2687 				struct writeback_control *wbc,
2688 				struct extent_page_data *epd)
2689 {
2690 	struct btrfs_fs_info *fs_info = eb->fs_info;
2691 	struct page *page = eb->pages[0];
2692 	blk_opf_t write_flags = wbc_to_write_flags(wbc);
2693 	bool no_dirty_ebs = false;
2694 	int ret;
2695 
2696 	prepare_eb_write(eb);
2697 
2698 	/* clear_page_dirty_for_io() in subpage helper needs page locked */
2699 	lock_page(page);
2700 	btrfs_subpage_set_writeback(fs_info, page, eb->start, eb->len);
2701 
2702 	/* Check if this is the last dirty bit to update nr_written */
2703 	no_dirty_ebs = btrfs_subpage_clear_and_test_dirty(fs_info, page,
2704 							  eb->start, eb->len);
2705 	if (no_dirty_ebs)
2706 		clear_page_dirty_for_io(page);
2707 
2708 	epd->bio_ctrl.end_io_func = end_bio_subpage_eb_writepage;
2709 
2710 	ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2711 			&epd->bio_ctrl, eb->start, page, eb->len,
2712 			eb->start - page_offset(page), 0, false);
2713 	if (ret) {
2714 		btrfs_subpage_clear_writeback(fs_info, page, eb->start, eb->len);
2715 		set_btree_ioerr(page, eb);
2716 		unlock_page(page);
2717 
2718 		if (atomic_dec_and_test(&eb->io_pages))
2719 			end_extent_buffer_writeback(eb);
2720 		return -EIO;
2721 	}
2722 	unlock_page(page);
2723 	/*
2724 	 * Submission finished without problem, if no range of the page is
2725 	 * dirty anymore, we have submitted a page.  Update nr_written in wbc.
2726 	 */
2727 	if (no_dirty_ebs)
2728 		wbc->nr_to_write--;
2729 	return ret;
2730 }
2731 
write_one_eb(struct extent_buffer * eb,struct writeback_control * wbc,struct extent_page_data * epd)2732 static noinline_for_stack int write_one_eb(struct extent_buffer *eb,
2733 			struct writeback_control *wbc,
2734 			struct extent_page_data *epd)
2735 {
2736 	u64 disk_bytenr = eb->start;
2737 	int i, num_pages;
2738 	blk_opf_t write_flags = wbc_to_write_flags(wbc);
2739 	int ret = 0;
2740 
2741 	prepare_eb_write(eb);
2742 
2743 	epd->bio_ctrl.end_io_func = end_bio_extent_buffer_writepage;
2744 
2745 	num_pages = num_extent_pages(eb);
2746 	for (i = 0; i < num_pages; i++) {
2747 		struct page *p = eb->pages[i];
2748 
2749 		clear_page_dirty_for_io(p);
2750 		set_page_writeback(p);
2751 		ret = submit_extent_page(REQ_OP_WRITE | write_flags, wbc,
2752 					 &epd->bio_ctrl, disk_bytenr, p,
2753 					 PAGE_SIZE, 0, 0, false);
2754 		if (ret) {
2755 			set_btree_ioerr(p, eb);
2756 			if (PageWriteback(p))
2757 				end_page_writeback(p);
2758 			if (atomic_sub_and_test(num_pages - i, &eb->io_pages))
2759 				end_extent_buffer_writeback(eb);
2760 			ret = -EIO;
2761 			break;
2762 		}
2763 		disk_bytenr += PAGE_SIZE;
2764 		wbc->nr_to_write--;
2765 		unlock_page(p);
2766 	}
2767 
2768 	if (unlikely(ret)) {
2769 		for (; i < num_pages; i++) {
2770 			struct page *p = eb->pages[i];
2771 			clear_page_dirty_for_io(p);
2772 			unlock_page(p);
2773 		}
2774 	}
2775 
2776 	return ret;
2777 }
2778 
2779 /*
2780  * Submit one subpage btree page.
2781  *
2782  * The main difference to submit_eb_page() is:
2783  * - Page locking
2784  *   For subpage, we don't rely on page locking at all.
2785  *
2786  * - Flush write bio
2787  *   We only flush bio if we may be unable to fit current extent buffers into
2788  *   current bio.
2789  *
2790  * Return >=0 for the number of submitted extent buffers.
2791  * Return <0 for fatal error.
2792  */
submit_eb_subpage(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd)2793 static int submit_eb_subpage(struct page *page,
2794 			     struct writeback_control *wbc,
2795 			     struct extent_page_data *epd)
2796 {
2797 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
2798 	int submitted = 0;
2799 	u64 page_start = page_offset(page);
2800 	int bit_start = 0;
2801 	int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
2802 	int ret;
2803 
2804 	/* Lock and write each dirty extent buffers in the range */
2805 	while (bit_start < fs_info->subpage_info->bitmap_nr_bits) {
2806 		struct btrfs_subpage *subpage = (struct btrfs_subpage *)page->private;
2807 		struct extent_buffer *eb;
2808 		unsigned long flags;
2809 		u64 start;
2810 
2811 		/*
2812 		 * Take private lock to ensure the subpage won't be detached
2813 		 * in the meantime.
2814 		 */
2815 		spin_lock(&page->mapping->private_lock);
2816 		if (!PagePrivate(page)) {
2817 			spin_unlock(&page->mapping->private_lock);
2818 			break;
2819 		}
2820 		spin_lock_irqsave(&subpage->lock, flags);
2821 		if (!test_bit(bit_start + fs_info->subpage_info->dirty_offset,
2822 			      subpage->bitmaps)) {
2823 			spin_unlock_irqrestore(&subpage->lock, flags);
2824 			spin_unlock(&page->mapping->private_lock);
2825 			bit_start++;
2826 			continue;
2827 		}
2828 
2829 		start = page_start + bit_start * fs_info->sectorsize;
2830 		bit_start += sectors_per_node;
2831 
2832 		/*
2833 		 * Here we just want to grab the eb without touching extra
2834 		 * spin locks, so call find_extent_buffer_nolock().
2835 		 */
2836 		eb = find_extent_buffer_nolock(fs_info, start);
2837 		spin_unlock_irqrestore(&subpage->lock, flags);
2838 		spin_unlock(&page->mapping->private_lock);
2839 
2840 		/*
2841 		 * The eb has already reached 0 refs thus find_extent_buffer()
2842 		 * doesn't return it. We don't need to write back such eb
2843 		 * anyway.
2844 		 */
2845 		if (!eb)
2846 			continue;
2847 
2848 		ret = lock_extent_buffer_for_io(eb, epd);
2849 		if (ret == 0) {
2850 			free_extent_buffer(eb);
2851 			continue;
2852 		}
2853 		if (ret < 0) {
2854 			free_extent_buffer(eb);
2855 			goto cleanup;
2856 		}
2857 		ret = write_one_subpage_eb(eb, wbc, epd);
2858 		free_extent_buffer(eb);
2859 		if (ret < 0)
2860 			goto cleanup;
2861 		submitted++;
2862 	}
2863 	return submitted;
2864 
2865 cleanup:
2866 	/* We hit error, end bio for the submitted extent buffers */
2867 	submit_write_bio(epd, ret);
2868 	return ret;
2869 }
2870 
2871 /*
2872  * Submit all page(s) of one extent buffer.
2873  *
2874  * @page:	the page of one extent buffer
2875  * @eb_context:	to determine if we need to submit this page, if current page
2876  *		belongs to this eb, we don't need to submit
2877  *
2878  * The caller should pass each page in their bytenr order, and here we use
2879  * @eb_context to determine if we have submitted pages of one extent buffer.
2880  *
2881  * If we have, we just skip until we hit a new page that doesn't belong to
2882  * current @eb_context.
2883  *
2884  * If not, we submit all the page(s) of the extent buffer.
2885  *
2886  * Return >0 if we have submitted the extent buffer successfully.
2887  * Return 0 if we don't need to submit the page, as it's already submitted by
2888  * previous call.
2889  * Return <0 for fatal error.
2890  */
submit_eb_page(struct page * page,struct writeback_control * wbc,struct extent_page_data * epd,struct extent_buffer ** eb_context)2891 static int submit_eb_page(struct page *page, struct writeback_control *wbc,
2892 			  struct extent_page_data *epd,
2893 			  struct extent_buffer **eb_context)
2894 {
2895 	struct address_space *mapping = page->mapping;
2896 	struct btrfs_block_group *cache = NULL;
2897 	struct extent_buffer *eb;
2898 	int ret;
2899 
2900 	if (!PagePrivate(page))
2901 		return 0;
2902 
2903 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
2904 		return submit_eb_subpage(page, wbc, epd);
2905 
2906 	spin_lock(&mapping->private_lock);
2907 	if (!PagePrivate(page)) {
2908 		spin_unlock(&mapping->private_lock);
2909 		return 0;
2910 	}
2911 
2912 	eb = (struct extent_buffer *)page->private;
2913 
2914 	/*
2915 	 * Shouldn't happen and normally this would be a BUG_ON but no point
2916 	 * crashing the machine for something we can survive anyway.
2917 	 */
2918 	if (WARN_ON(!eb)) {
2919 		spin_unlock(&mapping->private_lock);
2920 		return 0;
2921 	}
2922 
2923 	if (eb == *eb_context) {
2924 		spin_unlock(&mapping->private_lock);
2925 		return 0;
2926 	}
2927 	ret = atomic_inc_not_zero(&eb->refs);
2928 	spin_unlock(&mapping->private_lock);
2929 	if (!ret)
2930 		return 0;
2931 
2932 	if (!btrfs_check_meta_write_pointer(eb->fs_info, eb, &cache)) {
2933 		/*
2934 		 * If for_sync, this hole will be filled with
2935 		 * trasnsaction commit.
2936 		 */
2937 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
2938 			ret = -EAGAIN;
2939 		else
2940 			ret = 0;
2941 		free_extent_buffer(eb);
2942 		return ret;
2943 	}
2944 
2945 	*eb_context = eb;
2946 
2947 	ret = lock_extent_buffer_for_io(eb, epd);
2948 	if (ret <= 0) {
2949 		btrfs_revert_meta_write_pointer(cache, eb);
2950 		if (cache)
2951 			btrfs_put_block_group(cache);
2952 		free_extent_buffer(eb);
2953 		return ret;
2954 	}
2955 	if (cache) {
2956 		/*
2957 		 * Implies write in zoned mode. Mark the last eb in a block group.
2958 		 */
2959 		btrfs_schedule_zone_finish_bg(cache, eb);
2960 		btrfs_put_block_group(cache);
2961 	}
2962 	ret = write_one_eb(eb, wbc, epd);
2963 	free_extent_buffer(eb);
2964 	if (ret < 0)
2965 		return ret;
2966 	return 1;
2967 }
2968 
btree_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc)2969 int btree_write_cache_pages(struct address_space *mapping,
2970 				   struct writeback_control *wbc)
2971 {
2972 	struct extent_buffer *eb_context = NULL;
2973 	struct extent_page_data epd = {
2974 		.bio_ctrl = { 0 },
2975 		.extent_locked = 0,
2976 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
2977 	};
2978 	struct btrfs_fs_info *fs_info = BTRFS_I(mapping->host)->root->fs_info;
2979 	int ret = 0;
2980 	int done = 0;
2981 	int nr_to_write_done = 0;
2982 	struct pagevec pvec;
2983 	int nr_pages;
2984 	pgoff_t index;
2985 	pgoff_t end;		/* Inclusive */
2986 	int scanned = 0;
2987 	xa_mark_t tag;
2988 
2989 	pagevec_init(&pvec);
2990 	if (wbc->range_cyclic) {
2991 		index = mapping->writeback_index; /* Start from prev offset */
2992 		end = -1;
2993 		/*
2994 		 * Start from the beginning does not need to cycle over the
2995 		 * range, mark it as scanned.
2996 		 */
2997 		scanned = (index == 0);
2998 	} else {
2999 		index = wbc->range_start >> PAGE_SHIFT;
3000 		end = wbc->range_end >> PAGE_SHIFT;
3001 		scanned = 1;
3002 	}
3003 	if (wbc->sync_mode == WB_SYNC_ALL)
3004 		tag = PAGECACHE_TAG_TOWRITE;
3005 	else
3006 		tag = PAGECACHE_TAG_DIRTY;
3007 	btrfs_zoned_meta_io_lock(fs_info);
3008 retry:
3009 	if (wbc->sync_mode == WB_SYNC_ALL)
3010 		tag_pages_for_writeback(mapping, index, end);
3011 	while (!done && !nr_to_write_done && (index <= end) &&
3012 	       (nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
3013 			tag))) {
3014 		unsigned i;
3015 
3016 		for (i = 0; i < nr_pages; i++) {
3017 			struct page *page = pvec.pages[i];
3018 
3019 			ret = submit_eb_page(page, wbc, &epd, &eb_context);
3020 			if (ret == 0)
3021 				continue;
3022 			if (ret < 0) {
3023 				done = 1;
3024 				break;
3025 			}
3026 
3027 			/*
3028 			 * The filesystem may choose to bump up nr_to_write.
3029 			 * We have to make sure to honor the new nr_to_write
3030 			 * at any time.
3031 			 */
3032 			nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
3033 					    wbc->nr_to_write <= 0);
3034 		}
3035 		pagevec_release(&pvec);
3036 		cond_resched();
3037 	}
3038 	if (!scanned && !done) {
3039 		/*
3040 		 * We hit the last page and there is more work to be done: wrap
3041 		 * back to the start of the file
3042 		 */
3043 		scanned = 1;
3044 		index = 0;
3045 		goto retry;
3046 	}
3047 	/*
3048 	 * If something went wrong, don't allow any metadata write bio to be
3049 	 * submitted.
3050 	 *
3051 	 * This would prevent use-after-free if we had dirty pages not
3052 	 * cleaned up, which can still happen by fuzzed images.
3053 	 *
3054 	 * - Bad extent tree
3055 	 *   Allowing existing tree block to be allocated for other trees.
3056 	 *
3057 	 * - Log tree operations
3058 	 *   Exiting tree blocks get allocated to log tree, bumps its
3059 	 *   generation, then get cleaned in tree re-balance.
3060 	 *   Such tree block will not be written back, since it's clean,
3061 	 *   thus no WRITTEN flag set.
3062 	 *   And after log writes back, this tree block is not traced by
3063 	 *   any dirty extent_io_tree.
3064 	 *
3065 	 * - Offending tree block gets re-dirtied from its original owner
3066 	 *   Since it has bumped generation, no WRITTEN flag, it can be
3067 	 *   reused without COWing. This tree block will not be traced
3068 	 *   by btrfs_transaction::dirty_pages.
3069 	 *
3070 	 *   Now such dirty tree block will not be cleaned by any dirty
3071 	 *   extent io tree. Thus we don't want to submit such wild eb
3072 	 *   if the fs already has error.
3073 	 *
3074 	 * We can get ret > 0 from submit_extent_page() indicating how many ebs
3075 	 * were submitted. Reset it to 0 to avoid false alerts for the caller.
3076 	 */
3077 	if (ret > 0)
3078 		ret = 0;
3079 	if (!ret && BTRFS_FS_ERROR(fs_info))
3080 		ret = -EROFS;
3081 	submit_write_bio(&epd, ret);
3082 
3083 	btrfs_zoned_meta_io_unlock(fs_info);
3084 	return ret;
3085 }
3086 
3087 /**
3088  * Walk the list of dirty pages of the given address space and write all of them.
3089  *
3090  * @mapping: address space structure to write
3091  * @wbc:     subtract the number of written pages from *@wbc->nr_to_write
3092  * @epd:     holds context for the write, namely the bio
3093  *
3094  * If a page is already under I/O, write_cache_pages() skips it, even
3095  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
3096  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
3097  * and msync() need to guarantee that all the data which was dirty at the time
3098  * the call was made get new I/O started against them.  If wbc->sync_mode is
3099  * WB_SYNC_ALL then we were called for data integrity and we must wait for
3100  * existing IO to complete.
3101  */
extent_write_cache_pages(struct address_space * mapping,struct writeback_control * wbc,struct extent_page_data * epd)3102 static int extent_write_cache_pages(struct address_space *mapping,
3103 			     struct writeback_control *wbc,
3104 			     struct extent_page_data *epd)
3105 {
3106 	struct inode *inode = mapping->host;
3107 	int ret = 0;
3108 	int done = 0;
3109 	int nr_to_write_done = 0;
3110 	struct pagevec pvec;
3111 	int nr_pages;
3112 	pgoff_t index;
3113 	pgoff_t end;		/* Inclusive */
3114 	pgoff_t done_index;
3115 	int range_whole = 0;
3116 	int scanned = 0;
3117 	xa_mark_t tag;
3118 
3119 	/*
3120 	 * We have to hold onto the inode so that ordered extents can do their
3121 	 * work when the IO finishes.  The alternative to this is failing to add
3122 	 * an ordered extent if the igrab() fails there and that is a huge pain
3123 	 * to deal with, so instead just hold onto the inode throughout the
3124 	 * writepages operation.  If it fails here we are freeing up the inode
3125 	 * anyway and we'd rather not waste our time writing out stuff that is
3126 	 * going to be truncated anyway.
3127 	 */
3128 	if (!igrab(inode))
3129 		return 0;
3130 
3131 	pagevec_init(&pvec);
3132 	if (wbc->range_cyclic) {
3133 		index = mapping->writeback_index; /* Start from prev offset */
3134 		end = -1;
3135 		/*
3136 		 * Start from the beginning does not need to cycle over the
3137 		 * range, mark it as scanned.
3138 		 */
3139 		scanned = (index == 0);
3140 	} else {
3141 		index = wbc->range_start >> PAGE_SHIFT;
3142 		end = wbc->range_end >> PAGE_SHIFT;
3143 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
3144 			range_whole = 1;
3145 		scanned = 1;
3146 	}
3147 
3148 	/*
3149 	 * We do the tagged writepage as long as the snapshot flush bit is set
3150 	 * and we are the first one who do the filemap_flush() on this inode.
3151 	 *
3152 	 * The nr_to_write == LONG_MAX is needed to make sure other flushers do
3153 	 * not race in and drop the bit.
3154 	 */
3155 	if (range_whole && wbc->nr_to_write == LONG_MAX &&
3156 	    test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
3157 			       &BTRFS_I(inode)->runtime_flags))
3158 		wbc->tagged_writepages = 1;
3159 
3160 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3161 		tag = PAGECACHE_TAG_TOWRITE;
3162 	else
3163 		tag = PAGECACHE_TAG_DIRTY;
3164 retry:
3165 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
3166 		tag_pages_for_writeback(mapping, index, end);
3167 	done_index = index;
3168 	while (!done && !nr_to_write_done && (index <= end) &&
3169 			(nr_pages = pagevec_lookup_range_tag(&pvec, mapping,
3170 						&index, end, tag))) {
3171 		unsigned i;
3172 
3173 		for (i = 0; i < nr_pages; i++) {
3174 			struct page *page = pvec.pages[i];
3175 
3176 			done_index = page->index + 1;
3177 			/*
3178 			 * At this point we hold neither the i_pages lock nor
3179 			 * the page lock: the page may be truncated or
3180 			 * invalidated (changing page->mapping to NULL),
3181 			 * or even swizzled back from swapper_space to
3182 			 * tmpfs file mapping
3183 			 */
3184 			if (!trylock_page(page)) {
3185 				submit_write_bio(epd, 0);
3186 				lock_page(page);
3187 			}
3188 
3189 			if (unlikely(page->mapping != mapping)) {
3190 				unlock_page(page);
3191 				continue;
3192 			}
3193 
3194 			if (wbc->sync_mode != WB_SYNC_NONE) {
3195 				if (PageWriteback(page))
3196 					submit_write_bio(epd, 0);
3197 				wait_on_page_writeback(page);
3198 			}
3199 
3200 			if (PageWriteback(page) ||
3201 			    !clear_page_dirty_for_io(page)) {
3202 				unlock_page(page);
3203 				continue;
3204 			}
3205 
3206 			ret = __extent_writepage(page, wbc, epd);
3207 			if (ret < 0) {
3208 				done = 1;
3209 				break;
3210 			}
3211 
3212 			/*
3213 			 * the filesystem may choose to bump up nr_to_write.
3214 			 * We have to make sure to honor the new nr_to_write
3215 			 * at any time
3216 			 */
3217 			nr_to_write_done = wbc->nr_to_write <= 0;
3218 		}
3219 		pagevec_release(&pvec);
3220 		cond_resched();
3221 	}
3222 	if (!scanned && !done) {
3223 		/*
3224 		 * We hit the last page and there is more work to be done: wrap
3225 		 * back to the start of the file
3226 		 */
3227 		scanned = 1;
3228 		index = 0;
3229 
3230 		/*
3231 		 * If we're looping we could run into a page that is locked by a
3232 		 * writer and that writer could be waiting on writeback for a
3233 		 * page in our current bio, and thus deadlock, so flush the
3234 		 * write bio here.
3235 		 */
3236 		submit_write_bio(epd, 0);
3237 		goto retry;
3238 	}
3239 
3240 	if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
3241 		mapping->writeback_index = done_index;
3242 
3243 	btrfs_add_delayed_iput(inode);
3244 	return ret;
3245 }
3246 
3247 /*
3248  * Submit the pages in the range to bio for call sites which delalloc range has
3249  * already been ran (aka, ordered extent inserted) and all pages are still
3250  * locked.
3251  */
extent_write_locked_range(struct inode * inode,u64 start,u64 end)3252 int extent_write_locked_range(struct inode *inode, u64 start, u64 end)
3253 {
3254 	bool found_error = false;
3255 	int first_error = 0;
3256 	int ret = 0;
3257 	struct address_space *mapping = inode->i_mapping;
3258 	struct page *page;
3259 	u64 cur = start;
3260 	unsigned long nr_pages;
3261 	const u32 sectorsize = btrfs_sb(inode->i_sb)->sectorsize;
3262 	struct extent_page_data epd = {
3263 		.bio_ctrl = { 0 },
3264 		.extent_locked = 1,
3265 		.sync_io = 1,
3266 	};
3267 	struct writeback_control wbc_writepages = {
3268 		.sync_mode	= WB_SYNC_ALL,
3269 		.range_start	= start,
3270 		.range_end	= end + 1,
3271 		/* We're called from an async helper function */
3272 		.punt_to_cgroup	= 1,
3273 		.no_cgroup_owner = 1,
3274 	};
3275 
3276 	ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
3277 	nr_pages = (round_up(end, PAGE_SIZE) - round_down(start, PAGE_SIZE)) >>
3278 		   PAGE_SHIFT;
3279 	wbc_writepages.nr_to_write = nr_pages * 2;
3280 
3281 	wbc_attach_fdatawrite_inode(&wbc_writepages, inode);
3282 	while (cur <= end) {
3283 		u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
3284 
3285 		page = find_get_page(mapping, cur >> PAGE_SHIFT);
3286 		/*
3287 		 * All pages in the range are locked since
3288 		 * btrfs_run_delalloc_range(), thus there is no way to clear
3289 		 * the page dirty flag.
3290 		 */
3291 		ASSERT(PageLocked(page));
3292 		ASSERT(PageDirty(page));
3293 		clear_page_dirty_for_io(page);
3294 		ret = __extent_writepage(page, &wbc_writepages, &epd);
3295 		ASSERT(ret <= 0);
3296 		if (ret < 0) {
3297 			found_error = true;
3298 			first_error = ret;
3299 		}
3300 		put_page(page);
3301 		cur = cur_end + 1;
3302 	}
3303 
3304 	submit_write_bio(&epd, found_error ? ret : 0);
3305 
3306 	wbc_detach_inode(&wbc_writepages);
3307 	if (found_error)
3308 		return first_error;
3309 	return ret;
3310 }
3311 
extent_writepages(struct address_space * mapping,struct writeback_control * wbc)3312 int extent_writepages(struct address_space *mapping,
3313 		      struct writeback_control *wbc)
3314 {
3315 	struct inode *inode = mapping->host;
3316 	int ret = 0;
3317 	struct extent_page_data epd = {
3318 		.bio_ctrl = { 0 },
3319 		.extent_locked = 0,
3320 		.sync_io = wbc->sync_mode == WB_SYNC_ALL,
3321 	};
3322 
3323 	/*
3324 	 * Allow only a single thread to do the reloc work in zoned mode to
3325 	 * protect the write pointer updates.
3326 	 */
3327 	btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
3328 	ret = extent_write_cache_pages(mapping, wbc, &epd);
3329 	submit_write_bio(&epd, ret);
3330 	btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
3331 	return ret;
3332 }
3333 
extent_readahead(struct readahead_control * rac)3334 void extent_readahead(struct readahead_control *rac)
3335 {
3336 	struct btrfs_bio_ctrl bio_ctrl = { 0 };
3337 	struct page *pagepool[16];
3338 	struct extent_map *em_cached = NULL;
3339 	u64 prev_em_start = (u64)-1;
3340 	int nr;
3341 
3342 	while ((nr = readahead_page_batch(rac, pagepool))) {
3343 		u64 contig_start = readahead_pos(rac);
3344 		u64 contig_end = contig_start + readahead_batch_length(rac) - 1;
3345 
3346 		contiguous_readpages(pagepool, nr, contig_start, contig_end,
3347 				&em_cached, &bio_ctrl, &prev_em_start);
3348 	}
3349 
3350 	if (em_cached)
3351 		free_extent_map(em_cached);
3352 	submit_one_bio(&bio_ctrl);
3353 }
3354 
3355 /*
3356  * basic invalidate_folio code, this waits on any locked or writeback
3357  * ranges corresponding to the folio, and then deletes any extent state
3358  * records from the tree
3359  */
extent_invalidate_folio(struct extent_io_tree * tree,struct folio * folio,size_t offset)3360 int extent_invalidate_folio(struct extent_io_tree *tree,
3361 			  struct folio *folio, size_t offset)
3362 {
3363 	struct extent_state *cached_state = NULL;
3364 	u64 start = folio_pos(folio);
3365 	u64 end = start + folio_size(folio) - 1;
3366 	size_t blocksize = folio->mapping->host->i_sb->s_blocksize;
3367 
3368 	/* This function is only called for the btree inode */
3369 	ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
3370 
3371 	start += ALIGN(offset, blocksize);
3372 	if (start > end)
3373 		return 0;
3374 
3375 	lock_extent(tree, start, end, &cached_state);
3376 	folio_wait_writeback(folio);
3377 
3378 	/*
3379 	 * Currently for btree io tree, only EXTENT_LOCKED is utilized,
3380 	 * so here we only need to unlock the extent range to free any
3381 	 * existing extent state.
3382 	 */
3383 	unlock_extent(tree, start, end, &cached_state);
3384 	return 0;
3385 }
3386 
3387 /*
3388  * a helper for release_folio, this tests for areas of the page that
3389  * are locked or under IO and drops the related state bits if it is safe
3390  * to drop the page.
3391  */
try_release_extent_state(struct extent_io_tree * tree,struct page * page,gfp_t mask)3392 static int try_release_extent_state(struct extent_io_tree *tree,
3393 				    struct page *page, gfp_t mask)
3394 {
3395 	u64 start = page_offset(page);
3396 	u64 end = start + PAGE_SIZE - 1;
3397 	int ret = 1;
3398 
3399 	if (test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL)) {
3400 		ret = 0;
3401 	} else {
3402 		u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
3403 				   EXTENT_DELALLOC_NEW | EXTENT_CTLBITS |
3404 				   EXTENT_QGROUP_RESERVED);
3405 
3406 		/*
3407 		 * At this point we can safely clear everything except the
3408 		 * locked bit, the nodatasum bit and the delalloc new bit.
3409 		 * The delalloc new bit will be cleared by ordered extent
3410 		 * completion.
3411 		 */
3412 		ret = __clear_extent_bit(tree, start, end, clear_bits, NULL,
3413 					 mask, NULL);
3414 
3415 		/* if clear_extent_bit failed for enomem reasons,
3416 		 * we can't allow the release to continue.
3417 		 */
3418 		if (ret < 0)
3419 			ret = 0;
3420 		else
3421 			ret = 1;
3422 	}
3423 	return ret;
3424 }
3425 
3426 /*
3427  * a helper for release_folio.  As long as there are no locked extents
3428  * in the range corresponding to the page, both state records and extent
3429  * map records are removed
3430  */
try_release_extent_mapping(struct page * page,gfp_t mask)3431 int try_release_extent_mapping(struct page *page, gfp_t mask)
3432 {
3433 	struct extent_map *em;
3434 	u64 start = page_offset(page);
3435 	u64 end = start + PAGE_SIZE - 1;
3436 	struct btrfs_inode *btrfs_inode = BTRFS_I(page->mapping->host);
3437 	struct extent_io_tree *tree = &btrfs_inode->io_tree;
3438 	struct extent_map_tree *map = &btrfs_inode->extent_tree;
3439 
3440 	if (gfpflags_allow_blocking(mask) &&
3441 	    page->mapping->host->i_size > SZ_16M) {
3442 		u64 len;
3443 		while (start <= end) {
3444 			struct btrfs_fs_info *fs_info;
3445 			u64 cur_gen;
3446 
3447 			len = end - start + 1;
3448 			write_lock(&map->lock);
3449 			em = lookup_extent_mapping(map, start, len);
3450 			if (!em) {
3451 				write_unlock(&map->lock);
3452 				break;
3453 			}
3454 			if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
3455 			    em->start != start) {
3456 				write_unlock(&map->lock);
3457 				free_extent_map(em);
3458 				break;
3459 			}
3460 			if (test_range_bit(tree, em->start,
3461 					   extent_map_end(em) - 1,
3462 					   EXTENT_LOCKED, 0, NULL))
3463 				goto next;
3464 			/*
3465 			 * If it's not in the list of modified extents, used
3466 			 * by a fast fsync, we can remove it. If it's being
3467 			 * logged we can safely remove it since fsync took an
3468 			 * extra reference on the em.
3469 			 */
3470 			if (list_empty(&em->list) ||
3471 			    test_bit(EXTENT_FLAG_LOGGING, &em->flags))
3472 				goto remove_em;
3473 			/*
3474 			 * If it's in the list of modified extents, remove it
3475 			 * only if its generation is older then the current one,
3476 			 * in which case we don't need it for a fast fsync.
3477 			 * Otherwise don't remove it, we could be racing with an
3478 			 * ongoing fast fsync that could miss the new extent.
3479 			 */
3480 			fs_info = btrfs_inode->root->fs_info;
3481 			spin_lock(&fs_info->trans_lock);
3482 			cur_gen = fs_info->generation;
3483 			spin_unlock(&fs_info->trans_lock);
3484 			if (em->generation >= cur_gen)
3485 				goto next;
3486 remove_em:
3487 			/*
3488 			 * We only remove extent maps that are not in the list of
3489 			 * modified extents or that are in the list but with a
3490 			 * generation lower then the current generation, so there
3491 			 * is no need to set the full fsync flag on the inode (it
3492 			 * hurts the fsync performance for workloads with a data
3493 			 * size that exceeds or is close to the system's memory).
3494 			 */
3495 			remove_extent_mapping(map, em);
3496 			/* once for the rb tree */
3497 			free_extent_map(em);
3498 next:
3499 			start = extent_map_end(em);
3500 			write_unlock(&map->lock);
3501 
3502 			/* once for us */
3503 			free_extent_map(em);
3504 
3505 			cond_resched(); /* Allow large-extent preemption. */
3506 		}
3507 	}
3508 	return try_release_extent_state(tree, page, mask);
3509 }
3510 
3511 /*
3512  * To cache previous fiemap extent
3513  *
3514  * Will be used for merging fiemap extent
3515  */
3516 struct fiemap_cache {
3517 	u64 offset;
3518 	u64 phys;
3519 	u64 len;
3520 	u32 flags;
3521 	bool cached;
3522 };
3523 
3524 /*
3525  * Helper to submit fiemap extent.
3526  *
3527  * Will try to merge current fiemap extent specified by @offset, @phys,
3528  * @len and @flags with cached one.
3529  * And only when we fails to merge, cached one will be submitted as
3530  * fiemap extent.
3531  *
3532  * Return value is the same as fiemap_fill_next_extent().
3533  */
emit_fiemap_extent(struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache,u64 offset,u64 phys,u64 len,u32 flags)3534 static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
3535 				struct fiemap_cache *cache,
3536 				u64 offset, u64 phys, u64 len, u32 flags)
3537 {
3538 	int ret = 0;
3539 
3540 	/* Set at the end of extent_fiemap(). */
3541 	ASSERT((flags & FIEMAP_EXTENT_LAST) == 0);
3542 
3543 	if (!cache->cached)
3544 		goto assign;
3545 
3546 	/*
3547 	 * Sanity check, extent_fiemap() should have ensured that new
3548 	 * fiemap extent won't overlap with cached one.
3549 	 * Not recoverable.
3550 	 *
3551 	 * NOTE: Physical address can overlap, due to compression
3552 	 */
3553 	if (cache->offset + cache->len > offset) {
3554 		WARN_ON(1);
3555 		return -EINVAL;
3556 	}
3557 
3558 	/*
3559 	 * Only merges fiemap extents if
3560 	 * 1) Their logical addresses are continuous
3561 	 *
3562 	 * 2) Their physical addresses are continuous
3563 	 *    So truly compressed (physical size smaller than logical size)
3564 	 *    extents won't get merged with each other
3565 	 *
3566 	 * 3) Share same flags
3567 	 */
3568 	if (cache->offset + cache->len  == offset &&
3569 	    cache->phys + cache->len == phys  &&
3570 	    cache->flags == flags) {
3571 		cache->len += len;
3572 		return 0;
3573 	}
3574 
3575 	/* Not mergeable, need to submit cached one */
3576 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3577 				      cache->len, cache->flags);
3578 	cache->cached = false;
3579 	if (ret)
3580 		return ret;
3581 assign:
3582 	cache->cached = true;
3583 	cache->offset = offset;
3584 	cache->phys = phys;
3585 	cache->len = len;
3586 	cache->flags = flags;
3587 
3588 	return 0;
3589 }
3590 
3591 /*
3592  * Emit last fiemap cache
3593  *
3594  * The last fiemap cache may still be cached in the following case:
3595  * 0		      4k		    8k
3596  * |<- Fiemap range ->|
3597  * |<------------  First extent ----------->|
3598  *
3599  * In this case, the first extent range will be cached but not emitted.
3600  * So we must emit it before ending extent_fiemap().
3601  */
emit_last_fiemap_cache(struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache)3602 static int emit_last_fiemap_cache(struct fiemap_extent_info *fieinfo,
3603 				  struct fiemap_cache *cache)
3604 {
3605 	int ret;
3606 
3607 	if (!cache->cached)
3608 		return 0;
3609 
3610 	ret = fiemap_fill_next_extent(fieinfo, cache->offset, cache->phys,
3611 				      cache->len, cache->flags);
3612 	cache->cached = false;
3613 	if (ret > 0)
3614 		ret = 0;
3615 	return ret;
3616 }
3617 
fiemap_next_leaf_item(struct btrfs_inode * inode,struct btrfs_path * path)3618 static int fiemap_next_leaf_item(struct btrfs_inode *inode, struct btrfs_path *path)
3619 {
3620 	struct extent_buffer *clone;
3621 	struct btrfs_key key;
3622 	int slot;
3623 	int ret;
3624 
3625 	path->slots[0]++;
3626 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0]))
3627 		return 0;
3628 
3629 	ret = btrfs_next_leaf(inode->root, path);
3630 	if (ret != 0)
3631 		return ret;
3632 
3633 	/*
3634 	 * Don't bother with cloning if there are no more file extent items for
3635 	 * our inode.
3636 	 */
3637 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3638 	if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY)
3639 		return 1;
3640 
3641 	/* See the comment at fiemap_search_slot() about why we clone. */
3642 	clone = btrfs_clone_extent_buffer(path->nodes[0]);
3643 	if (!clone)
3644 		return -ENOMEM;
3645 
3646 	slot = path->slots[0];
3647 	btrfs_release_path(path);
3648 	path->nodes[0] = clone;
3649 	path->slots[0] = slot;
3650 
3651 	return 0;
3652 }
3653 
3654 /*
3655  * Search for the first file extent item that starts at a given file offset or
3656  * the one that starts immediately before that offset.
3657  * Returns: 0 on success, < 0 on error, 1 if not found.
3658  */
fiemap_search_slot(struct btrfs_inode * inode,struct btrfs_path * path,u64 file_offset)3659 static int fiemap_search_slot(struct btrfs_inode *inode, struct btrfs_path *path,
3660 			      u64 file_offset)
3661 {
3662 	const u64 ino = btrfs_ino(inode);
3663 	struct btrfs_root *root = inode->root;
3664 	struct extent_buffer *clone;
3665 	struct btrfs_key key;
3666 	int slot;
3667 	int ret;
3668 
3669 	key.objectid = ino;
3670 	key.type = BTRFS_EXTENT_DATA_KEY;
3671 	key.offset = file_offset;
3672 
3673 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3674 	if (ret < 0)
3675 		return ret;
3676 
3677 	if (ret > 0 && path->slots[0] > 0) {
3678 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3679 		if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3680 			path->slots[0]--;
3681 	}
3682 
3683 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3684 		ret = btrfs_next_leaf(root, path);
3685 		if (ret != 0)
3686 			return ret;
3687 
3688 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3689 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3690 			return 1;
3691 	}
3692 
3693 	/*
3694 	 * We clone the leaf and use it during fiemap. This is because while
3695 	 * using the leaf we do expensive things like checking if an extent is
3696 	 * shared, which can take a long time. In order to prevent blocking
3697 	 * other tasks for too long, we use a clone of the leaf. We have locked
3698 	 * the file range in the inode's io tree, so we know none of our file
3699 	 * extent items can change. This way we avoid blocking other tasks that
3700 	 * want to insert items for other inodes in the same leaf or b+tree
3701 	 * rebalance operations (triggered for example when someone is trying
3702 	 * to push items into this leaf when trying to insert an item in a
3703 	 * neighbour leaf).
3704 	 * We also need the private clone because holding a read lock on an
3705 	 * extent buffer of the subvolume's b+tree will make lockdep unhappy
3706 	 * when we call fiemap_fill_next_extent(), because that may cause a page
3707 	 * fault when filling the user space buffer with fiemap data.
3708 	 */
3709 	clone = btrfs_clone_extent_buffer(path->nodes[0]);
3710 	if (!clone)
3711 		return -ENOMEM;
3712 
3713 	slot = path->slots[0];
3714 	btrfs_release_path(path);
3715 	path->nodes[0] = clone;
3716 	path->slots[0] = slot;
3717 
3718 	return 0;
3719 }
3720 
3721 /*
3722  * Process a range which is a hole or a prealloc extent in the inode's subvolume
3723  * btree. If @disk_bytenr is 0, we are dealing with a hole, otherwise a prealloc
3724  * extent. The end offset (@end) is inclusive.
3725  */
fiemap_process_hole(struct btrfs_inode * inode,struct fiemap_extent_info * fieinfo,struct fiemap_cache * cache,struct btrfs_backref_shared_cache * backref_cache,u64 disk_bytenr,u64 extent_offset,u64 extent_gen,struct ulist * roots,struct ulist * tmp_ulist,u64 start,u64 end)3726 static int fiemap_process_hole(struct btrfs_inode *inode,
3727 			       struct fiemap_extent_info *fieinfo,
3728 			       struct fiemap_cache *cache,
3729 			       struct btrfs_backref_shared_cache *backref_cache,
3730 			       u64 disk_bytenr, u64 extent_offset,
3731 			       u64 extent_gen,
3732 			       struct ulist *roots, struct ulist *tmp_ulist,
3733 			       u64 start, u64 end)
3734 {
3735 	const u64 i_size = i_size_read(&inode->vfs_inode);
3736 	const u64 ino = btrfs_ino(inode);
3737 	u64 cur_offset = start;
3738 	u64 last_delalloc_end = 0;
3739 	u32 prealloc_flags = FIEMAP_EXTENT_UNWRITTEN;
3740 	bool checked_extent_shared = false;
3741 	int ret;
3742 
3743 	/*
3744 	 * There can be no delalloc past i_size, so don't waste time looking for
3745 	 * it beyond i_size.
3746 	 */
3747 	while (cur_offset < end && cur_offset < i_size) {
3748 		u64 delalloc_start;
3749 		u64 delalloc_end;
3750 		u64 prealloc_start;
3751 		u64 prealloc_len = 0;
3752 		bool delalloc;
3753 
3754 		delalloc = btrfs_find_delalloc_in_range(inode, cur_offset, end,
3755 							&delalloc_start,
3756 							&delalloc_end);
3757 		if (!delalloc)
3758 			break;
3759 
3760 		/*
3761 		 * If this is a prealloc extent we have to report every section
3762 		 * of it that has no delalloc.
3763 		 */
3764 		if (disk_bytenr != 0) {
3765 			if (last_delalloc_end == 0) {
3766 				prealloc_start = start;
3767 				prealloc_len = delalloc_start - start;
3768 			} else {
3769 				prealloc_start = last_delalloc_end + 1;
3770 				prealloc_len = delalloc_start - prealloc_start;
3771 			}
3772 		}
3773 
3774 		if (prealloc_len > 0) {
3775 			if (!checked_extent_shared && fieinfo->fi_extents_max) {
3776 				ret = btrfs_is_data_extent_shared(inode->root,
3777 							  ino, disk_bytenr,
3778 							  extent_gen, roots,
3779 							  tmp_ulist,
3780 							  backref_cache);
3781 				if (ret < 0)
3782 					return ret;
3783 				else if (ret > 0)
3784 					prealloc_flags |= FIEMAP_EXTENT_SHARED;
3785 
3786 				checked_extent_shared = true;
3787 			}
3788 			ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3789 						 disk_bytenr + extent_offset,
3790 						 prealloc_len, prealloc_flags);
3791 			if (ret)
3792 				return ret;
3793 			extent_offset += prealloc_len;
3794 		}
3795 
3796 		ret = emit_fiemap_extent(fieinfo, cache, delalloc_start, 0,
3797 					 delalloc_end + 1 - delalloc_start,
3798 					 FIEMAP_EXTENT_DELALLOC |
3799 					 FIEMAP_EXTENT_UNKNOWN);
3800 		if (ret)
3801 			return ret;
3802 
3803 		last_delalloc_end = delalloc_end;
3804 		cur_offset = delalloc_end + 1;
3805 		extent_offset += cur_offset - delalloc_start;
3806 		cond_resched();
3807 	}
3808 
3809 	/*
3810 	 * Either we found no delalloc for the whole prealloc extent or we have
3811 	 * a prealloc extent that spans i_size or starts at or after i_size.
3812 	 */
3813 	if (disk_bytenr != 0 && last_delalloc_end < end) {
3814 		u64 prealloc_start;
3815 		u64 prealloc_len;
3816 
3817 		if (last_delalloc_end == 0) {
3818 			prealloc_start = start;
3819 			prealloc_len = end + 1 - start;
3820 		} else {
3821 			prealloc_start = last_delalloc_end + 1;
3822 			prealloc_len = end + 1 - prealloc_start;
3823 		}
3824 
3825 		if (!checked_extent_shared && fieinfo->fi_extents_max) {
3826 			ret = btrfs_is_data_extent_shared(inode->root,
3827 							  ino, disk_bytenr,
3828 							  extent_gen, roots,
3829 							  tmp_ulist,
3830 							  backref_cache);
3831 			if (ret < 0)
3832 				return ret;
3833 			else if (ret > 0)
3834 				prealloc_flags |= FIEMAP_EXTENT_SHARED;
3835 		}
3836 		ret = emit_fiemap_extent(fieinfo, cache, prealloc_start,
3837 					 disk_bytenr + extent_offset,
3838 					 prealloc_len, prealloc_flags);
3839 		if (ret)
3840 			return ret;
3841 	}
3842 
3843 	return 0;
3844 }
3845 
fiemap_find_last_extent_offset(struct btrfs_inode * inode,struct btrfs_path * path,u64 * last_extent_end_ret)3846 static int fiemap_find_last_extent_offset(struct btrfs_inode *inode,
3847 					  struct btrfs_path *path,
3848 					  u64 *last_extent_end_ret)
3849 {
3850 	const u64 ino = btrfs_ino(inode);
3851 	struct btrfs_root *root = inode->root;
3852 	struct extent_buffer *leaf;
3853 	struct btrfs_file_extent_item *ei;
3854 	struct btrfs_key key;
3855 	u64 disk_bytenr;
3856 	int ret;
3857 
3858 	/*
3859 	 * Lookup the last file extent. We're not using i_size here because
3860 	 * there might be preallocation past i_size.
3861 	 */
3862 	ret = btrfs_lookup_file_extent(NULL, root, path, ino, (u64)-1, 0);
3863 	/* There can't be a file extent item at offset (u64)-1 */
3864 	ASSERT(ret != 0);
3865 	if (ret < 0)
3866 		return ret;
3867 
3868 	/*
3869 	 * For a non-existing key, btrfs_search_slot() always leaves us at a
3870 	 * slot > 0, except if the btree is empty, which is impossible because
3871 	 * at least it has the inode item for this inode and all the items for
3872 	 * the root inode 256.
3873 	 */
3874 	ASSERT(path->slots[0] > 0);
3875 	path->slots[0]--;
3876 	leaf = path->nodes[0];
3877 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3878 	if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
3879 		/* No file extent items in the subvolume tree. */
3880 		*last_extent_end_ret = 0;
3881 		return 0;
3882 	}
3883 
3884 	/*
3885 	 * For an inline extent, the disk_bytenr is where inline data starts at,
3886 	 * so first check if we have an inline extent item before checking if we
3887 	 * have an implicit hole (disk_bytenr == 0).
3888 	 */
3889 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
3890 	if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
3891 		*last_extent_end_ret = btrfs_file_extent_end(path);
3892 		return 0;
3893 	}
3894 
3895 	/*
3896 	 * Find the last file extent item that is not a hole (when NO_HOLES is
3897 	 * not enabled). This should take at most 2 iterations in the worst
3898 	 * case: we have one hole file extent item at slot 0 of a leaf and
3899 	 * another hole file extent item as the last item in the previous leaf.
3900 	 * This is because we merge file extent items that represent holes.
3901 	 */
3902 	disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3903 	while (disk_bytenr == 0) {
3904 		ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
3905 		if (ret < 0) {
3906 			return ret;
3907 		} else if (ret > 0) {
3908 			/* No file extent items that are not holes. */
3909 			*last_extent_end_ret = 0;
3910 			return 0;
3911 		}
3912 		leaf = path->nodes[0];
3913 		ei = btrfs_item_ptr(leaf, path->slots[0],
3914 				    struct btrfs_file_extent_item);
3915 		disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
3916 	}
3917 
3918 	*last_extent_end_ret = btrfs_file_extent_end(path);
3919 	return 0;
3920 }
3921 
extent_fiemap(struct btrfs_inode * inode,struct fiemap_extent_info * fieinfo,u64 start,u64 len)3922 int extent_fiemap(struct btrfs_inode *inode, struct fiemap_extent_info *fieinfo,
3923 		  u64 start, u64 len)
3924 {
3925 	const u64 ino = btrfs_ino(inode);
3926 	struct extent_state *cached_state = NULL;
3927 	struct btrfs_path *path;
3928 	struct btrfs_root *root = inode->root;
3929 	struct fiemap_cache cache = { 0 };
3930 	struct btrfs_backref_shared_cache *backref_cache;
3931 	struct ulist *roots;
3932 	struct ulist *tmp_ulist;
3933 	u64 last_extent_end;
3934 	u64 prev_extent_end;
3935 	u64 lockstart;
3936 	u64 lockend;
3937 	bool stopped = false;
3938 	int ret;
3939 
3940 	backref_cache = kzalloc(sizeof(*backref_cache), GFP_KERNEL);
3941 	path = btrfs_alloc_path();
3942 	roots = ulist_alloc(GFP_KERNEL);
3943 	tmp_ulist = ulist_alloc(GFP_KERNEL);
3944 	if (!backref_cache || !path || !roots || !tmp_ulist) {
3945 		ret = -ENOMEM;
3946 		goto out;
3947 	}
3948 
3949 	lockstart = round_down(start, root->fs_info->sectorsize);
3950 	lockend = round_up(start + len, root->fs_info->sectorsize);
3951 	prev_extent_end = lockstart;
3952 
3953 	btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
3954 	lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
3955 
3956 	ret = fiemap_find_last_extent_offset(inode, path, &last_extent_end);
3957 	if (ret < 0)
3958 		goto out_unlock;
3959 	btrfs_release_path(path);
3960 
3961 	path->reada = READA_FORWARD;
3962 	ret = fiemap_search_slot(inode, path, lockstart);
3963 	if (ret < 0) {
3964 		goto out_unlock;
3965 	} else if (ret > 0) {
3966 		/*
3967 		 * No file extent item found, but we may have delalloc between
3968 		 * the current offset and i_size. So check for that.
3969 		 */
3970 		ret = 0;
3971 		goto check_eof_delalloc;
3972 	}
3973 
3974 	while (prev_extent_end < lockend) {
3975 		struct extent_buffer *leaf = path->nodes[0];
3976 		struct btrfs_file_extent_item *ei;
3977 		struct btrfs_key key;
3978 		u64 extent_end;
3979 		u64 extent_len;
3980 		u64 extent_offset = 0;
3981 		u64 extent_gen;
3982 		u64 disk_bytenr = 0;
3983 		u64 flags = 0;
3984 		int extent_type;
3985 		u8 compression;
3986 
3987 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3988 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3989 			break;
3990 
3991 		extent_end = btrfs_file_extent_end(path);
3992 
3993 		/*
3994 		 * The first iteration can leave us at an extent item that ends
3995 		 * before our range's start. Move to the next item.
3996 		 */
3997 		if (extent_end <= lockstart)
3998 			goto next_item;
3999 
4000 		/* We have in implicit hole (NO_HOLES feature enabled). */
4001 		if (prev_extent_end < key.offset) {
4002 			const u64 range_end = min(key.offset, lockend) - 1;
4003 
4004 			ret = fiemap_process_hole(inode, fieinfo, &cache,
4005 						  backref_cache, 0, 0, 0,
4006 						  roots, tmp_ulist,
4007 						  prev_extent_end, range_end);
4008 			if (ret < 0) {
4009 				goto out_unlock;
4010 			} else if (ret > 0) {
4011 				/* fiemap_fill_next_extent() told us to stop. */
4012 				stopped = true;
4013 				break;
4014 			}
4015 
4016 			/* We've reached the end of the fiemap range, stop. */
4017 			if (key.offset >= lockend) {
4018 				stopped = true;
4019 				break;
4020 			}
4021 		}
4022 
4023 		extent_len = extent_end - key.offset;
4024 		ei = btrfs_item_ptr(leaf, path->slots[0],
4025 				    struct btrfs_file_extent_item);
4026 		compression = btrfs_file_extent_compression(leaf, ei);
4027 		extent_type = btrfs_file_extent_type(leaf, ei);
4028 		extent_gen = btrfs_file_extent_generation(leaf, ei);
4029 
4030 		if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4031 			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
4032 			if (compression == BTRFS_COMPRESS_NONE)
4033 				extent_offset = btrfs_file_extent_offset(leaf, ei);
4034 		}
4035 
4036 		if (compression != BTRFS_COMPRESS_NONE)
4037 			flags |= FIEMAP_EXTENT_ENCODED;
4038 
4039 		if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4040 			flags |= FIEMAP_EXTENT_DATA_INLINE;
4041 			flags |= FIEMAP_EXTENT_NOT_ALIGNED;
4042 			ret = emit_fiemap_extent(fieinfo, &cache, key.offset, 0,
4043 						 extent_len, flags);
4044 		} else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
4045 			ret = fiemap_process_hole(inode, fieinfo, &cache,
4046 						  backref_cache,
4047 						  disk_bytenr, extent_offset,
4048 						  extent_gen, roots, tmp_ulist,
4049 						  key.offset, extent_end - 1);
4050 		} else if (disk_bytenr == 0) {
4051 			/* We have an explicit hole. */
4052 			ret = fiemap_process_hole(inode, fieinfo, &cache,
4053 						  backref_cache, 0, 0, 0,
4054 						  roots, tmp_ulist,
4055 						  key.offset, extent_end - 1);
4056 		} else {
4057 			/* We have a regular extent. */
4058 			if (fieinfo->fi_extents_max) {
4059 				ret = btrfs_is_data_extent_shared(root, ino,
4060 								  disk_bytenr,
4061 								  extent_gen,
4062 								  roots,
4063 								  tmp_ulist,
4064 								  backref_cache);
4065 				if (ret < 0)
4066 					goto out_unlock;
4067 				else if (ret > 0)
4068 					flags |= FIEMAP_EXTENT_SHARED;
4069 			}
4070 
4071 			ret = emit_fiemap_extent(fieinfo, &cache, key.offset,
4072 						 disk_bytenr + extent_offset,
4073 						 extent_len, flags);
4074 		}
4075 
4076 		if (ret < 0) {
4077 			goto out_unlock;
4078 		} else if (ret > 0) {
4079 			/* fiemap_fill_next_extent() told us to stop. */
4080 			stopped = true;
4081 			break;
4082 		}
4083 
4084 		prev_extent_end = extent_end;
4085 next_item:
4086 		if (fatal_signal_pending(current)) {
4087 			ret = -EINTR;
4088 			goto out_unlock;
4089 		}
4090 
4091 		ret = fiemap_next_leaf_item(inode, path);
4092 		if (ret < 0) {
4093 			goto out_unlock;
4094 		} else if (ret > 0) {
4095 			/* No more file extent items for this inode. */
4096 			break;
4097 		}
4098 		cond_resched();
4099 	}
4100 
4101 check_eof_delalloc:
4102 	/*
4103 	 * Release (and free) the path before emitting any final entries to
4104 	 * fiemap_fill_next_extent() to keep lockdep happy. This is because
4105 	 * once we find no more file extent items exist, we may have a
4106 	 * non-cloned leaf, and fiemap_fill_next_extent() can trigger page
4107 	 * faults when copying data to the user space buffer.
4108 	 */
4109 	btrfs_free_path(path);
4110 	path = NULL;
4111 
4112 	if (!stopped && prev_extent_end < lockend) {
4113 		ret = fiemap_process_hole(inode, fieinfo, &cache, backref_cache,
4114 					  0, 0, 0, roots, tmp_ulist,
4115 					  prev_extent_end, lockend - 1);
4116 		if (ret < 0)
4117 			goto out_unlock;
4118 		prev_extent_end = lockend;
4119 	}
4120 
4121 	if (cache.cached && cache.offset + cache.len >= last_extent_end) {
4122 		const u64 i_size = i_size_read(&inode->vfs_inode);
4123 
4124 		if (prev_extent_end < i_size) {
4125 			u64 delalloc_start;
4126 			u64 delalloc_end;
4127 			bool delalloc;
4128 
4129 			delalloc = btrfs_find_delalloc_in_range(inode,
4130 								prev_extent_end,
4131 								i_size - 1,
4132 								&delalloc_start,
4133 								&delalloc_end);
4134 			if (!delalloc)
4135 				cache.flags |= FIEMAP_EXTENT_LAST;
4136 		} else {
4137 			cache.flags |= FIEMAP_EXTENT_LAST;
4138 		}
4139 	}
4140 
4141 	ret = emit_last_fiemap_cache(fieinfo, &cache);
4142 
4143 out_unlock:
4144 	unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
4145 	btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
4146 out:
4147 	kfree(backref_cache);
4148 	btrfs_free_path(path);
4149 	ulist_free(roots);
4150 	ulist_free(tmp_ulist);
4151 	return ret;
4152 }
4153 
__free_extent_buffer(struct extent_buffer * eb)4154 static void __free_extent_buffer(struct extent_buffer *eb)
4155 {
4156 	kmem_cache_free(extent_buffer_cache, eb);
4157 }
4158 
extent_buffer_under_io(const struct extent_buffer * eb)4159 int extent_buffer_under_io(const struct extent_buffer *eb)
4160 {
4161 	return (atomic_read(&eb->io_pages) ||
4162 		test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
4163 		test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4164 }
4165 
page_range_has_eb(struct btrfs_fs_info * fs_info,struct page * page)4166 static bool page_range_has_eb(struct btrfs_fs_info *fs_info, struct page *page)
4167 {
4168 	struct btrfs_subpage *subpage;
4169 
4170 	lockdep_assert_held(&page->mapping->private_lock);
4171 
4172 	if (PagePrivate(page)) {
4173 		subpage = (struct btrfs_subpage *)page->private;
4174 		if (atomic_read(&subpage->eb_refs))
4175 			return true;
4176 		/*
4177 		 * Even there is no eb refs here, we may still have
4178 		 * end_page_read() call relying on page::private.
4179 		 */
4180 		if (atomic_read(&subpage->readers))
4181 			return true;
4182 	}
4183 	return false;
4184 }
4185 
detach_extent_buffer_page(struct extent_buffer * eb,struct page * page)4186 static void detach_extent_buffer_page(struct extent_buffer *eb, struct page *page)
4187 {
4188 	struct btrfs_fs_info *fs_info = eb->fs_info;
4189 	const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4190 
4191 	/*
4192 	 * For mapped eb, we're going to change the page private, which should
4193 	 * be done under the private_lock.
4194 	 */
4195 	if (mapped)
4196 		spin_lock(&page->mapping->private_lock);
4197 
4198 	if (!PagePrivate(page)) {
4199 		if (mapped)
4200 			spin_unlock(&page->mapping->private_lock);
4201 		return;
4202 	}
4203 
4204 	if (fs_info->nodesize >= PAGE_SIZE) {
4205 		/*
4206 		 * We do this since we'll remove the pages after we've
4207 		 * removed the eb from the radix tree, so we could race
4208 		 * and have this page now attached to the new eb.  So
4209 		 * only clear page_private if it's still connected to
4210 		 * this eb.
4211 		 */
4212 		if (PagePrivate(page) &&
4213 		    page->private == (unsigned long)eb) {
4214 			BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
4215 			BUG_ON(PageDirty(page));
4216 			BUG_ON(PageWriteback(page));
4217 			/*
4218 			 * We need to make sure we haven't be attached
4219 			 * to a new eb.
4220 			 */
4221 			detach_page_private(page);
4222 		}
4223 		if (mapped)
4224 			spin_unlock(&page->mapping->private_lock);
4225 		return;
4226 	}
4227 
4228 	/*
4229 	 * For subpage, we can have dummy eb with page private.  In this case,
4230 	 * we can directly detach the private as such page is only attached to
4231 	 * one dummy eb, no sharing.
4232 	 */
4233 	if (!mapped) {
4234 		btrfs_detach_subpage(fs_info, page);
4235 		return;
4236 	}
4237 
4238 	btrfs_page_dec_eb_refs(fs_info, page);
4239 
4240 	/*
4241 	 * We can only detach the page private if there are no other ebs in the
4242 	 * page range and no unfinished IO.
4243 	 */
4244 	if (!page_range_has_eb(fs_info, page))
4245 		btrfs_detach_subpage(fs_info, page);
4246 
4247 	spin_unlock(&page->mapping->private_lock);
4248 }
4249 
4250 /* Release all pages attached to the extent buffer */
btrfs_release_extent_buffer_pages(struct extent_buffer * eb)4251 static void btrfs_release_extent_buffer_pages(struct extent_buffer *eb)
4252 {
4253 	int i;
4254 	int num_pages;
4255 
4256 	ASSERT(!extent_buffer_under_io(eb));
4257 
4258 	num_pages = num_extent_pages(eb);
4259 	for (i = 0; i < num_pages; i++) {
4260 		struct page *page = eb->pages[i];
4261 
4262 		if (!page)
4263 			continue;
4264 
4265 		detach_extent_buffer_page(eb, page);
4266 
4267 		/* One for when we allocated the page */
4268 		put_page(page);
4269 	}
4270 }
4271 
4272 /*
4273  * Helper for releasing the extent buffer.
4274  */
btrfs_release_extent_buffer(struct extent_buffer * eb)4275 static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
4276 {
4277 	btrfs_release_extent_buffer_pages(eb);
4278 	btrfs_leak_debug_del_eb(eb);
4279 	__free_extent_buffer(eb);
4280 }
4281 
4282 static struct extent_buffer *
__alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)4283 __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
4284 		      unsigned long len)
4285 {
4286 	struct extent_buffer *eb = NULL;
4287 
4288 	eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
4289 	eb->start = start;
4290 	eb->len = len;
4291 	eb->fs_info = fs_info;
4292 	eb->bflags = 0;
4293 	init_rwsem(&eb->lock);
4294 
4295 	btrfs_leak_debug_add_eb(eb);
4296 	INIT_LIST_HEAD(&eb->release_list);
4297 
4298 	spin_lock_init(&eb->refs_lock);
4299 	atomic_set(&eb->refs, 1);
4300 	atomic_set(&eb->io_pages, 0);
4301 
4302 	ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
4303 
4304 	return eb;
4305 }
4306 
btrfs_clone_extent_buffer(const struct extent_buffer * src)4307 struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
4308 {
4309 	int i;
4310 	struct extent_buffer *new;
4311 	int num_pages = num_extent_pages(src);
4312 	int ret;
4313 
4314 	new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
4315 	if (new == NULL)
4316 		return NULL;
4317 
4318 	/*
4319 	 * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
4320 	 * btrfs_release_extent_buffer() have different behavior for
4321 	 * UNMAPPED subpage extent buffer.
4322 	 */
4323 	set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
4324 
4325 	memset(new->pages, 0, sizeof(*new->pages) * num_pages);
4326 	ret = btrfs_alloc_page_array(num_pages, new->pages);
4327 	if (ret) {
4328 		btrfs_release_extent_buffer(new);
4329 		return NULL;
4330 	}
4331 
4332 	for (i = 0; i < num_pages; i++) {
4333 		int ret;
4334 		struct page *p = new->pages[i];
4335 
4336 		ret = attach_extent_buffer_page(new, p, NULL);
4337 		if (ret < 0) {
4338 			btrfs_release_extent_buffer(new);
4339 			return NULL;
4340 		}
4341 		WARN_ON(PageDirty(p));
4342 		copy_page(page_address(p), page_address(src->pages[i]));
4343 	}
4344 	set_extent_buffer_uptodate(new);
4345 
4346 	return new;
4347 }
4348 
__alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,unsigned long len)4349 struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4350 						  u64 start, unsigned long len)
4351 {
4352 	struct extent_buffer *eb;
4353 	int num_pages;
4354 	int i;
4355 	int ret;
4356 
4357 	eb = __alloc_extent_buffer(fs_info, start, len);
4358 	if (!eb)
4359 		return NULL;
4360 
4361 	num_pages = num_extent_pages(eb);
4362 	ret = btrfs_alloc_page_array(num_pages, eb->pages);
4363 	if (ret)
4364 		goto err;
4365 
4366 	for (i = 0; i < num_pages; i++) {
4367 		struct page *p = eb->pages[i];
4368 
4369 		ret = attach_extent_buffer_page(eb, p, NULL);
4370 		if (ret < 0)
4371 			goto err;
4372 	}
4373 
4374 	set_extent_buffer_uptodate(eb);
4375 	btrfs_set_header_nritems(eb, 0);
4376 	set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
4377 
4378 	return eb;
4379 err:
4380 	for (i = 0; i < num_pages; i++) {
4381 		if (eb->pages[i]) {
4382 			detach_extent_buffer_page(eb, eb->pages[i]);
4383 			__free_page(eb->pages[i]);
4384 		}
4385 	}
4386 	__free_extent_buffer(eb);
4387 	return NULL;
4388 }
4389 
alloc_dummy_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)4390 struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
4391 						u64 start)
4392 {
4393 	return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
4394 }
4395 
check_buffer_tree_ref(struct extent_buffer * eb)4396 static void check_buffer_tree_ref(struct extent_buffer *eb)
4397 {
4398 	int refs;
4399 	/*
4400 	 * The TREE_REF bit is first set when the extent_buffer is added
4401 	 * to the radix tree. It is also reset, if unset, when a new reference
4402 	 * is created by find_extent_buffer.
4403 	 *
4404 	 * It is only cleared in two cases: freeing the last non-tree
4405 	 * reference to the extent_buffer when its STALE bit is set or
4406 	 * calling release_folio when the tree reference is the only reference.
4407 	 *
4408 	 * In both cases, care is taken to ensure that the extent_buffer's
4409 	 * pages are not under io. However, release_folio can be concurrently
4410 	 * called with creating new references, which is prone to race
4411 	 * conditions between the calls to check_buffer_tree_ref in those
4412 	 * codepaths and clearing TREE_REF in try_release_extent_buffer.
4413 	 *
4414 	 * The actual lifetime of the extent_buffer in the radix tree is
4415 	 * adequately protected by the refcount, but the TREE_REF bit and
4416 	 * its corresponding reference are not. To protect against this
4417 	 * class of races, we call check_buffer_tree_ref from the codepaths
4418 	 * which trigger io after they set eb->io_pages. Note that once io is
4419 	 * initiated, TREE_REF can no longer be cleared, so that is the
4420 	 * moment at which any such race is best fixed.
4421 	 */
4422 	refs = atomic_read(&eb->refs);
4423 	if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4424 		return;
4425 
4426 	spin_lock(&eb->refs_lock);
4427 	if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4428 		atomic_inc(&eb->refs);
4429 	spin_unlock(&eb->refs_lock);
4430 }
4431 
mark_extent_buffer_accessed(struct extent_buffer * eb,struct page * accessed)4432 static void mark_extent_buffer_accessed(struct extent_buffer *eb,
4433 		struct page *accessed)
4434 {
4435 	int num_pages, i;
4436 
4437 	check_buffer_tree_ref(eb);
4438 
4439 	num_pages = num_extent_pages(eb);
4440 	for (i = 0; i < num_pages; i++) {
4441 		struct page *p = eb->pages[i];
4442 
4443 		if (p != accessed)
4444 			mark_page_accessed(p);
4445 	}
4446 }
4447 
find_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)4448 struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
4449 					 u64 start)
4450 {
4451 	struct extent_buffer *eb;
4452 
4453 	eb = find_extent_buffer_nolock(fs_info, start);
4454 	if (!eb)
4455 		return NULL;
4456 	/*
4457 	 * Lock our eb's refs_lock to avoid races with free_extent_buffer().
4458 	 * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
4459 	 * another task running free_extent_buffer() might have seen that flag
4460 	 * set, eb->refs == 2, that the buffer isn't under IO (dirty and
4461 	 * writeback flags not set) and it's still in the tree (flag
4462 	 * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
4463 	 * decrementing the extent buffer's reference count twice.  So here we
4464 	 * could race and increment the eb's reference count, clear its stale
4465 	 * flag, mark it as dirty and drop our reference before the other task
4466 	 * finishes executing free_extent_buffer, which would later result in
4467 	 * an attempt to free an extent buffer that is dirty.
4468 	 */
4469 	if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
4470 		spin_lock(&eb->refs_lock);
4471 		spin_unlock(&eb->refs_lock);
4472 	}
4473 	mark_extent_buffer_accessed(eb, NULL);
4474 	return eb;
4475 }
4476 
4477 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
alloc_test_extent_buffer(struct btrfs_fs_info * fs_info,u64 start)4478 struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
4479 					u64 start)
4480 {
4481 	struct extent_buffer *eb, *exists = NULL;
4482 	int ret;
4483 
4484 	eb = find_extent_buffer(fs_info, start);
4485 	if (eb)
4486 		return eb;
4487 	eb = alloc_dummy_extent_buffer(fs_info, start);
4488 	if (!eb)
4489 		return ERR_PTR(-ENOMEM);
4490 	eb->fs_info = fs_info;
4491 again:
4492 	ret = radix_tree_preload(GFP_NOFS);
4493 	if (ret) {
4494 		exists = ERR_PTR(ret);
4495 		goto free_eb;
4496 	}
4497 	spin_lock(&fs_info->buffer_lock);
4498 	ret = radix_tree_insert(&fs_info->buffer_radix,
4499 				start >> fs_info->sectorsize_bits, eb);
4500 	spin_unlock(&fs_info->buffer_lock);
4501 	radix_tree_preload_end();
4502 	if (ret == -EEXIST) {
4503 		exists = find_extent_buffer(fs_info, start);
4504 		if (exists)
4505 			goto free_eb;
4506 		else
4507 			goto again;
4508 	}
4509 	check_buffer_tree_ref(eb);
4510 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4511 
4512 	return eb;
4513 free_eb:
4514 	btrfs_release_extent_buffer(eb);
4515 	return exists;
4516 }
4517 #endif
4518 
grab_extent_buffer(struct btrfs_fs_info * fs_info,struct page * page)4519 static struct extent_buffer *grab_extent_buffer(
4520 		struct btrfs_fs_info *fs_info, struct page *page)
4521 {
4522 	struct extent_buffer *exists;
4523 
4524 	/*
4525 	 * For subpage case, we completely rely on radix tree to ensure we
4526 	 * don't try to insert two ebs for the same bytenr.  So here we always
4527 	 * return NULL and just continue.
4528 	 */
4529 	if (fs_info->nodesize < PAGE_SIZE)
4530 		return NULL;
4531 
4532 	/* Page not yet attached to an extent buffer */
4533 	if (!PagePrivate(page))
4534 		return NULL;
4535 
4536 	/*
4537 	 * We could have already allocated an eb for this page and attached one
4538 	 * so lets see if we can get a ref on the existing eb, and if we can we
4539 	 * know it's good and we can just return that one, else we know we can
4540 	 * just overwrite page->private.
4541 	 */
4542 	exists = (struct extent_buffer *)page->private;
4543 	if (atomic_inc_not_zero(&exists->refs))
4544 		return exists;
4545 
4546 	WARN_ON(PageDirty(page));
4547 	detach_page_private(page);
4548 	return NULL;
4549 }
4550 
check_eb_alignment(struct btrfs_fs_info * fs_info,u64 start)4551 static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
4552 {
4553 	if (!IS_ALIGNED(start, fs_info->sectorsize)) {
4554 		btrfs_err(fs_info, "bad tree block start %llu", start);
4555 		return -EINVAL;
4556 	}
4557 
4558 	if (fs_info->nodesize < PAGE_SIZE &&
4559 	    offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
4560 		btrfs_err(fs_info,
4561 		"tree block crosses page boundary, start %llu nodesize %u",
4562 			  start, fs_info->nodesize);
4563 		return -EINVAL;
4564 	}
4565 	if (fs_info->nodesize >= PAGE_SIZE &&
4566 	    !PAGE_ALIGNED(start)) {
4567 		btrfs_err(fs_info,
4568 		"tree block is not page aligned, start %llu nodesize %u",
4569 			  start, fs_info->nodesize);
4570 		return -EINVAL;
4571 	}
4572 	return 0;
4573 }
4574 
alloc_extent_buffer(struct btrfs_fs_info * fs_info,u64 start,u64 owner_root,int level)4575 struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
4576 					  u64 start, u64 owner_root, int level)
4577 {
4578 	unsigned long len = fs_info->nodesize;
4579 	int num_pages;
4580 	int i;
4581 	unsigned long index = start >> PAGE_SHIFT;
4582 	struct extent_buffer *eb;
4583 	struct extent_buffer *exists = NULL;
4584 	struct page *p;
4585 	struct address_space *mapping = fs_info->btree_inode->i_mapping;
4586 	u64 lockdep_owner = owner_root;
4587 	int uptodate = 1;
4588 	int ret;
4589 
4590 	if (check_eb_alignment(fs_info, start))
4591 		return ERR_PTR(-EINVAL);
4592 
4593 #if BITS_PER_LONG == 32
4594 	if (start >= MAX_LFS_FILESIZE) {
4595 		btrfs_err_rl(fs_info,
4596 		"extent buffer %llu is beyond 32bit page cache limit", start);
4597 		btrfs_err_32bit_limit(fs_info);
4598 		return ERR_PTR(-EOVERFLOW);
4599 	}
4600 	if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
4601 		btrfs_warn_32bit_limit(fs_info);
4602 #endif
4603 
4604 	eb = find_extent_buffer(fs_info, start);
4605 	if (eb)
4606 		return eb;
4607 
4608 	eb = __alloc_extent_buffer(fs_info, start, len);
4609 	if (!eb)
4610 		return ERR_PTR(-ENOMEM);
4611 
4612 	/*
4613 	 * The reloc trees are just snapshots, so we need them to appear to be
4614 	 * just like any other fs tree WRT lockdep.
4615 	 */
4616 	if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
4617 		lockdep_owner = BTRFS_FS_TREE_OBJECTID;
4618 
4619 	btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
4620 
4621 	num_pages = num_extent_pages(eb);
4622 	for (i = 0; i < num_pages; i++, index++) {
4623 		struct btrfs_subpage *prealloc = NULL;
4624 
4625 		p = find_or_create_page(mapping, index, GFP_NOFS|__GFP_NOFAIL);
4626 		if (!p) {
4627 			exists = ERR_PTR(-ENOMEM);
4628 			goto free_eb;
4629 		}
4630 
4631 		/*
4632 		 * Preallocate page->private for subpage case, so that we won't
4633 		 * allocate memory with private_lock hold.  The memory will be
4634 		 * freed by attach_extent_buffer_page() or freed manually if
4635 		 * we exit earlier.
4636 		 *
4637 		 * Although we have ensured one subpage eb can only have one
4638 		 * page, but it may change in the future for 16K page size
4639 		 * support, so we still preallocate the memory in the loop.
4640 		 */
4641 		if (fs_info->nodesize < PAGE_SIZE) {
4642 			prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
4643 			if (IS_ERR(prealloc)) {
4644 				ret = PTR_ERR(prealloc);
4645 				unlock_page(p);
4646 				put_page(p);
4647 				exists = ERR_PTR(ret);
4648 				goto free_eb;
4649 			}
4650 		}
4651 
4652 		spin_lock(&mapping->private_lock);
4653 		exists = grab_extent_buffer(fs_info, p);
4654 		if (exists) {
4655 			spin_unlock(&mapping->private_lock);
4656 			unlock_page(p);
4657 			put_page(p);
4658 			mark_extent_buffer_accessed(exists, p);
4659 			btrfs_free_subpage(prealloc);
4660 			goto free_eb;
4661 		}
4662 		/* Should not fail, as we have preallocated the memory */
4663 		ret = attach_extent_buffer_page(eb, p, prealloc);
4664 		ASSERT(!ret);
4665 		/*
4666 		 * To inform we have extra eb under allocation, so that
4667 		 * detach_extent_buffer_page() won't release the page private
4668 		 * when the eb hasn't yet been inserted into radix tree.
4669 		 *
4670 		 * The ref will be decreased when the eb released the page, in
4671 		 * detach_extent_buffer_page().
4672 		 * Thus needs no special handling in error path.
4673 		 */
4674 		btrfs_page_inc_eb_refs(fs_info, p);
4675 		spin_unlock(&mapping->private_lock);
4676 
4677 		WARN_ON(btrfs_page_test_dirty(fs_info, p, eb->start, eb->len));
4678 		eb->pages[i] = p;
4679 		if (!PageUptodate(p))
4680 			uptodate = 0;
4681 
4682 		/*
4683 		 * We can't unlock the pages just yet since the extent buffer
4684 		 * hasn't been properly inserted in the radix tree, this
4685 		 * opens a race with btree_release_folio which can free a page
4686 		 * while we are still filling in all pages for the buffer and
4687 		 * we could crash.
4688 		 */
4689 	}
4690 	if (uptodate)
4691 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4692 again:
4693 	ret = radix_tree_preload(GFP_NOFS);
4694 	if (ret) {
4695 		exists = ERR_PTR(ret);
4696 		goto free_eb;
4697 	}
4698 
4699 	spin_lock(&fs_info->buffer_lock);
4700 	ret = radix_tree_insert(&fs_info->buffer_radix,
4701 				start >> fs_info->sectorsize_bits, eb);
4702 	spin_unlock(&fs_info->buffer_lock);
4703 	radix_tree_preload_end();
4704 	if (ret == -EEXIST) {
4705 		exists = find_extent_buffer(fs_info, start);
4706 		if (exists)
4707 			goto free_eb;
4708 		else
4709 			goto again;
4710 	}
4711 	/* add one reference for the tree */
4712 	check_buffer_tree_ref(eb);
4713 	set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
4714 
4715 	/*
4716 	 * Now it's safe to unlock the pages because any calls to
4717 	 * btree_release_folio will correctly detect that a page belongs to a
4718 	 * live buffer and won't free them prematurely.
4719 	 */
4720 	for (i = 0; i < num_pages; i++)
4721 		unlock_page(eb->pages[i]);
4722 	return eb;
4723 
4724 free_eb:
4725 	WARN_ON(!atomic_dec_and_test(&eb->refs));
4726 	for (i = 0; i < num_pages; i++) {
4727 		if (eb->pages[i])
4728 			unlock_page(eb->pages[i]);
4729 	}
4730 
4731 	btrfs_release_extent_buffer(eb);
4732 	return exists;
4733 }
4734 
btrfs_release_extent_buffer_rcu(struct rcu_head * head)4735 static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
4736 {
4737 	struct extent_buffer *eb =
4738 			container_of(head, struct extent_buffer, rcu_head);
4739 
4740 	__free_extent_buffer(eb);
4741 }
4742 
release_extent_buffer(struct extent_buffer * eb)4743 static int release_extent_buffer(struct extent_buffer *eb)
4744 	__releases(&eb->refs_lock)
4745 {
4746 	lockdep_assert_held(&eb->refs_lock);
4747 
4748 	WARN_ON(atomic_read(&eb->refs) == 0);
4749 	if (atomic_dec_and_test(&eb->refs)) {
4750 		if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
4751 			struct btrfs_fs_info *fs_info = eb->fs_info;
4752 
4753 			spin_unlock(&eb->refs_lock);
4754 
4755 			spin_lock(&fs_info->buffer_lock);
4756 			radix_tree_delete(&fs_info->buffer_radix,
4757 					  eb->start >> fs_info->sectorsize_bits);
4758 			spin_unlock(&fs_info->buffer_lock);
4759 		} else {
4760 			spin_unlock(&eb->refs_lock);
4761 		}
4762 
4763 		btrfs_leak_debug_del_eb(eb);
4764 		/* Should be safe to release our pages at this point */
4765 		btrfs_release_extent_buffer_pages(eb);
4766 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4767 		if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
4768 			__free_extent_buffer(eb);
4769 			return 1;
4770 		}
4771 #endif
4772 		call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
4773 		return 1;
4774 	}
4775 	spin_unlock(&eb->refs_lock);
4776 
4777 	return 0;
4778 }
4779 
free_extent_buffer(struct extent_buffer * eb)4780 void free_extent_buffer(struct extent_buffer *eb)
4781 {
4782 	int refs;
4783 	if (!eb)
4784 		return;
4785 
4786 	refs = atomic_read(&eb->refs);
4787 	while (1) {
4788 		if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
4789 		    || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
4790 			refs == 1))
4791 			break;
4792 		if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
4793 			return;
4794 	}
4795 
4796 	spin_lock(&eb->refs_lock);
4797 	if (atomic_read(&eb->refs) == 2 &&
4798 	    test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
4799 	    !extent_buffer_under_io(eb) &&
4800 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4801 		atomic_dec(&eb->refs);
4802 
4803 	/*
4804 	 * I know this is terrible, but it's temporary until we stop tracking
4805 	 * the uptodate bits and such for the extent buffers.
4806 	 */
4807 	release_extent_buffer(eb);
4808 }
4809 
free_extent_buffer_stale(struct extent_buffer * eb)4810 void free_extent_buffer_stale(struct extent_buffer *eb)
4811 {
4812 	if (!eb)
4813 		return;
4814 
4815 	spin_lock(&eb->refs_lock);
4816 	set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
4817 
4818 	if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
4819 	    test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
4820 		atomic_dec(&eb->refs);
4821 	release_extent_buffer(eb);
4822 }
4823 
btree_clear_page_dirty(struct page * page)4824 static void btree_clear_page_dirty(struct page *page)
4825 {
4826 	ASSERT(PageDirty(page));
4827 	ASSERT(PageLocked(page));
4828 	clear_page_dirty_for_io(page);
4829 	xa_lock_irq(&page->mapping->i_pages);
4830 	if (!PageDirty(page))
4831 		__xa_clear_mark(&page->mapping->i_pages,
4832 				page_index(page), PAGECACHE_TAG_DIRTY);
4833 	xa_unlock_irq(&page->mapping->i_pages);
4834 }
4835 
clear_subpage_extent_buffer_dirty(const struct extent_buffer * eb)4836 static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
4837 {
4838 	struct btrfs_fs_info *fs_info = eb->fs_info;
4839 	struct page *page = eb->pages[0];
4840 	bool last;
4841 
4842 	/* btree_clear_page_dirty() needs page locked */
4843 	lock_page(page);
4844 	last = btrfs_subpage_clear_and_test_dirty(fs_info, page, eb->start,
4845 						  eb->len);
4846 	if (last)
4847 		btree_clear_page_dirty(page);
4848 	unlock_page(page);
4849 	WARN_ON(atomic_read(&eb->refs) == 0);
4850 }
4851 
clear_extent_buffer_dirty(const struct extent_buffer * eb)4852 void clear_extent_buffer_dirty(const struct extent_buffer *eb)
4853 {
4854 	int i;
4855 	int num_pages;
4856 	struct page *page;
4857 
4858 	if (eb->fs_info->nodesize < PAGE_SIZE)
4859 		return clear_subpage_extent_buffer_dirty(eb);
4860 
4861 	num_pages = num_extent_pages(eb);
4862 
4863 	for (i = 0; i < num_pages; i++) {
4864 		page = eb->pages[i];
4865 		if (!PageDirty(page))
4866 			continue;
4867 		lock_page(page);
4868 		btree_clear_page_dirty(page);
4869 		ClearPageError(page);
4870 		unlock_page(page);
4871 	}
4872 	WARN_ON(atomic_read(&eb->refs) == 0);
4873 }
4874 
set_extent_buffer_dirty(struct extent_buffer * eb)4875 bool set_extent_buffer_dirty(struct extent_buffer *eb)
4876 {
4877 	int i;
4878 	int num_pages;
4879 	bool was_dirty;
4880 
4881 	check_buffer_tree_ref(eb);
4882 
4883 	was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
4884 
4885 	num_pages = num_extent_pages(eb);
4886 	WARN_ON(atomic_read(&eb->refs) == 0);
4887 	WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
4888 
4889 	if (!was_dirty) {
4890 		bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
4891 
4892 		/*
4893 		 * For subpage case, we can have other extent buffers in the
4894 		 * same page, and in clear_subpage_extent_buffer_dirty() we
4895 		 * have to clear page dirty without subpage lock held.
4896 		 * This can cause race where our page gets dirty cleared after
4897 		 * we just set it.
4898 		 *
4899 		 * Thankfully, clear_subpage_extent_buffer_dirty() has locked
4900 		 * its page for other reasons, we can use page lock to prevent
4901 		 * the above race.
4902 		 */
4903 		if (subpage)
4904 			lock_page(eb->pages[0]);
4905 		for (i = 0; i < num_pages; i++)
4906 			btrfs_page_set_dirty(eb->fs_info, eb->pages[i],
4907 					     eb->start, eb->len);
4908 		if (subpage)
4909 			unlock_page(eb->pages[0]);
4910 	}
4911 #ifdef CONFIG_BTRFS_DEBUG
4912 	for (i = 0; i < num_pages; i++)
4913 		ASSERT(PageDirty(eb->pages[i]));
4914 #endif
4915 
4916 	return was_dirty;
4917 }
4918 
clear_extent_buffer_uptodate(struct extent_buffer * eb)4919 void clear_extent_buffer_uptodate(struct extent_buffer *eb)
4920 {
4921 	struct btrfs_fs_info *fs_info = eb->fs_info;
4922 	struct page *page;
4923 	int num_pages;
4924 	int i;
4925 
4926 	clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4927 	num_pages = num_extent_pages(eb);
4928 	for (i = 0; i < num_pages; i++) {
4929 		page = eb->pages[i];
4930 		if (!page)
4931 			continue;
4932 
4933 		/*
4934 		 * This is special handling for metadata subpage, as regular
4935 		 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4936 		 */
4937 		if (fs_info->nodesize >= PAGE_SIZE)
4938 			ClearPageUptodate(page);
4939 		else
4940 			btrfs_subpage_clear_uptodate(fs_info, page, eb->start,
4941 						     eb->len);
4942 	}
4943 }
4944 
set_extent_buffer_uptodate(struct extent_buffer * eb)4945 void set_extent_buffer_uptodate(struct extent_buffer *eb)
4946 {
4947 	struct btrfs_fs_info *fs_info = eb->fs_info;
4948 	struct page *page;
4949 	int num_pages;
4950 	int i;
4951 
4952 	set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4953 	num_pages = num_extent_pages(eb);
4954 	for (i = 0; i < num_pages; i++) {
4955 		page = eb->pages[i];
4956 
4957 		/*
4958 		 * This is special handling for metadata subpage, as regular
4959 		 * btrfs_is_subpage() can not handle cloned/dummy metadata.
4960 		 */
4961 		if (fs_info->nodesize >= PAGE_SIZE)
4962 			SetPageUptodate(page);
4963 		else
4964 			btrfs_subpage_set_uptodate(fs_info, page, eb->start,
4965 						   eb->len);
4966 	}
4967 }
4968 
read_extent_buffer_subpage(struct extent_buffer * eb,int wait,int mirror_num)4969 static int read_extent_buffer_subpage(struct extent_buffer *eb, int wait,
4970 				      int mirror_num)
4971 {
4972 	struct btrfs_fs_info *fs_info = eb->fs_info;
4973 	struct extent_io_tree *io_tree;
4974 	struct page *page = eb->pages[0];
4975 	struct btrfs_bio_ctrl bio_ctrl = {
4976 		.mirror_num = mirror_num,
4977 	};
4978 	int ret = 0;
4979 
4980 	ASSERT(!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags));
4981 	ASSERT(PagePrivate(page));
4982 	io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
4983 
4984 	if (wait == WAIT_NONE) {
4985 		if (!try_lock_extent(io_tree, eb->start, eb->start + eb->len - 1))
4986 			return -EAGAIN;
4987 	} else {
4988 		ret = lock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4989 		if (ret < 0)
4990 			return ret;
4991 	}
4992 
4993 	ret = 0;
4994 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags) ||
4995 	    PageUptodate(page) ||
4996 	    btrfs_subpage_test_uptodate(fs_info, page, eb->start, eb->len)) {
4997 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
4998 		unlock_extent(io_tree, eb->start, eb->start + eb->len - 1, NULL);
4999 		return ret;
5000 	}
5001 
5002 	clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5003 	eb->read_mirror = 0;
5004 	atomic_set(&eb->io_pages, 1);
5005 	check_buffer_tree_ref(eb);
5006 	bio_ctrl.end_io_func = end_bio_extent_readpage;
5007 
5008 	btrfs_subpage_clear_error(fs_info, page, eb->start, eb->len);
5009 
5010 	btrfs_subpage_start_reader(fs_info, page, eb->start, eb->len);
5011 	ret = submit_extent_page(REQ_OP_READ, NULL, &bio_ctrl,
5012 				 eb->start, page, eb->len,
5013 				 eb->start - page_offset(page), 0, true);
5014 	if (ret) {
5015 		/*
5016 		 * In the endio function, if we hit something wrong we will
5017 		 * increase the io_pages, so here we need to decrease it for
5018 		 * error path.
5019 		 */
5020 		atomic_dec(&eb->io_pages);
5021 	}
5022 	submit_one_bio(&bio_ctrl);
5023 	if (ret || wait != WAIT_COMPLETE)
5024 		return ret;
5025 
5026 	wait_extent_bit(io_tree, eb->start, eb->start + eb->len - 1, EXTENT_LOCKED);
5027 	if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5028 		ret = -EIO;
5029 	return ret;
5030 }
5031 
read_extent_buffer_pages(struct extent_buffer * eb,int wait,int mirror_num)5032 int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num)
5033 {
5034 	int i;
5035 	struct page *page;
5036 	int err;
5037 	int ret = 0;
5038 	int locked_pages = 0;
5039 	int all_uptodate = 1;
5040 	int num_pages;
5041 	unsigned long num_reads = 0;
5042 	struct btrfs_bio_ctrl bio_ctrl = {
5043 		.mirror_num = mirror_num,
5044 	};
5045 
5046 	if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
5047 		return 0;
5048 
5049 	/*
5050 	 * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
5051 	 * operation, which could potentially still be in flight.  In this case
5052 	 * we simply want to return an error.
5053 	 */
5054 	if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
5055 		return -EIO;
5056 
5057 	if (eb->fs_info->nodesize < PAGE_SIZE)
5058 		return read_extent_buffer_subpage(eb, wait, mirror_num);
5059 
5060 	num_pages = num_extent_pages(eb);
5061 	for (i = 0; i < num_pages; i++) {
5062 		page = eb->pages[i];
5063 		if (wait == WAIT_NONE) {
5064 			/*
5065 			 * WAIT_NONE is only utilized by readahead. If we can't
5066 			 * acquire the lock atomically it means either the eb
5067 			 * is being read out or under modification.
5068 			 * Either way the eb will be or has been cached,
5069 			 * readahead can exit safely.
5070 			 */
5071 			if (!trylock_page(page))
5072 				goto unlock_exit;
5073 		} else {
5074 			lock_page(page);
5075 		}
5076 		locked_pages++;
5077 	}
5078 	/*
5079 	 * We need to firstly lock all pages to make sure that
5080 	 * the uptodate bit of our pages won't be affected by
5081 	 * clear_extent_buffer_uptodate().
5082 	 */
5083 	for (i = 0; i < num_pages; i++) {
5084 		page = eb->pages[i];
5085 		if (!PageUptodate(page)) {
5086 			num_reads++;
5087 			all_uptodate = 0;
5088 		}
5089 	}
5090 
5091 	if (all_uptodate) {
5092 		set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
5093 		goto unlock_exit;
5094 	}
5095 
5096 	clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
5097 	eb->read_mirror = 0;
5098 	atomic_set(&eb->io_pages, num_reads);
5099 	/*
5100 	 * It is possible for release_folio to clear the TREE_REF bit before we
5101 	 * set io_pages. See check_buffer_tree_ref for a more detailed comment.
5102 	 */
5103 	check_buffer_tree_ref(eb);
5104 	bio_ctrl.end_io_func = end_bio_extent_readpage;
5105 	for (i = 0; i < num_pages; i++) {
5106 		page = eb->pages[i];
5107 
5108 		if (!PageUptodate(page)) {
5109 			if (ret) {
5110 				atomic_dec(&eb->io_pages);
5111 				unlock_page(page);
5112 				continue;
5113 			}
5114 
5115 			ClearPageError(page);
5116 			err = submit_extent_page(REQ_OP_READ, NULL,
5117 					 &bio_ctrl, page_offset(page), page,
5118 					 PAGE_SIZE, 0, 0, false);
5119 			if (err) {
5120 				/*
5121 				 * We failed to submit the bio so it's the
5122 				 * caller's responsibility to perform cleanup
5123 				 * i.e unlock page/set error bit.
5124 				 */
5125 				ret = err;
5126 				SetPageError(page);
5127 				unlock_page(page);
5128 				atomic_dec(&eb->io_pages);
5129 			}
5130 		} else {
5131 			unlock_page(page);
5132 		}
5133 	}
5134 
5135 	submit_one_bio(&bio_ctrl);
5136 
5137 	if (ret || wait != WAIT_COMPLETE)
5138 		return ret;
5139 
5140 	for (i = 0; i < num_pages; i++) {
5141 		page = eb->pages[i];
5142 		wait_on_page_locked(page);
5143 		if (!PageUptodate(page))
5144 			ret = -EIO;
5145 	}
5146 
5147 	return ret;
5148 
5149 unlock_exit:
5150 	while (locked_pages > 0) {
5151 		locked_pages--;
5152 		page = eb->pages[locked_pages];
5153 		unlock_page(page);
5154 	}
5155 	return ret;
5156 }
5157 
report_eb_range(const struct extent_buffer * eb,unsigned long start,unsigned long len)5158 static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
5159 			    unsigned long len)
5160 {
5161 	btrfs_warn(eb->fs_info,
5162 		"access to eb bytenr %llu len %lu out of range start %lu len %lu",
5163 		eb->start, eb->len, start, len);
5164 	WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5165 
5166 	return true;
5167 }
5168 
5169 /*
5170  * Check if the [start, start + len) range is valid before reading/writing
5171  * the eb.
5172  * NOTE: @start and @len are offset inside the eb, not logical address.
5173  *
5174  * Caller should not touch the dst/src memory if this function returns error.
5175  */
check_eb_range(const struct extent_buffer * eb,unsigned long start,unsigned long len)5176 static inline int check_eb_range(const struct extent_buffer *eb,
5177 				 unsigned long start, unsigned long len)
5178 {
5179 	unsigned long offset;
5180 
5181 	/* start, start + len should not go beyond eb->len nor overflow */
5182 	if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
5183 		return report_eb_range(eb, start, len);
5184 
5185 	return false;
5186 }
5187 
read_extent_buffer(const struct extent_buffer * eb,void * dstv,unsigned long start,unsigned long len)5188 void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
5189 			unsigned long start, unsigned long len)
5190 {
5191 	size_t cur;
5192 	size_t offset;
5193 	struct page *page;
5194 	char *kaddr;
5195 	char *dst = (char *)dstv;
5196 	unsigned long i = get_eb_page_index(start);
5197 
5198 	if (check_eb_range(eb, start, len)) {
5199 		/*
5200 		 * Invalid range hit, reset the memory, so callers won't get
5201 		 * some random garbage for their uninitialzed memory.
5202 		 */
5203 		memset(dstv, 0, len);
5204 		return;
5205 	}
5206 
5207 	offset = get_eb_offset_in_page(eb, start);
5208 
5209 	while (len > 0) {
5210 		page = eb->pages[i];
5211 
5212 		cur = min(len, (PAGE_SIZE - offset));
5213 		kaddr = page_address(page);
5214 		memcpy(dst, kaddr + offset, cur);
5215 
5216 		dst += cur;
5217 		len -= cur;
5218 		offset = 0;
5219 		i++;
5220 	}
5221 }
5222 
read_extent_buffer_to_user_nofault(const struct extent_buffer * eb,void __user * dstv,unsigned long start,unsigned long len)5223 int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
5224 				       void __user *dstv,
5225 				       unsigned long start, unsigned long len)
5226 {
5227 	size_t cur;
5228 	size_t offset;
5229 	struct page *page;
5230 	char *kaddr;
5231 	char __user *dst = (char __user *)dstv;
5232 	unsigned long i = get_eb_page_index(start);
5233 	int ret = 0;
5234 
5235 	WARN_ON(start > eb->len);
5236 	WARN_ON(start + len > eb->start + eb->len);
5237 
5238 	offset = get_eb_offset_in_page(eb, start);
5239 
5240 	while (len > 0) {
5241 		page = eb->pages[i];
5242 
5243 		cur = min(len, (PAGE_SIZE - offset));
5244 		kaddr = page_address(page);
5245 		if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
5246 			ret = -EFAULT;
5247 			break;
5248 		}
5249 
5250 		dst += cur;
5251 		len -= cur;
5252 		offset = 0;
5253 		i++;
5254 	}
5255 
5256 	return ret;
5257 }
5258 
memcmp_extent_buffer(const struct extent_buffer * eb,const void * ptrv,unsigned long start,unsigned long len)5259 int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
5260 			 unsigned long start, unsigned long len)
5261 {
5262 	size_t cur;
5263 	size_t offset;
5264 	struct page *page;
5265 	char *kaddr;
5266 	char *ptr = (char *)ptrv;
5267 	unsigned long i = get_eb_page_index(start);
5268 	int ret = 0;
5269 
5270 	if (check_eb_range(eb, start, len))
5271 		return -EINVAL;
5272 
5273 	offset = get_eb_offset_in_page(eb, start);
5274 
5275 	while (len > 0) {
5276 		page = eb->pages[i];
5277 
5278 		cur = min(len, (PAGE_SIZE - offset));
5279 
5280 		kaddr = page_address(page);
5281 		ret = memcmp(ptr, kaddr + offset, cur);
5282 		if (ret)
5283 			break;
5284 
5285 		ptr += cur;
5286 		len -= cur;
5287 		offset = 0;
5288 		i++;
5289 	}
5290 	return ret;
5291 }
5292 
5293 /*
5294  * Check that the extent buffer is uptodate.
5295  *
5296  * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
5297  * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
5298  */
assert_eb_page_uptodate(const struct extent_buffer * eb,struct page * page)5299 static void assert_eb_page_uptodate(const struct extent_buffer *eb,
5300 				    struct page *page)
5301 {
5302 	struct btrfs_fs_info *fs_info = eb->fs_info;
5303 
5304 	/*
5305 	 * If we are using the commit root we could potentially clear a page
5306 	 * Uptodate while we're using the extent buffer that we've previously
5307 	 * looked up.  We don't want to complain in this case, as the page was
5308 	 * valid before, we just didn't write it out.  Instead we want to catch
5309 	 * the case where we didn't actually read the block properly, which
5310 	 * would have !PageUptodate && !PageError, as we clear PageError before
5311 	 * reading.
5312 	 */
5313 	if (fs_info->nodesize < PAGE_SIZE) {
5314 		bool uptodate, error;
5315 
5316 		uptodate = btrfs_subpage_test_uptodate(fs_info, page,
5317 						       eb->start, eb->len);
5318 		error = btrfs_subpage_test_error(fs_info, page, eb->start, eb->len);
5319 		WARN_ON(!uptodate && !error);
5320 	} else {
5321 		WARN_ON(!PageUptodate(page) && !PageError(page));
5322 	}
5323 }
5324 
write_extent_buffer_chunk_tree_uuid(const struct extent_buffer * eb,const void * srcv)5325 void write_extent_buffer_chunk_tree_uuid(const struct extent_buffer *eb,
5326 		const void *srcv)
5327 {
5328 	char *kaddr;
5329 
5330 	assert_eb_page_uptodate(eb, eb->pages[0]);
5331 	kaddr = page_address(eb->pages[0]) +
5332 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header,
5333 						   chunk_tree_uuid));
5334 	memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5335 }
5336 
write_extent_buffer_fsid(const struct extent_buffer * eb,const void * srcv)5337 void write_extent_buffer_fsid(const struct extent_buffer *eb, const void *srcv)
5338 {
5339 	char *kaddr;
5340 
5341 	assert_eb_page_uptodate(eb, eb->pages[0]);
5342 	kaddr = page_address(eb->pages[0]) +
5343 		get_eb_offset_in_page(eb, offsetof(struct btrfs_header, fsid));
5344 	memcpy(kaddr, srcv, BTRFS_FSID_SIZE);
5345 }
5346 
write_extent_buffer(const struct extent_buffer * eb,const void * srcv,unsigned long start,unsigned long len)5347 void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
5348 			 unsigned long start, unsigned long len)
5349 {
5350 	size_t cur;
5351 	size_t offset;
5352 	struct page *page;
5353 	char *kaddr;
5354 	char *src = (char *)srcv;
5355 	unsigned long i = get_eb_page_index(start);
5356 
5357 	WARN_ON(test_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags));
5358 
5359 	if (check_eb_range(eb, start, len))
5360 		return;
5361 
5362 	offset = get_eb_offset_in_page(eb, start);
5363 
5364 	while (len > 0) {
5365 		page = eb->pages[i];
5366 		assert_eb_page_uptodate(eb, page);
5367 
5368 		cur = min(len, PAGE_SIZE - offset);
5369 		kaddr = page_address(page);
5370 		memcpy(kaddr + offset, src, cur);
5371 
5372 		src += cur;
5373 		len -= cur;
5374 		offset = 0;
5375 		i++;
5376 	}
5377 }
5378 
memzero_extent_buffer(const struct extent_buffer * eb,unsigned long start,unsigned long len)5379 void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
5380 		unsigned long len)
5381 {
5382 	size_t cur;
5383 	size_t offset;
5384 	struct page *page;
5385 	char *kaddr;
5386 	unsigned long i = get_eb_page_index(start);
5387 
5388 	if (check_eb_range(eb, start, len))
5389 		return;
5390 
5391 	offset = get_eb_offset_in_page(eb, start);
5392 
5393 	while (len > 0) {
5394 		page = eb->pages[i];
5395 		assert_eb_page_uptodate(eb, page);
5396 
5397 		cur = min(len, PAGE_SIZE - offset);
5398 		kaddr = page_address(page);
5399 		memset(kaddr + offset, 0, cur);
5400 
5401 		len -= cur;
5402 		offset = 0;
5403 		i++;
5404 	}
5405 }
5406 
copy_extent_buffer_full(const struct extent_buffer * dst,const struct extent_buffer * src)5407 void copy_extent_buffer_full(const struct extent_buffer *dst,
5408 			     const struct extent_buffer *src)
5409 {
5410 	int i;
5411 	int num_pages;
5412 
5413 	ASSERT(dst->len == src->len);
5414 
5415 	if (dst->fs_info->nodesize >= PAGE_SIZE) {
5416 		num_pages = num_extent_pages(dst);
5417 		for (i = 0; i < num_pages; i++)
5418 			copy_page(page_address(dst->pages[i]),
5419 				  page_address(src->pages[i]));
5420 	} else {
5421 		size_t src_offset = get_eb_offset_in_page(src, 0);
5422 		size_t dst_offset = get_eb_offset_in_page(dst, 0);
5423 
5424 		ASSERT(src->fs_info->nodesize < PAGE_SIZE);
5425 		memcpy(page_address(dst->pages[0]) + dst_offset,
5426 		       page_address(src->pages[0]) + src_offset,
5427 		       src->len);
5428 	}
5429 }
5430 
copy_extent_buffer(const struct extent_buffer * dst,const struct extent_buffer * src,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5431 void copy_extent_buffer(const struct extent_buffer *dst,
5432 			const struct extent_buffer *src,
5433 			unsigned long dst_offset, unsigned long src_offset,
5434 			unsigned long len)
5435 {
5436 	u64 dst_len = dst->len;
5437 	size_t cur;
5438 	size_t offset;
5439 	struct page *page;
5440 	char *kaddr;
5441 	unsigned long i = get_eb_page_index(dst_offset);
5442 
5443 	if (check_eb_range(dst, dst_offset, len) ||
5444 	    check_eb_range(src, src_offset, len))
5445 		return;
5446 
5447 	WARN_ON(src->len != dst_len);
5448 
5449 	offset = get_eb_offset_in_page(dst, dst_offset);
5450 
5451 	while (len > 0) {
5452 		page = dst->pages[i];
5453 		assert_eb_page_uptodate(dst, page);
5454 
5455 		cur = min(len, (unsigned long)(PAGE_SIZE - offset));
5456 
5457 		kaddr = page_address(page);
5458 		read_extent_buffer(src, kaddr + offset, src_offset, cur);
5459 
5460 		src_offset += cur;
5461 		len -= cur;
5462 		offset = 0;
5463 		i++;
5464 	}
5465 }
5466 
5467 /*
5468  * eb_bitmap_offset() - calculate the page and offset of the byte containing the
5469  * given bit number
5470  * @eb: the extent buffer
5471  * @start: offset of the bitmap item in the extent buffer
5472  * @nr: bit number
5473  * @page_index: return index of the page in the extent buffer that contains the
5474  * given bit number
5475  * @page_offset: return offset into the page given by page_index
5476  *
5477  * This helper hides the ugliness of finding the byte in an extent buffer which
5478  * contains a given bit.
5479  */
eb_bitmap_offset(const struct extent_buffer * eb,unsigned long start,unsigned long nr,unsigned long * page_index,size_t * page_offset)5480 static inline void eb_bitmap_offset(const struct extent_buffer *eb,
5481 				    unsigned long start, unsigned long nr,
5482 				    unsigned long *page_index,
5483 				    size_t *page_offset)
5484 {
5485 	size_t byte_offset = BIT_BYTE(nr);
5486 	size_t offset;
5487 
5488 	/*
5489 	 * The byte we want is the offset of the extent buffer + the offset of
5490 	 * the bitmap item in the extent buffer + the offset of the byte in the
5491 	 * bitmap item.
5492 	 */
5493 	offset = start + offset_in_page(eb->start) + byte_offset;
5494 
5495 	*page_index = offset >> PAGE_SHIFT;
5496 	*page_offset = offset_in_page(offset);
5497 }
5498 
5499 /**
5500  * extent_buffer_test_bit - determine whether a bit in a bitmap item is set
5501  * @eb: the extent buffer
5502  * @start: offset of the bitmap item in the extent buffer
5503  * @nr: bit number to test
5504  */
extent_buffer_test_bit(const struct extent_buffer * eb,unsigned long start,unsigned long nr)5505 int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
5506 			   unsigned long nr)
5507 {
5508 	u8 *kaddr;
5509 	struct page *page;
5510 	unsigned long i;
5511 	size_t offset;
5512 
5513 	eb_bitmap_offset(eb, start, nr, &i, &offset);
5514 	page = eb->pages[i];
5515 	assert_eb_page_uptodate(eb, page);
5516 	kaddr = page_address(page);
5517 	return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
5518 }
5519 
5520 /**
5521  * extent_buffer_bitmap_set - set an area of a bitmap
5522  * @eb: the extent buffer
5523  * @start: offset of the bitmap item in the extent buffer
5524  * @pos: bit number of the first bit
5525  * @len: number of bits to set
5526  */
extent_buffer_bitmap_set(const struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)5527 void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
5528 			      unsigned long pos, unsigned long len)
5529 {
5530 	u8 *kaddr;
5531 	struct page *page;
5532 	unsigned long i;
5533 	size_t offset;
5534 	const unsigned int size = pos + len;
5535 	int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5536 	u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);
5537 
5538 	eb_bitmap_offset(eb, start, pos, &i, &offset);
5539 	page = eb->pages[i];
5540 	assert_eb_page_uptodate(eb, page);
5541 	kaddr = page_address(page);
5542 
5543 	while (len >= bits_to_set) {
5544 		kaddr[offset] |= mask_to_set;
5545 		len -= bits_to_set;
5546 		bits_to_set = BITS_PER_BYTE;
5547 		mask_to_set = ~0;
5548 		if (++offset >= PAGE_SIZE && len > 0) {
5549 			offset = 0;
5550 			page = eb->pages[++i];
5551 			assert_eb_page_uptodate(eb, page);
5552 			kaddr = page_address(page);
5553 		}
5554 	}
5555 	if (len) {
5556 		mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
5557 		kaddr[offset] |= mask_to_set;
5558 	}
5559 }
5560 
5561 
5562 /**
5563  * extent_buffer_bitmap_clear - clear an area of a bitmap
5564  * @eb: the extent buffer
5565  * @start: offset of the bitmap item in the extent buffer
5566  * @pos: bit number of the first bit
5567  * @len: number of bits to clear
5568  */
extent_buffer_bitmap_clear(const struct extent_buffer * eb,unsigned long start,unsigned long pos,unsigned long len)5569 void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
5570 				unsigned long start, unsigned long pos,
5571 				unsigned long len)
5572 {
5573 	u8 *kaddr;
5574 	struct page *page;
5575 	unsigned long i;
5576 	size_t offset;
5577 	const unsigned int size = pos + len;
5578 	int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
5579 	u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);
5580 
5581 	eb_bitmap_offset(eb, start, pos, &i, &offset);
5582 	page = eb->pages[i];
5583 	assert_eb_page_uptodate(eb, page);
5584 	kaddr = page_address(page);
5585 
5586 	while (len >= bits_to_clear) {
5587 		kaddr[offset] &= ~mask_to_clear;
5588 		len -= bits_to_clear;
5589 		bits_to_clear = BITS_PER_BYTE;
5590 		mask_to_clear = ~0;
5591 		if (++offset >= PAGE_SIZE && len > 0) {
5592 			offset = 0;
5593 			page = eb->pages[++i];
5594 			assert_eb_page_uptodate(eb, page);
5595 			kaddr = page_address(page);
5596 		}
5597 	}
5598 	if (len) {
5599 		mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
5600 		kaddr[offset] &= ~mask_to_clear;
5601 	}
5602 }
5603 
areas_overlap(unsigned long src,unsigned long dst,unsigned long len)5604 static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
5605 {
5606 	unsigned long distance = (src > dst) ? src - dst : dst - src;
5607 	return distance < len;
5608 }
5609 
copy_pages(struct page * dst_page,struct page * src_page,unsigned long dst_off,unsigned long src_off,unsigned long len)5610 static void copy_pages(struct page *dst_page, struct page *src_page,
5611 		       unsigned long dst_off, unsigned long src_off,
5612 		       unsigned long len)
5613 {
5614 	char *dst_kaddr = page_address(dst_page);
5615 	char *src_kaddr;
5616 	int must_memmove = 0;
5617 
5618 	if (dst_page != src_page) {
5619 		src_kaddr = page_address(src_page);
5620 	} else {
5621 		src_kaddr = dst_kaddr;
5622 		if (areas_overlap(src_off, dst_off, len))
5623 			must_memmove = 1;
5624 	}
5625 
5626 	if (must_memmove)
5627 		memmove(dst_kaddr + dst_off, src_kaddr + src_off, len);
5628 	else
5629 		memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
5630 }
5631 
memcpy_extent_buffer(const struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5632 void memcpy_extent_buffer(const struct extent_buffer *dst,
5633 			  unsigned long dst_offset, unsigned long src_offset,
5634 			  unsigned long len)
5635 {
5636 	size_t cur;
5637 	size_t dst_off_in_page;
5638 	size_t src_off_in_page;
5639 	unsigned long dst_i;
5640 	unsigned long src_i;
5641 
5642 	if (check_eb_range(dst, dst_offset, len) ||
5643 	    check_eb_range(dst, src_offset, len))
5644 		return;
5645 
5646 	while (len > 0) {
5647 		dst_off_in_page = get_eb_offset_in_page(dst, dst_offset);
5648 		src_off_in_page = get_eb_offset_in_page(dst, src_offset);
5649 
5650 		dst_i = get_eb_page_index(dst_offset);
5651 		src_i = get_eb_page_index(src_offset);
5652 
5653 		cur = min(len, (unsigned long)(PAGE_SIZE -
5654 					       src_off_in_page));
5655 		cur = min_t(unsigned long, cur,
5656 			(unsigned long)(PAGE_SIZE - dst_off_in_page));
5657 
5658 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
5659 			   dst_off_in_page, src_off_in_page, cur);
5660 
5661 		src_offset += cur;
5662 		dst_offset += cur;
5663 		len -= cur;
5664 	}
5665 }
5666 
memmove_extent_buffer(const struct extent_buffer * dst,unsigned long dst_offset,unsigned long src_offset,unsigned long len)5667 void memmove_extent_buffer(const struct extent_buffer *dst,
5668 			   unsigned long dst_offset, unsigned long src_offset,
5669 			   unsigned long len)
5670 {
5671 	size_t cur;
5672 	size_t dst_off_in_page;
5673 	size_t src_off_in_page;
5674 	unsigned long dst_end = dst_offset + len - 1;
5675 	unsigned long src_end = src_offset + len - 1;
5676 	unsigned long dst_i;
5677 	unsigned long src_i;
5678 
5679 	if (check_eb_range(dst, dst_offset, len) ||
5680 	    check_eb_range(dst, src_offset, len))
5681 		return;
5682 	if (dst_offset < src_offset) {
5683 		memcpy_extent_buffer(dst, dst_offset, src_offset, len);
5684 		return;
5685 	}
5686 	while (len > 0) {
5687 		dst_i = get_eb_page_index(dst_end);
5688 		src_i = get_eb_page_index(src_end);
5689 
5690 		dst_off_in_page = get_eb_offset_in_page(dst, dst_end);
5691 		src_off_in_page = get_eb_offset_in_page(dst, src_end);
5692 
5693 		cur = min_t(unsigned long, len, src_off_in_page + 1);
5694 		cur = min(cur, dst_off_in_page + 1);
5695 		copy_pages(dst->pages[dst_i], dst->pages[src_i],
5696 			   dst_off_in_page - cur + 1,
5697 			   src_off_in_page - cur + 1, cur);
5698 
5699 		dst_end -= cur;
5700 		src_end -= cur;
5701 		len -= cur;
5702 	}
5703 }
5704 
5705 #define GANG_LOOKUP_SIZE	16
get_next_extent_buffer(struct btrfs_fs_info * fs_info,struct page * page,u64 bytenr)5706 static struct extent_buffer *get_next_extent_buffer(
5707 		struct btrfs_fs_info *fs_info, struct page *page, u64 bytenr)
5708 {
5709 	struct extent_buffer *gang[GANG_LOOKUP_SIZE];
5710 	struct extent_buffer *found = NULL;
5711 	u64 page_start = page_offset(page);
5712 	u64 cur = page_start;
5713 
5714 	ASSERT(in_range(bytenr, page_start, PAGE_SIZE));
5715 	lockdep_assert_held(&fs_info->buffer_lock);
5716 
5717 	while (cur < page_start + PAGE_SIZE) {
5718 		int ret;
5719 		int i;
5720 
5721 		ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
5722 				(void **)gang, cur >> fs_info->sectorsize_bits,
5723 				min_t(unsigned int, GANG_LOOKUP_SIZE,
5724 				      PAGE_SIZE / fs_info->nodesize));
5725 		if (ret == 0)
5726 			goto out;
5727 		for (i = 0; i < ret; i++) {
5728 			/* Already beyond page end */
5729 			if (gang[i]->start >= page_start + PAGE_SIZE)
5730 				goto out;
5731 			/* Found one */
5732 			if (gang[i]->start >= bytenr) {
5733 				found = gang[i];
5734 				goto out;
5735 			}
5736 		}
5737 		cur = gang[ret - 1]->start + gang[ret - 1]->len;
5738 	}
5739 out:
5740 	return found;
5741 }
5742 
try_release_subpage_extent_buffer(struct page * page)5743 static int try_release_subpage_extent_buffer(struct page *page)
5744 {
5745 	struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
5746 	u64 cur = page_offset(page);
5747 	const u64 end = page_offset(page) + PAGE_SIZE;
5748 	int ret;
5749 
5750 	while (cur < end) {
5751 		struct extent_buffer *eb = NULL;
5752 
5753 		/*
5754 		 * Unlike try_release_extent_buffer() which uses page->private
5755 		 * to grab buffer, for subpage case we rely on radix tree, thus
5756 		 * we need to ensure radix tree consistency.
5757 		 *
5758 		 * We also want an atomic snapshot of the radix tree, thus go
5759 		 * with spinlock rather than RCU.
5760 		 */
5761 		spin_lock(&fs_info->buffer_lock);
5762 		eb = get_next_extent_buffer(fs_info, page, cur);
5763 		if (!eb) {
5764 			/* No more eb in the page range after or at cur */
5765 			spin_unlock(&fs_info->buffer_lock);
5766 			break;
5767 		}
5768 		cur = eb->start + eb->len;
5769 
5770 		/*
5771 		 * The same as try_release_extent_buffer(), to ensure the eb
5772 		 * won't disappear out from under us.
5773 		 */
5774 		spin_lock(&eb->refs_lock);
5775 		if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5776 			spin_unlock(&eb->refs_lock);
5777 			spin_unlock(&fs_info->buffer_lock);
5778 			break;
5779 		}
5780 		spin_unlock(&fs_info->buffer_lock);
5781 
5782 		/*
5783 		 * If tree ref isn't set then we know the ref on this eb is a
5784 		 * real ref, so just return, this eb will likely be freed soon
5785 		 * anyway.
5786 		 */
5787 		if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5788 			spin_unlock(&eb->refs_lock);
5789 			break;
5790 		}
5791 
5792 		/*
5793 		 * Here we don't care about the return value, we will always
5794 		 * check the page private at the end.  And
5795 		 * release_extent_buffer() will release the refs_lock.
5796 		 */
5797 		release_extent_buffer(eb);
5798 	}
5799 	/*
5800 	 * Finally to check if we have cleared page private, as if we have
5801 	 * released all ebs in the page, the page private should be cleared now.
5802 	 */
5803 	spin_lock(&page->mapping->private_lock);
5804 	if (!PagePrivate(page))
5805 		ret = 1;
5806 	else
5807 		ret = 0;
5808 	spin_unlock(&page->mapping->private_lock);
5809 	return ret;
5810 
5811 }
5812 
try_release_extent_buffer(struct page * page)5813 int try_release_extent_buffer(struct page *page)
5814 {
5815 	struct extent_buffer *eb;
5816 
5817 	if (btrfs_sb(page->mapping->host->i_sb)->nodesize < PAGE_SIZE)
5818 		return try_release_subpage_extent_buffer(page);
5819 
5820 	/*
5821 	 * We need to make sure nobody is changing page->private, as we rely on
5822 	 * page->private as the pointer to extent buffer.
5823 	 */
5824 	spin_lock(&page->mapping->private_lock);
5825 	if (!PagePrivate(page)) {
5826 		spin_unlock(&page->mapping->private_lock);
5827 		return 1;
5828 	}
5829 
5830 	eb = (struct extent_buffer *)page->private;
5831 	BUG_ON(!eb);
5832 
5833 	/*
5834 	 * This is a little awful but should be ok, we need to make sure that
5835 	 * the eb doesn't disappear out from under us while we're looking at
5836 	 * this page.
5837 	 */
5838 	spin_lock(&eb->refs_lock);
5839 	if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
5840 		spin_unlock(&eb->refs_lock);
5841 		spin_unlock(&page->mapping->private_lock);
5842 		return 0;
5843 	}
5844 	spin_unlock(&page->mapping->private_lock);
5845 
5846 	/*
5847 	 * If tree ref isn't set then we know the ref on this eb is a real ref,
5848 	 * so just return, this page will likely be freed soon anyway.
5849 	 */
5850 	if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
5851 		spin_unlock(&eb->refs_lock);
5852 		return 0;
5853 	}
5854 
5855 	return release_extent_buffer(eb);
5856 }
5857 
5858 /*
5859  * btrfs_readahead_tree_block - attempt to readahead a child block
5860  * @fs_info:	the fs_info
5861  * @bytenr:	bytenr to read
5862  * @owner_root: objectid of the root that owns this eb
5863  * @gen:	generation for the uptodate check, can be 0
5864  * @level:	level for the eb
5865  *
5866  * Attempt to readahead a tree block at @bytenr.  If @gen is 0 then we do a
5867  * normal uptodate check of the eb, without checking the generation.  If we have
5868  * to read the block we will not block on anything.
5869  */
btrfs_readahead_tree_block(struct btrfs_fs_info * fs_info,u64 bytenr,u64 owner_root,u64 gen,int level)5870 void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
5871 				u64 bytenr, u64 owner_root, u64 gen, int level)
5872 {
5873 	struct extent_buffer *eb;
5874 	int ret;
5875 
5876 	eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
5877 	if (IS_ERR(eb))
5878 		return;
5879 
5880 	if (btrfs_buffer_uptodate(eb, gen, 1)) {
5881 		free_extent_buffer(eb);
5882 		return;
5883 	}
5884 
5885 	ret = read_extent_buffer_pages(eb, WAIT_NONE, 0);
5886 	if (ret < 0)
5887 		free_extent_buffer_stale(eb);
5888 	else
5889 		free_extent_buffer(eb);
5890 }
5891 
5892 /*
5893  * btrfs_readahead_node_child - readahead a node's child block
5894  * @node:	parent node we're reading from
5895  * @slot:	slot in the parent node for the child we want to read
5896  *
5897  * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
5898  * the slot in the node provided.
5899  */
btrfs_readahead_node_child(struct extent_buffer * node,int slot)5900 void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
5901 {
5902 	btrfs_readahead_tree_block(node->fs_info,
5903 				   btrfs_node_blockptr(node, slot),
5904 				   btrfs_header_owner(node),
5905 				   btrfs_node_ptr_generation(node, slot),
5906 				   btrfs_header_level(node) - 1);
5907 }
5908