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