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