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