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