xref: /linux/fs/buffer.c (revision c5fd5e67c7812bc40cd897422c1e0d6dd9ed1e2e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/buffer.c
4  *
5  *  Copyright (C) 1991, 1992, 2002  Linus Torvalds
6  */
7 
8 /*
9  * Start bdflush() with kernel_thread not syscall - Paul Gortmaker, 12/95
10  *
11  * Removed a lot of unnecessary code and simplified things now that
12  * the buffer cache isn't our primary cache - Andrew Tridgell 12/96
13  *
14  * Speed up hash, lru, and free list operations.  Use gfp() for allocating
15  * hash table, use SLAB cache for buffer heads. SMP threading.  -DaveM
16  *
17  * Added 32k buffer block sizes - these are required older ARM systems. - RMK
18  *
19  * async buffer flushing, 1999 Andrea Arcangeli <andrea@suse.de>
20  */
21 
22 #include <linux/kernel.h>
23 #include <linux/sched/signal.h>
24 #include <linux/syscalls.h>
25 #include <linux/fs.h>
26 #include <linux/iomap.h>
27 #include <linux/mm.h>
28 #include <linux/percpu.h>
29 #include <linux/slab.h>
30 #include <linux/capability.h>
31 #include <linux/blkdev.h>
32 #include <linux/blk-crypto.h>
33 #include <linux/file.h>
34 #include <linux/quotaops.h>
35 #include <linux/highmem.h>
36 #include <linux/export.h>
37 #include <linux/backing-dev.h>
38 #include <linux/writeback.h>
39 #include <linux/hash.h>
40 #include <linux/suspend.h>
41 #include <linux/buffer_head.h>
42 #include <linux/task_io_accounting_ops.h>
43 #include <linux/bio.h>
44 #include <linux/cpu.h>
45 #include <linux/bitops.h>
46 #include <linux/mpage.h>
47 #include <linux/bit_spinlock.h>
48 #include <linux/folio_batch.h>
49 #include <linux/sched/mm.h>
50 #include <trace/events/block.h>
51 #include <linux/fscrypt.h>
52 #include <linux/fsverity.h>
53 #include <linux/sched/isolation.h>
54 
55 #include "internal.h"
56 
57 #define BH_ENTRY(list) list_entry((list), struct buffer_head, b_assoc_buffers)
58 
59 inline void touch_buffer(struct buffer_head *bh)
60 {
61 	trace_block_touch_buffer(bh);
62 	folio_mark_accessed(bh->b_folio);
63 }
64 EXPORT_SYMBOL(touch_buffer);
65 
66 void __lock_buffer(struct buffer_head *bh)
67 {
68 	wait_on_bit_lock_io(&bh->b_state, BH_Lock, TASK_UNINTERRUPTIBLE);
69 }
70 EXPORT_SYMBOL(__lock_buffer);
71 
72 void unlock_buffer(struct buffer_head *bh)
73 {
74 	clear_and_wake_up_bit(BH_Lock, &bh->b_state);
75 }
76 EXPORT_SYMBOL(unlock_buffer);
77 
78 /*
79  * Returns if the folio has dirty or writeback buffers. If all the buffers
80  * are unlocked and clean then the folio_test_dirty information is stale. If
81  * any of the buffers are locked, it is assumed they are locked for IO.
82  */
83 void buffer_check_dirty_writeback(struct folio *folio,
84 				     bool *dirty, bool *writeback)
85 {
86 	struct buffer_head *head, *bh;
87 	*dirty = false;
88 	*writeback = false;
89 
90 	BUG_ON(!folio_test_locked(folio));
91 
92 	head = folio_buffers(folio);
93 	if (!head)
94 		return;
95 
96 	if (folio_test_writeback(folio))
97 		*writeback = true;
98 
99 	bh = head;
100 	do {
101 		if (buffer_locked(bh))
102 			*writeback = true;
103 
104 		if (buffer_dirty(bh))
105 			*dirty = true;
106 
107 		bh = bh->b_this_page;
108 	} while (bh != head);
109 }
110 
111 /*
112  * Block until a buffer comes unlocked.  This doesn't stop it
113  * from becoming locked again - you have to lock it yourself
114  * if you want to preserve its state.
115  */
116 void __wait_on_buffer(struct buffer_head * bh)
117 {
118 	wait_on_bit_io(&bh->b_state, BH_Lock, TASK_UNINTERRUPTIBLE);
119 }
120 EXPORT_SYMBOL(__wait_on_buffer);
121 
122 static void buffer_io_error(struct buffer_head *bh, char *msg)
123 {
124 	if (!test_bit(BH_Quiet, &bh->b_state))
125 		printk_ratelimited(KERN_ERR
126 			"Buffer I/O error on dev %pg, logical block %llu%s\n",
127 			bh->b_bdev, (unsigned long long)bh->b_blocknr, msg);
128 }
129 
130 /**
131  * bio_endio_bh - Discard the bio used to submit a buffer.
132  * @bio: The bio.
133  * @bhp: Where to return the buffer_head.
134  *
135  * Call this in your bio_end_io handler to retrieve the buffer_head
136  * submitted in bh_submit().  If you did not call bh_submit(), do not
137  * call this function; it will return garbage.
138  *
139  * This function consumes the bio refcount which will probably free the
140  * bio.
141  *
142  * Return: True if the I/O succeeded.
143  */
144 bool bio_endio_bh(struct bio *bio, struct buffer_head **bhp)
145 {
146 	bool success = bio->bi_status == BLK_STS_OK;
147 	struct buffer_head *bh = bio->bi_private;
148 
149 	if (unlikely(bio_flagged(bio, BIO_QUIET)))
150 		set_bit(BH_Quiet, &bh->b_state);
151 	bio_put(bio);
152 
153 	*bhp = bh;
154 	return success;
155 }
156 EXPORT_SYMBOL(bio_endio_bh);
157 
158 /**
159  * end_buffer_read_sync - Handle buffer reads finishing
160  * @bh: The buffer.
161  * @uptodate: True if the read was successful.
162  *
163  * If a buffer is read through a mechanism that isn't bh_submit(), you
164  * can call this function to finish the read.
165  */
166 void end_buffer_read_sync(struct buffer_head *bh, int uptodate)
167 {
168 	if (uptodate) {
169 		set_buffer_uptodate(bh);
170 	} else {
171 		/* This happens, due to failed read-ahead attempts. */
172 		clear_buffer_uptodate(bh);
173 	}
174 	unlock_buffer(bh);
175 }
176 EXPORT_SYMBOL(end_buffer_read_sync);
177 
178 /**
179  * bh_end_read - I/O end handler for reads
180  * @bio: The bio being completed.
181  *
182  * Pass this function to bh_submit() if you're reading into the buffer,
183  * unless you need your own special I/O end handler.
184  */
185 void bh_end_read(struct bio *bio)
186 {
187 	struct buffer_head *bh;
188 	bool uptodate = bio_endio_bh(bio, &bh);
189 	end_buffer_read_sync(bh, uptodate);
190 }
191 EXPORT_SYMBOL(bh_end_read);
192 
193 /**
194  * bh_end_write - I/O end handler for writes
195  * @bio: The bio being completed.
196  *
197  * Pass this function to bh_submit() if you're writing from the buffer,
198  * unless you need your own special I/O end handler.
199  */
200 void bh_end_write(struct bio *bio)
201 {
202 	struct buffer_head *bh;
203 	bool success = bio_endio_bh(bio, &bh);
204 
205 	if (success) {
206 		clear_buffer_write_io_error(bh);
207 	} else {
208 		buffer_io_error(bh, ", lost sync page write");
209 		mark_buffer_write_io_error(bh);
210 	}
211 	unlock_buffer(bh);
212 }
213 EXPORT_SYMBOL(bh_end_write);
214 
215 static struct buffer_head *
216 __find_get_block_slow(struct block_device *bdev, sector_t block, bool atomic)
217 {
218 	struct address_space *bd_mapping = bdev->bd_mapping;
219 	const int blkbits = bd_mapping->host->i_blkbits;
220 	struct buffer_head *ret = NULL;
221 	pgoff_t index;
222 	struct buffer_head *bh;
223 	struct buffer_head *head;
224 	struct folio *folio;
225 	int all_mapped = 1;
226 	static DEFINE_RATELIMIT_STATE(last_warned, HZ, 1);
227 
228 	index = ((loff_t)block << blkbits) / PAGE_SIZE;
229 	folio = __filemap_get_folio(bd_mapping, index, FGP_ACCESSED, 0);
230 	if (IS_ERR(folio))
231 		goto out;
232 
233 	/*
234 	 * Folio lock protects the buffers. Callers that cannot block
235 	 * will fallback to serializing vs try_to_free_buffers() via
236 	 * the i_private_lock.
237 	 */
238 	if (atomic)
239 		spin_lock(&bd_mapping->i_private_lock);
240 	else
241 		folio_lock(folio);
242 
243 	head = folio_buffers(folio);
244 	if (!head)
245 		goto out_unlock;
246 	/*
247 	 * Upon a noref migration, the folio lock serializes here;
248 	 * otherwise bail.
249 	 */
250 	if (test_bit_acquire(BH_Migrate, &head->b_state)) {
251 		WARN_ON(!atomic);
252 		goto out_unlock;
253 	}
254 
255 	bh = head;
256 	do {
257 		if (!buffer_mapped(bh))
258 			all_mapped = 0;
259 		else if (bh->b_blocknr == block) {
260 			ret = bh;
261 			get_bh(bh);
262 			goto out_unlock;
263 		}
264 		bh = bh->b_this_page;
265 	} while (bh != head);
266 
267 	/* we might be here because some of the buffers on this folio are
268 	 * not mapped.  This is due to various races between
269 	 * file io on the block device and getblk.  It gets dealt with
270 	 * elsewhere, don't buffer_error if we had some unmapped buffers
271 	 */
272 	ratelimit_set_flags(&last_warned, RATELIMIT_MSG_ON_RELEASE);
273 	if (all_mapped && __ratelimit(&last_warned)) {
274 		printk("__find_get_block_slow() failed. block=%llu, "
275 		       "b_blocknr=%llu, b_state=0x%08lx, b_size=%zu, "
276 		       "device %pg blocksize: %d\n",
277 		       (unsigned long long)block,
278 		       (unsigned long long)bh->b_blocknr,
279 		       bh->b_state, bh->b_size, bdev,
280 		       1 << blkbits);
281 	}
282 out_unlock:
283 	if (atomic)
284 		spin_unlock(&bd_mapping->i_private_lock);
285 	else
286 		folio_unlock(folio);
287 	folio_put(folio);
288 out:
289 	return ret;
290 }
291 
292 static void end_buffer_async_read(struct buffer_head *bh, int uptodate)
293 {
294 	unsigned long flags;
295 	struct buffer_head *first;
296 	struct buffer_head *tmp;
297 	struct folio *folio;
298 	int folio_uptodate = 1;
299 
300 	BUG_ON(!buffer_async_read(bh));
301 
302 	folio = bh->b_folio;
303 	if (uptodate) {
304 		set_buffer_uptodate(bh);
305 	} else {
306 		clear_buffer_uptodate(bh);
307 		buffer_io_error(bh, ", async page read");
308 	}
309 
310 	/*
311 	 * Be _very_ careful from here on. Bad things can happen if
312 	 * two buffer heads end IO at almost the same time and both
313 	 * decide that the folio is now completely done.
314 	 */
315 	first = folio_buffers(folio);
316 	spin_lock_irqsave(&first->b_uptodate_lock, flags);
317 	clear_buffer_async_read(bh);
318 	unlock_buffer(bh);
319 	tmp = bh;
320 	do {
321 		if (!buffer_uptodate(tmp))
322 			folio_uptodate = 0;
323 		if (buffer_async_read(tmp)) {
324 			BUG_ON(!buffer_locked(tmp));
325 			goto still_busy;
326 		}
327 		tmp = tmp->b_this_page;
328 	} while (tmp != bh);
329 	spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
330 
331 	folio_end_read(folio, folio_uptodate);
332 	return;
333 
334 still_busy:
335 	spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
336 }
337 
338 struct verify_bh_ctx {
339 	struct work_struct work;
340 	struct buffer_head *bh;
341 	struct fsverity_info *vi;
342 };
343 
344 static void verify_bh(struct work_struct *work)
345 {
346 	struct verify_bh_ctx *ctx =
347 		container_of(work, struct verify_bh_ctx, work);
348 	struct buffer_head *bh = ctx->bh;
349 	bool valid;
350 
351 	valid = fsverity_verify_blocks(ctx->vi, bh->b_folio, bh->b_size,
352 				       bh_offset(bh));
353 	end_buffer_async_read(bh, valid);
354 	kfree(ctx);
355 }
356 
357 /*
358  * I/O completion handler for block_read_full_folio() - folios
359  * which come unlocked at the end of I/O.
360  */
361 static void bh_end_async_read(struct bio *bio)
362 {
363 	struct buffer_head *bh;
364 	bool uptodate = bio_endio_bh(bio, &bh);
365 	struct inode *inode = bh->b_folio->mapping->host;
366 	struct fsverity_info *vi = NULL;
367 
368 	/* needed by ext4 */
369 	if (bh->b_folio->index < DIV_ROUND_UP(inode->i_size, PAGE_SIZE))
370 		vi = fsverity_get_info(inode);
371 
372 	/* Verify (with fsverity) if needed. */
373 	if (vi && uptodate) {
374 		struct verify_bh_ctx *ctx = kmalloc_obj(*ctx, GFP_ATOMIC);
375 
376 		if (ctx) {
377 			ctx->bh = bh;
378 			ctx->vi = vi;
379 			INIT_WORK(&ctx->work, verify_bh);
380 			fsverity_enqueue_verify_work(&ctx->work);
381 			return;
382 		}
383 		uptodate = false;
384 	}
385 	end_buffer_async_read(bh, uptodate);
386 }
387 
388 /**
389  * bh_end_async_write - I/O end handler for async folio writes
390  * @bio: The bio being completed.
391  *
392  * Pass this function to bh_submit() if you're doing the equivalent of
393  * block_write_full_folio().  That is, the folio is unlocked, and will
394  * have its writeback flag cleared once all async write buffers have
395  * completed.
396  */
397 void bh_end_async_write(struct bio *bio)
398 {
399 	struct buffer_head *bh;
400 	bool success = bio_endio_bh(bio, &bh);
401 	unsigned long flags;
402 	struct buffer_head *first;
403 	struct buffer_head *tmp;
404 	struct folio *folio;
405 
406 	BUG_ON(!buffer_async_write(bh));
407 
408 	folio = bh->b_folio;
409 	if (success) {
410 		clear_buffer_write_io_error(bh);
411 	} else {
412 		buffer_io_error(bh, ", lost async page write");
413 		mark_buffer_write_io_error(bh);
414 	}
415 
416 	first = folio_buffers(folio);
417 	spin_lock_irqsave(&first->b_uptodate_lock, flags);
418 
419 	clear_buffer_async_write(bh);
420 	unlock_buffer(bh);
421 	tmp = bh->b_this_page;
422 	while (tmp != bh) {
423 		if (buffer_async_write(tmp)) {
424 			BUG_ON(!buffer_locked(tmp));
425 			goto still_busy;
426 		}
427 		tmp = tmp->b_this_page;
428 	}
429 	spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
430 	folio_end_writeback(folio);
431 	return;
432 
433 still_busy:
434 	spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
435 }
436 EXPORT_SYMBOL(bh_end_async_write);
437 
438 
439 /*
440  * fs/buffer.c contains helper functions for buffer-backed address space's
441  * fsync functions.  A common requirement for buffer-based filesystems is
442  * that certain data from the backing blockdev needs to be written out for
443  * a successful fsync().  For example, ext2 indirect blocks need to be
444  * written back and waited upon before fsync() returns.
445  *
446  * The functions mmb_mark_buffer_dirty(), mmb_sync(), mmb_has_buffers()
447  * and mmb_invalidate() are provided for the management of a list of dependent
448  * buffers in mapping_metadata_bhs struct.
449  *
450  * The locking is a little subtle: The list of buffer heads is protected by
451  * the lock in mapping_metadata_bhs so functions coming from bdev mapping
452  * (such as try_to_free_buffers()) need to safely get to mapping_metadata_bhs
453  * using RCU, grab the lock, verify we didn't race with somebody detaching the
454  * bh / moving it to different inode and only then proceeding.
455  */
456 
457 void mmb_init(struct mapping_metadata_bhs *mmb, struct address_space *mapping)
458 {
459 	spin_lock_init(&mmb->lock);
460 	INIT_LIST_HEAD(&mmb->list);
461 	mmb->mapping = mapping;
462 }
463 EXPORT_SYMBOL(mmb_init);
464 
465 static void __remove_assoc_queue(struct mapping_metadata_bhs *mmb,
466 			         struct buffer_head *bh)
467 {
468 	lockdep_assert_held(&mmb->lock);
469 	list_del_init(&bh->b_assoc_buffers);
470 	WARN_ON(!bh->b_mmb);
471 	bh->b_mmb = NULL;
472 }
473 
474 static void remove_assoc_queue(struct buffer_head *bh)
475 {
476 	struct mapping_metadata_bhs *mmb;
477 
478 	/*
479 	 * The locking dance is ugly here. We need to acquire the lock
480 	 * protecting the metadata bh list while possibly racing with bh
481 	 * being removed from the list or moved to a different one.  We
482 	 * use RCU to pin mapping_metadata_bhs in memory to
483 	 * opportunistically acquire the lock and then recheck the bh
484 	 * didn't move under us.
485 	 */
486 	while (bh->b_mmb) {
487 		rcu_read_lock();
488 		mmb = READ_ONCE(bh->b_mmb);
489 		if (mmb) {
490 			spin_lock(&mmb->lock);
491 			if (bh->b_mmb == mmb)
492 				__remove_assoc_queue(mmb, bh);
493 			spin_unlock(&mmb->lock);
494 		}
495 		rcu_read_unlock();
496 	}
497 }
498 
499 bool mmb_has_buffers(struct mapping_metadata_bhs *mmb)
500 {
501 	return !list_empty(&mmb->list);
502 }
503 EXPORT_SYMBOL_GPL(mmb_has_buffers);
504 
505 /**
506  * mmb_sync - write out & wait upon all buffers in a list
507  * @mmb: the list of buffers to write
508  *
509  * Starts I/O against the buffers in the given list and waits upon
510  * that I/O. Basically, this is a convenience function for fsync().  @mmb is
511  * for a file or directory which needs those buffers to be written for a
512  * successful fsync().
513  *
514  * We have conflicting pressures: we want to make sure that all
515  * initially dirty buffers get waited on, but that any subsequently
516  * dirtied buffers don't.  After all, we don't want fsync to last
517  * forever if somebody is actively writing to the file.
518  *
519  * Do this in two main stages: first we copy dirty buffers to a
520  * temporary inode list, queueing the writes as we go. Then we clean
521  * up, waiting for those writes to complete. mmb_mark_buffer_dirty()
522  * doesn't touch b_assoc_buffers list if b_mmb is set so we are sure the
523  * buffer stays on our list until IO completes (at which point it can be
524  * reaped).
525  */
526 int mmb_sync(struct mapping_metadata_bhs *mmb)
527 {
528 	struct buffer_head *bh;
529 	int err = 0;
530 	struct blk_plug plug;
531 	LIST_HEAD(tmp);
532 
533 	if (!mmb_has_buffers(mmb))
534 		return 0;
535 
536 	blk_start_plug(&plug);
537 
538 	spin_lock(&mmb->lock);
539 	while (!list_empty(&mmb->list)) {
540 		bh = BH_ENTRY(mmb->list.next);
541 		WARN_ON_ONCE(bh->b_mmb != mmb);
542 		__remove_assoc_queue(mmb, bh);
543 		/* Avoid race with mmb_mark_buffer_dirty() which does
544 		 * a lockless check and we rely on seeing the dirty bit */
545 		smp_mb();
546 		if (buffer_dirty(bh) || buffer_locked(bh)) {
547 			list_add(&bh->b_assoc_buffers, &tmp);
548 			bh->b_mmb = mmb;
549 			if (buffer_dirty(bh)) {
550 				get_bh(bh);
551 				spin_unlock(&mmb->lock);
552 				/*
553 				 * Ensure any pending I/O completes so that
554 				 * write_dirty_buffer() actually writes the
555 				 * current contents - it is a noop if I/O is
556 				 * still in flight on potentially older
557 				 * contents.
558 				 */
559 				write_dirty_buffer(bh, REQ_SYNC);
560 
561 				/*
562 				 * Kick off IO for the previous mapping. Note
563 				 * that we will not run the very last mapping,
564 				 * wait_on_buffer() will do that for us
565 				 * through sync_buffer().
566 				 */
567 				brelse(bh);
568 				spin_lock(&mmb->lock);
569 			}
570 		}
571 	}
572 
573 	spin_unlock(&mmb->lock);
574 	blk_finish_plug(&plug);
575 	spin_lock(&mmb->lock);
576 
577 	while (!list_empty(&tmp)) {
578 		bh = BH_ENTRY(tmp.prev);
579 		get_bh(bh);
580 		__remove_assoc_queue(mmb, bh);
581 		/* Avoid race with mmb_mark_buffer_dirty() which does
582 		 * a lockless check and we rely on seeing the dirty bit */
583 		smp_mb();
584 		if (buffer_dirty(bh)) {
585 			list_add(&bh->b_assoc_buffers, &mmb->list);
586 			bh->b_mmb = mmb;
587 		}
588 		spin_unlock(&mmb->lock);
589 		wait_on_buffer(bh);
590 		if (buffer_write_io_error(bh))
591 			err = -EIO;
592 		brelse(bh);
593 		spin_lock(&mmb->lock);
594 	}
595 	spin_unlock(&mmb->lock);
596 	return err;
597 }
598 EXPORT_SYMBOL(mmb_sync);
599 
600 /*
601  * Called when we've recently written block `bblock', and it is known that
602  * `bblock' was for a buffer_boundary() buffer.  This means that the block at
603  * `bblock + 1' is probably a dirty indirect block.  Hunt it down and, if it's
604  * dirty, schedule it for IO.  So that indirects merge nicely with their data.
605  */
606 void write_boundary_block(struct block_device *bdev,
607 			sector_t bblock, unsigned blocksize)
608 {
609 	struct buffer_head *bh;
610 
611 	bh = __find_get_block_nonatomic(bdev, bblock + 1, blocksize);
612 	if (bh) {
613 		if (buffer_dirty(bh))
614 			write_dirty_buffer(bh, 0);
615 		put_bh(bh);
616 	}
617 }
618 
619 /**
620  * mmb_mark_buffer_dirty - Mark a metadata buffer dirty.
621  * @bh: The buffer to mark dirty.
622  * @mmb: The list of buffers to add the buffer to.
623  *
624  * Mark the buffer dirty and add it to the list if it is not already on
625  * a list.
626  */
627 void mmb_mark_buffer_dirty(struct buffer_head *bh,
628 			   struct mapping_metadata_bhs *mmb)
629 {
630 	mark_buffer_dirty(bh);
631 	if (!bh->b_mmb) {
632 		spin_lock(&mmb->lock);
633 		/*
634 		 * For a corrupted filesystem with multiply claimed blocks this
635 		 * can fail. Avoid corrupting the linked list in that case.
636 		 */
637 		if (cmpxchg(&bh->b_mmb, NULL, mmb) != NULL) {
638 			spin_unlock(&mmb->lock);
639 			return;
640 		}
641 		list_move_tail(&bh->b_assoc_buffers, &mmb->list);
642 		spin_unlock(&mmb->lock);
643 	}
644 }
645 EXPORT_SYMBOL(mmb_mark_buffer_dirty);
646 
647 /**
648  * block_dirty_folio - Mark a folio as dirty.
649  * @mapping: The address space containing this folio.
650  * @folio: The folio to mark dirty.
651  *
652  * Filesystems which use buffer_heads can use this function as their
653  * ->dirty_folio implementation.  Some filesystems need to do a little
654  * work before calling this function.  Filesystems which do not use
655  * buffer_heads should call filemap_dirty_folio() instead.
656  *
657  * If the folio has buffers, the uptodate buffers are set dirty, to
658  * preserve dirty-state coherency between the folio and the buffers.
659  * Buffers added to a dirty folio are created dirty.
660  *
661  * The buffers are dirtied before the folio is dirtied.  There's a small
662  * race window in which writeback may see the folio cleanness but not the
663  * buffer dirtiness.  That's fine.  If this code were to set the folio
664  * dirty before the buffers, writeback could clear the folio dirty flag,
665  * see a bunch of clean buffers and we'd end up with dirty buffers/clean
666  * folio on the dirty folio list.
667  *
668  * We use i_private_lock to lock against try_to_free_buffers() while
669  * using the folio's buffer list.  This also prevents clean buffers
670  * being added to the folio after it was set dirty.
671  *
672  * Context: May only be called from process context.  Does not sleep.
673  * Caller must ensure that @folio cannot be truncated during this call,
674  * typically by holding the folio lock or having a page in the folio
675  * mapped and holding the page table lock.
676  *
677  * Return: True if the folio was dirtied; false if it was already dirtied.
678  */
679 bool block_dirty_folio(struct address_space *mapping, struct folio *folio)
680 {
681 	struct buffer_head *head;
682 	bool newly_dirty;
683 
684 	spin_lock(&mapping->i_private_lock);
685 	head = folio_buffers(folio);
686 	if (head) {
687 		struct buffer_head *bh = head;
688 
689 		do {
690 			set_buffer_dirty(bh);
691 			bh = bh->b_this_page;
692 		} while (bh != head);
693 	}
694 	/*
695 	 * Lock out folio's memcg migration to keep folio dirty flag
696 	 * synchronized with per-memcg dirty page counters.
697 	 */
698 	newly_dirty = !folio_test_set_dirty(folio);
699 	spin_unlock(&mapping->i_private_lock);
700 
701 	if (newly_dirty)
702 		__folio_mark_dirty(folio, mapping, 1);
703 
704 	if (newly_dirty)
705 		__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
706 
707 	return newly_dirty;
708 }
709 EXPORT_SYMBOL(block_dirty_folio);
710 
711 /*
712  * Invalidate any and all dirty buffers on a given buffers list.  We are
713  * probably unmounting the fs, but that doesn't mean we have already
714  * done a sync().  Just drop the buffers from the inode list.
715  */
716 void mmb_invalidate(struct mapping_metadata_bhs *mmb)
717 {
718 	if (mmb_has_buffers(mmb)) {
719 		spin_lock(&mmb->lock);
720 		while (!list_empty(&mmb->list))
721 			__remove_assoc_queue(mmb, BH_ENTRY(mmb->list.next));
722 		spin_unlock(&mmb->lock);
723 	}
724 }
725 EXPORT_SYMBOL(mmb_invalidate);
726 
727 /*
728  * Create the appropriate buffers when given a folio for data area and
729  * the size of each buffer.. Use the bh->b_this_page linked list to
730  * follow the buffers created.  Return NULL if unable to create more
731  * buffers.
732  *
733  * The retry flag is used to differentiate async IO (paging, swapping)
734  * which may not fail from ordinary buffer allocations.
735  */
736 struct buffer_head *folio_alloc_buffers(struct folio *folio, unsigned long size,
737 					gfp_t gfp)
738 {
739 	struct buffer_head *bh, *head;
740 	long offset;
741 	struct mem_cgroup *memcg, *old_memcg;
742 
743 	memcg = get_mem_cgroup_from_folio(folio);
744 	old_memcg = set_active_memcg(memcg);
745 
746 	head = NULL;
747 	offset = folio_size(folio);
748 	while ((offset -= size) >= 0) {
749 		bh = alloc_buffer_head(gfp);
750 		if (!bh)
751 			goto no_grow;
752 
753 		bh->b_this_page = head;
754 		bh->b_blocknr = -1;
755 		head = bh;
756 
757 		bh->b_size = size;
758 
759 		/* Link the buffer to its folio */
760 		folio_set_bh(bh, folio, offset);
761 	}
762 out:
763 	set_active_memcg(old_memcg);
764 	mem_cgroup_put(memcg);
765 	return head;
766 /*
767  * In case anything failed, we just free everything we got.
768  */
769 no_grow:
770 	if (head) {
771 		do {
772 			bh = head;
773 			head = head->b_this_page;
774 			free_buffer_head(bh);
775 		} while (head);
776 	}
777 
778 	goto out;
779 }
780 EXPORT_SYMBOL_GPL(folio_alloc_buffers);
781 
782 static inline void link_dev_buffers(struct folio *folio,
783 		struct buffer_head *head)
784 {
785 	struct buffer_head *bh, *tail;
786 
787 	bh = head;
788 	do {
789 		tail = bh;
790 		bh = bh->b_this_page;
791 	} while (bh);
792 	tail->b_this_page = head;
793 	folio_attach_private(folio, head);
794 }
795 
796 static sector_t blkdev_max_block(struct block_device *bdev, unsigned int size)
797 {
798 	sector_t retval = ~((sector_t)0);
799 	loff_t sz = bdev_nr_bytes(bdev);
800 
801 	if (sz) {
802 		unsigned int sizebits = blksize_bits(size);
803 		retval = (sz >> sizebits);
804 	}
805 	return retval;
806 }
807 
808 /*
809  * Initialise the state of a blockdev folio's buffers.
810  */
811 static sector_t folio_init_buffers(struct folio *folio,
812 		struct block_device *bdev, unsigned size)
813 {
814 	struct buffer_head *head = folio_buffers(folio);
815 	struct buffer_head *bh = head;
816 	bool uptodate = folio_test_uptodate(folio);
817 	sector_t block = div_u64(folio_pos(folio), size);
818 	sector_t end_block = blkdev_max_block(bdev, size);
819 
820 	do {
821 		if (!buffer_mapped(bh)) {
822 			bh->b_private = NULL;
823 			bh->b_bdev = bdev;
824 			bh->b_blocknr = block;
825 			if (uptodate)
826 				set_buffer_uptodate(bh);
827 			if (block < end_block)
828 				set_buffer_mapped(bh);
829 		}
830 		block++;
831 		bh = bh->b_this_page;
832 	} while (bh != head);
833 
834 	/*
835 	 * Caller needs to validate requested block against end of device.
836 	 */
837 	return end_block;
838 }
839 
840 /*
841  * Create the page-cache folio that contains the requested block.
842  *
843  * This is used purely for blockdev mappings.
844  *
845  * Returns false if we have a failure which cannot be cured by retrying
846  * without sleeping.  Returns true if we succeeded, or the caller should retry.
847  */
848 static bool grow_dev_folio(struct block_device *bdev, sector_t block,
849 		pgoff_t index, unsigned size, gfp_t gfp)
850 {
851 	struct address_space *mapping = bdev->bd_mapping;
852 	struct folio *folio;
853 	struct buffer_head *bh;
854 	sector_t end_block = 0;
855 
856 	folio = __filemap_get_folio(mapping, index,
857 			FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
858 	if (IS_ERR(folio))
859 		return false;
860 
861 	bh = folio_buffers(folio);
862 	if (bh) {
863 		if (bh->b_size == size) {
864 			end_block = folio_init_buffers(folio, bdev, size);
865 			goto unlock;
866 		}
867 
868 		/*
869 		 * Retrying may succeed; for example the folio may finish
870 		 * writeback, or buffers may be cleaned.  This should not
871 		 * happen very often; maybe we have old buffers attached to
872 		 * this blockdev's page cache and we're trying to change
873 		 * the block size?
874 		 */
875 		if (!try_to_free_buffers(folio)) {
876 			end_block = ~0ULL;
877 			goto unlock;
878 		}
879 	}
880 
881 	bh = folio_alloc_buffers(folio, size, gfp | __GFP_ACCOUNT);
882 	if (!bh)
883 		goto unlock;
884 
885 	/*
886 	 * Link the folio to the buffers and initialise them.  Take the
887 	 * lock to be atomic wrt __find_get_block(), which does not
888 	 * run under the folio lock.
889 	 */
890 	spin_lock(&mapping->i_private_lock);
891 	link_dev_buffers(folio, bh);
892 	end_block = folio_init_buffers(folio, bdev, size);
893 	spin_unlock(&mapping->i_private_lock);
894 unlock:
895 	folio_unlock(folio);
896 	folio_put(folio);
897 	return block < end_block;
898 }
899 
900 /*
901  * Create buffers for the specified block device block's folio.  If
902  * that folio was dirty, the buffers are set dirty also.  Returns false
903  * if we've hit a permanent error.
904  */
905 static bool grow_buffers(struct block_device *bdev, sector_t block,
906 		unsigned size, gfp_t gfp)
907 {
908 	loff_t pos;
909 
910 	/*
911 	 * Check for a block which lies outside our maximum possible
912 	 * pagecache index.
913 	 */
914 	if (check_mul_overflow(block, (sector_t)size, &pos) || pos > MAX_LFS_FILESIZE) {
915 		printk(KERN_ERR "%s: requested out-of-range block %llu for device %pg\n",
916 			__func__, (unsigned long long)block,
917 			bdev);
918 		return false;
919 	}
920 
921 	/* Create a folio with the proper size buffers */
922 	return grow_dev_folio(bdev, block, pos / PAGE_SIZE, size, gfp);
923 }
924 
925 static struct buffer_head *
926 __getblk_slow(struct block_device *bdev, sector_t block,
927 	     unsigned size, gfp_t gfp)
928 {
929 	bool blocking = gfpflags_allow_blocking(gfp);
930 
931 	if (WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))) {
932 		printk(KERN_ERR "getblk(): block size %d not aligned to logical block size %d\n",
933 		       size, bdev_logical_block_size(bdev));
934 		return NULL;
935 	}
936 
937 	for (;;) {
938 		struct buffer_head *bh;
939 
940 		if (!grow_buffers(bdev, block, size, gfp))
941 			return NULL;
942 
943 		if (blocking)
944 			bh = __find_get_block_nonatomic(bdev, block, size);
945 		else
946 			bh = __find_get_block(bdev, block, size);
947 		if (bh)
948 			return bh;
949 	}
950 }
951 
952 /*
953  * The relationship between dirty buffers and dirty folios:
954  *
955  * Whenever a folio has any dirty buffers, the folio's dirty flag is set, and
956  * the folio is tagged dirty in the page cache.
957  *
958  * At all times, the dirtiness of the buffers represents the dirtiness of
959  * subsections of the folio.  If the folio has buffers, the folio dirty flag is
960  * merely a hint about the true dirty state.
961  *
962  * When a folio is set dirty in its entirety, all its buffers are marked dirty
963  * (if the folio has buffers).
964  *
965  * When a buffer is marked dirty, its folio is dirtied, but the folio's other
966  * buffers are not.
967  *
968  * Also.  When blockdev buffers are explicitly read with bread(), they
969  * individually become uptodate.  But their backing folio remains not
970  * uptodate - even if all of its buffers are uptodate.  A subsequent
971  * block_read_full_folio() against that folio will discover all the uptodate
972  * buffers, will set the folio uptodate and will perform no I/O.
973  */
974 
975 /**
976  * mark_buffer_dirty - mark a buffer_head as needing writeout
977  * @bh: the buffer_head to mark dirty
978  *
979  * mark_buffer_dirty() will set the dirty bit against the buffer, then set
980  * its backing folio dirty, then tag the folio as dirty in the page cache
981  * and then attach the address_space's inode to its superblock's dirty
982  * inode list.
983  *
984  * mark_buffer_dirty() is atomic.  It takes bh->b_folio->mapping->i_private_lock,
985  * i_pages lock and mapping->host->i_lock.
986  */
987 void mark_buffer_dirty(struct buffer_head *bh)
988 {
989 	WARN_ON_ONCE(!buffer_uptodate(bh));
990 
991 	trace_block_dirty_buffer(bh);
992 
993 	/*
994 	 * Very *carefully* optimize the it-is-already-dirty case.
995 	 *
996 	 * Don't let the final "is it dirty" escape to before we
997 	 * perhaps modified the buffer.
998 	 */
999 	if (buffer_dirty(bh)) {
1000 		smp_mb();
1001 		if (buffer_dirty(bh))
1002 			return;
1003 	}
1004 
1005 	if (!test_set_buffer_dirty(bh)) {
1006 		struct folio *folio = bh->b_folio;
1007 		struct address_space *mapping = NULL;
1008 
1009 		if (!folio_test_set_dirty(folio)) {
1010 			mapping = folio->mapping;
1011 			if (mapping)
1012 				__folio_mark_dirty(folio, mapping, 0);
1013 		}
1014 		if (mapping)
1015 			__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1016 	}
1017 }
1018 EXPORT_SYMBOL(mark_buffer_dirty);
1019 
1020 void mark_buffer_write_io_error(struct buffer_head *bh)
1021 {
1022 	struct mapping_metadata_bhs *mmb;
1023 
1024 	set_buffer_write_io_error(bh);
1025 	/* FIXME: do we need to set this in both places? */
1026 	if (bh->b_folio && bh->b_folio->mapping)
1027 		mapping_set_error(bh->b_folio->mapping, -EIO);
1028 	/* Protect us from mmb & inode getting freed while we work on it */
1029 	rcu_read_lock();
1030 	mmb = READ_ONCE(bh->b_mmb);
1031 	if (mmb)
1032 		mapping_set_error(mmb->mapping, -EIO);
1033 	rcu_read_unlock();
1034 }
1035 EXPORT_SYMBOL(mark_buffer_write_io_error);
1036 
1037 /**
1038  * __brelse - Release a buffer.
1039  * @bh: The buffer to release.
1040  *
1041  * This variant of brelse() can be called if @bh is guaranteed to not be NULL.
1042  */
1043 void __brelse(struct buffer_head *bh)
1044 {
1045 	if (atomic_read(&bh->b_count)) {
1046 		put_bh(bh);
1047 		return;
1048 	}
1049 	WARN(1, KERN_ERR "VFS: brelse: Trying to free free buffer\n");
1050 }
1051 EXPORT_SYMBOL(__brelse);
1052 
1053 /**
1054  * __bforget - Discard any dirty data in a buffer.
1055  * @bh: The buffer to forget.
1056  *
1057  * This variant of bforget() can be called if @bh is guaranteed to not
1058  * be NULL.
1059  */
1060 void __bforget(struct buffer_head *bh)
1061 {
1062 	clear_buffer_dirty(bh);
1063 	clear_buffer_write_io_error(bh);
1064 	remove_assoc_queue(bh);
1065 	__brelse(bh);
1066 }
1067 EXPORT_SYMBOL(__bforget);
1068 
1069 static void buffer_set_crypto_ctx(struct bio *bio, const struct buffer_head *bh,
1070 				  gfp_t gfp_mask)
1071 {
1072 	const struct address_space *mapping;
1073 
1074 	/*
1075 	 * The ext4 journal (jbd2) can submit a buffer_head it directly created
1076 	 * for memory that is not in the page cache at all.  fscrypt doesn't
1077 	 * care about these.
1078 	 */
1079 	if (!bh->b_folio)
1080 		return;
1081 	mapping = bh->b_folio->mapping;
1082 	if (!mapping)
1083 		return;
1084 	fscrypt_set_bio_crypt_ctx(bio, mapping->host,
1085 			folio_pos(bh->b_folio) + bh_offset(bh), gfp_mask);
1086 }
1087 
1088 static void __bh_submit(struct buffer_head *bh, blk_opf_t opf,
1089 		enum rw_hint write_hint, struct writeback_control *wbc,
1090 		bio_end_io_t end_bio)
1091 {
1092 	struct bio *bio;
1093 
1094 	BUG_ON(!buffer_locked(bh));
1095 	BUG_ON(!buffer_mapped(bh));
1096 	BUG_ON(buffer_delay(bh));
1097 	BUG_ON(buffer_unwritten(bh));
1098 
1099 	set_buffer_req(bh);
1100 
1101 	if (buffer_meta(bh))
1102 		opf |= REQ_META;
1103 	if (buffer_prio(bh))
1104 		opf |= REQ_PRIO;
1105 
1106 	bio = bio_alloc(bh->b_bdev, 1, opf, GFP_NOIO);
1107 
1108 	if (bh->b_folio && folio_test_dropbehind(bh->b_folio) &&
1109 	    op_is_write(opf))
1110 		bio_set_flag(bio, BIO_COMPLETE_IN_TASK);
1111 
1112 	if (IS_ENABLED(CONFIG_FS_ENCRYPTION))
1113 		buffer_set_crypto_ctx(bio, bh, GFP_NOIO);
1114 
1115 	bio->bi_iter.bi_sector = bh->b_blocknr * (bh->b_size >> 9);
1116 	bio->bi_write_hint = write_hint;
1117 
1118 	if (bh->b_folio)
1119 		bio_add_folio_nofail(bio, bh->b_folio, bh->b_size,
1120 				     bh_offset(bh));
1121 	else
1122 		bio_add_virt_nofail(bio, bh->b_data, bh->b_size);
1123 
1124 	bio->bi_end_io = end_bio;
1125 	bio->bi_private = bh;
1126 
1127 	/* Take care of bh's that straddle the end of the device */
1128 	guard_bio_eod(bio);
1129 
1130 	if (wbc) {
1131 		wbc_init_bio(wbc, bio);
1132 		if (bh->b_folio)
1133 			wbc_account_cgroup_owner(wbc, bh->b_folio, bh->b_size);
1134 	}
1135 
1136 	blk_crypto_submit_bio(bio);
1137 }
1138 
1139 /**
1140  * bh_submit - Start I/O against a buffer head
1141  * @bh: The buffer head to perform I/O on.
1142  * @opf: Operation and flags for bio.
1143  * @end_io: The routine to call when I/O has completed.
1144  *
1145  * If you need to do I/O on an individual bh (instead of allowing the
1146  * page cache to do I/O on the folio that it is in), call this function.
1147  */
1148 void bh_submit(struct buffer_head *bh, blk_opf_t opf, bio_end_io_t end_io)
1149 {
1150 	__bh_submit(bh, opf, WRITE_LIFE_NOT_SET, NULL, end_io);
1151 }
1152 EXPORT_SYMBOL(bh_submit);
1153 
1154 static struct buffer_head *__bread_slow(struct buffer_head *bh)
1155 {
1156 	lock_buffer(bh);
1157 	if (buffer_uptodate(bh)) {
1158 		unlock_buffer(bh);
1159 		return bh;
1160 	} else {
1161 		bh_submit(bh, REQ_OP_READ, bh_end_read);
1162 		wait_on_buffer(bh);
1163 		if (buffer_uptodate(bh))
1164 			return bh;
1165 	}
1166 	brelse(bh);
1167 	return NULL;
1168 }
1169 
1170 /*
1171  * Per-cpu buffer LRU implementation.  To reduce the cost of __find_get_block().
1172  * The bhs[] array is sorted - newest buffer is at bhs[0].  Buffers have their
1173  * refcount elevated by one when they're in an LRU.  A buffer can only appear
1174  * once in a particular CPU's LRU.  A single buffer can be present in multiple
1175  * CPU's LRUs at the same time.
1176  *
1177  * This is a transparent caching front-end to sb_bread(), sb_getblk() and
1178  * sb_find_get_block().
1179  *
1180  * The LRUs themselves only need locking against invalidate_bh_lrus.  We use
1181  * a local interrupt disable for that.
1182  */
1183 
1184 #define BH_LRU_SIZE	16
1185 
1186 struct bh_lru {
1187 	struct buffer_head *bhs[BH_LRU_SIZE];
1188 };
1189 
1190 static DEFINE_PER_CPU(struct bh_lru, bh_lrus) = {{ NULL }};
1191 
1192 #ifdef CONFIG_SMP
1193 #define bh_lru_lock()	local_irq_disable()
1194 #define bh_lru_unlock()	local_irq_enable()
1195 #else
1196 #define bh_lru_lock()	preempt_disable()
1197 #define bh_lru_unlock()	preempt_enable()
1198 #endif
1199 
1200 static inline void check_irqs_on(void)
1201 {
1202 #ifdef irqs_disabled
1203 	BUG_ON(irqs_disabled());
1204 #endif
1205 }
1206 
1207 /*
1208  * Install a buffer_head into this cpu's LRU.  If not already in the LRU, it is
1209  * inserted at the front, and the buffer_head at the back if any is evicted.
1210  * Or, if already in the LRU it is moved to the front.
1211  */
1212 static void bh_lru_install(struct buffer_head *bh)
1213 {
1214 	struct buffer_head *evictee = bh;
1215 	struct bh_lru *b;
1216 	int i;
1217 
1218 	check_irqs_on();
1219 	bh_lru_lock();
1220 
1221 	/*
1222 	 * the refcount of buffer_head in bh_lru prevents dropping the
1223 	 * attached folio (i.e., try_to_free_buffers) so it could cause
1224 	 * failing page migration.
1225 	 * Skip putting upcoming bh into bh_lru until migration is done.
1226 	 */
1227 	if (lru_cache_disabled() || cpu_is_isolated(smp_processor_id())) {
1228 		bh_lru_unlock();
1229 		return;
1230 	}
1231 
1232 	b = this_cpu_ptr(&bh_lrus);
1233 	for (i = 0; i < BH_LRU_SIZE; i++) {
1234 		swap(evictee, b->bhs[i]);
1235 		if (evictee == bh) {
1236 			bh_lru_unlock();
1237 			return;
1238 		}
1239 	}
1240 
1241 	get_bh(bh);
1242 	bh_lru_unlock();
1243 	brelse(evictee);
1244 }
1245 
1246 /*
1247  * Look up the bh in this cpu's LRU.  If it's there, move it to the head.
1248  */
1249 static struct buffer_head *
1250 lookup_bh_lru(struct block_device *bdev, sector_t block, unsigned size)
1251 {
1252 	struct buffer_head *ret = NULL;
1253 	unsigned int i;
1254 
1255 	check_irqs_on();
1256 	bh_lru_lock();
1257 	if (cpu_is_isolated(smp_processor_id())) {
1258 		bh_lru_unlock();
1259 		return NULL;
1260 	}
1261 	for (i = 0; i < BH_LRU_SIZE; i++) {
1262 		struct buffer_head *bh = __this_cpu_read(bh_lrus.bhs[i]);
1263 
1264 		if (bh && bh->b_blocknr == block && bh->b_bdev == bdev &&
1265 		    bh->b_size == size) {
1266 			if (i) {
1267 				while (i) {
1268 					__this_cpu_write(bh_lrus.bhs[i],
1269 						__this_cpu_read(bh_lrus.bhs[i - 1]));
1270 					i--;
1271 				}
1272 				__this_cpu_write(bh_lrus.bhs[0], bh);
1273 			}
1274 			get_bh(bh);
1275 			ret = bh;
1276 			break;
1277 		}
1278 	}
1279 	bh_lru_unlock();
1280 	return ret;
1281 }
1282 
1283 /*
1284  * Perform a pagecache lookup for the matching buffer.  If it's there, refresh
1285  * it in the LRU and mark it as accessed.  If it is not present then return
1286  * NULL. Atomic context callers may also return NULL if the buffer is being
1287  * migrated; similarly the folio is not marked accessed either.
1288  */
1289 static struct buffer_head *
1290 find_get_block_common(struct block_device *bdev, sector_t block,
1291 			unsigned size, bool atomic)
1292 {
1293 	struct buffer_head *bh = lookup_bh_lru(bdev, block, size);
1294 
1295 	if (bh == NULL) {
1296 		/* __find_get_block_slow will mark the folio accessed */
1297 		bh = __find_get_block_slow(bdev, block, atomic);
1298 		if (bh)
1299 			bh_lru_install(bh);
1300 	} else
1301 		touch_buffer(bh);
1302 
1303 	return bh;
1304 }
1305 
1306 struct buffer_head *
1307 __find_get_block(struct block_device *bdev, sector_t block, unsigned size)
1308 {
1309 	return find_get_block_common(bdev, block, size, true);
1310 }
1311 EXPORT_SYMBOL(__find_get_block);
1312 
1313 /* same as __find_get_block() but allows sleeping contexts */
1314 struct buffer_head *
1315 __find_get_block_nonatomic(struct block_device *bdev, sector_t block,
1316 			   unsigned size)
1317 {
1318 	return find_get_block_common(bdev, block, size, false);
1319 }
1320 EXPORT_SYMBOL(__find_get_block_nonatomic);
1321 
1322 /**
1323  * bdev_getblk - Get a buffer_head in a block device's buffer cache.
1324  * @bdev: The block device.
1325  * @block: The block number.
1326  * @size: The size of buffer_heads for this @bdev.
1327  * @gfp: The memory allocation flags to use.
1328  *
1329  * The returned buffer head has its reference count incremented, but is
1330  * not locked.  The caller should call brelse() when it has finished
1331  * with the buffer.  The buffer may not be uptodate.  If needed, the
1332  * caller can bring it uptodate either by reading it or overwriting it.
1333  *
1334  * Return: The buffer head, or NULL if memory could not be allocated.
1335  */
1336 struct buffer_head *bdev_getblk(struct block_device *bdev, sector_t block,
1337 		unsigned size, gfp_t gfp)
1338 {
1339 	struct buffer_head *bh;
1340 
1341 	if (gfpflags_allow_blocking(gfp))
1342 		bh = __find_get_block_nonatomic(bdev, block, size);
1343 	else
1344 		bh = __find_get_block(bdev, block, size);
1345 
1346 	might_alloc(gfp);
1347 	if (bh)
1348 		return bh;
1349 
1350 	return __getblk_slow(bdev, block, size, gfp);
1351 }
1352 EXPORT_SYMBOL(bdev_getblk);
1353 
1354 /*
1355  * Do async read-ahead on a buffer..
1356  */
1357 void __breadahead(struct block_device *bdev, sector_t block, unsigned size)
1358 {
1359 	struct buffer_head *bh = bdev_getblk(bdev, block, size,
1360 			GFP_NOWAIT | __GFP_MOVABLE);
1361 
1362 	if (likely(bh)) {
1363 		bh_readahead(bh, REQ_RAHEAD);
1364 		brelse(bh);
1365 	}
1366 }
1367 EXPORT_SYMBOL(__breadahead);
1368 
1369 /**
1370  * __bread_gfp() - Read a block.
1371  * @bdev: The block device to read from.
1372  * @block: Block number in units of block size.
1373  * @size: The block size of this device in bytes.
1374  * @gfp: Not page allocation flags; see below.
1375  *
1376  * You are not expected to call this function.  You should use one of
1377  * sb_bread(), sb_bread_unmovable() or __bread().
1378  *
1379  * Read a specified block, and return the buffer head that refers to it.
1380  * If @gfp is 0, the memory will be allocated using the block device's
1381  * default GFP flags.  If @gfp is __GFP_MOVABLE, the memory may be
1382  * allocated from a movable area.  Do not pass in a complete set of
1383  * GFP flags.
1384  *
1385  * The returned buffer head has its refcount increased.  The caller should
1386  * call brelse() when it has finished with the buffer.
1387  *
1388  * Context: May sleep waiting for I/O.
1389  * Return: NULL if the block was unreadable.
1390  */
1391 struct buffer_head *__bread_gfp(struct block_device *bdev, sector_t block,
1392 		unsigned size, gfp_t gfp)
1393 {
1394 	struct buffer_head *bh;
1395 
1396 	gfp |= mapping_gfp_constraint(bdev->bd_mapping, ~__GFP_FS);
1397 
1398 	/*
1399 	 * Prefer looping in the allocator rather than here, at least that
1400 	 * code knows what it's doing.
1401 	 */
1402 	gfp |= __GFP_NOFAIL;
1403 
1404 	bh = bdev_getblk(bdev, block, size, gfp);
1405 
1406 	if (likely(bh) && !buffer_uptodate(bh))
1407 		bh = __bread_slow(bh);
1408 	return bh;
1409 }
1410 EXPORT_SYMBOL(__bread_gfp);
1411 
1412 static void __invalidate_bh_lrus(struct bh_lru *b)
1413 {
1414 	int i;
1415 
1416 	for (i = 0; i < BH_LRU_SIZE; i++) {
1417 		brelse(b->bhs[i]);
1418 		b->bhs[i] = NULL;
1419 	}
1420 }
1421 /*
1422  * invalidate_bh_lrus() is called rarely - but not only at unmount.
1423  * This doesn't race because it runs in each cpu either in irq
1424  * or with preempt disabled.
1425  */
1426 static void invalidate_bh_lru(void *arg)
1427 {
1428 	struct bh_lru *b = &get_cpu_var(bh_lrus);
1429 
1430 	__invalidate_bh_lrus(b);
1431 	put_cpu_var(bh_lrus);
1432 }
1433 
1434 bool has_bh_in_lru(int cpu, void *dummy)
1435 {
1436 	struct bh_lru *b = per_cpu_ptr(&bh_lrus, cpu);
1437 	int i;
1438 
1439 	for (i = 0; i < BH_LRU_SIZE; i++) {
1440 		if (b->bhs[i])
1441 			return true;
1442 	}
1443 
1444 	return false;
1445 }
1446 
1447 void invalidate_bh_lrus(void)
1448 {
1449 	on_each_cpu_cond(has_bh_in_lru, invalidate_bh_lru, NULL, 1);
1450 }
1451 EXPORT_SYMBOL_GPL(invalidate_bh_lrus);
1452 
1453 /*
1454  * It's called from workqueue context so we need a bh_lru_lock to close
1455  * the race with preemption/irq.
1456  */
1457 void invalidate_bh_lrus_cpu(void)
1458 {
1459 	struct bh_lru *b;
1460 
1461 	bh_lru_lock();
1462 	b = this_cpu_ptr(&bh_lrus);
1463 	__invalidate_bh_lrus(b);
1464 	bh_lru_unlock();
1465 }
1466 
1467 void folio_set_bh(struct buffer_head *bh, struct folio *folio,
1468 		  unsigned long offset)
1469 {
1470 	bh->b_folio = folio;
1471 	BUG_ON(offset >= folio_size(folio));
1472 	if (folio_test_highmem(folio))
1473 		/*
1474 		 * This catches illegal uses and preserves the offset:
1475 		 */
1476 		bh->b_data = (char *)(0 + offset);
1477 	else
1478 		bh->b_data = folio_address(folio) + offset;
1479 }
1480 EXPORT_SYMBOL(folio_set_bh);
1481 
1482 /* Bits that are cleared during an invalidate */
1483 #define BUFFER_FLAGS_DISCARD \
1484 	(1 << BH_Mapped | 1 << BH_New | 1 << BH_Req | \
1485 	 1 << BH_Delay | 1 << BH_Unwritten | 1 << BH_Write_EIO)
1486 
1487 /*
1488  * Called when truncating a buffer on a folio completely.
1489  */
1490 static void discard_buffer(struct buffer_head * bh)
1491 {
1492 	unsigned long b_state;
1493 
1494 	lock_buffer(bh);
1495 	clear_buffer_dirty(bh);
1496 	bh->b_bdev = NULL;
1497 	b_state = READ_ONCE(bh->b_state);
1498 	do {
1499 	} while (!try_cmpxchg_relaxed(&bh->b_state, &b_state,
1500 				      b_state & ~BUFFER_FLAGS_DISCARD));
1501 	unlock_buffer(bh);
1502 }
1503 
1504 /**
1505  * block_invalidate_folio - Invalidate part or all of a buffer-backed folio.
1506  * @folio: The folio which is affected.
1507  * @offset: start of the range to invalidate
1508  * @length: length of the range to invalidate
1509  *
1510  * block_invalidate_folio() is called when all or part of the folio has been
1511  * invalidated by a truncate operation.
1512  *
1513  * block_invalidate_folio() does not have to release all buffers, but it must
1514  * ensure that no dirty buffer is left outside @offset and that no I/O
1515  * is underway against any of the blocks which are outside the truncation
1516  * point.  Because the caller is about to free (and possibly reuse) those
1517  * blocks on-disk.
1518  */
1519 void block_invalidate_folio(struct folio *folio, size_t offset, size_t length)
1520 {
1521 	struct buffer_head *head, *bh, *next;
1522 	size_t curr_off = 0;
1523 	size_t stop = length + offset;
1524 
1525 	BUG_ON(!folio_test_locked(folio));
1526 
1527 	/*
1528 	 * Check for overflow
1529 	 */
1530 	BUG_ON(stop > folio_size(folio) || stop < length);
1531 
1532 	head = folio_buffers(folio);
1533 	if (!head)
1534 		return;
1535 
1536 	bh = head;
1537 	do {
1538 		size_t next_off = curr_off + bh->b_size;
1539 		next = bh->b_this_page;
1540 
1541 		/*
1542 		 * Are we still fully in range ?
1543 		 */
1544 		if (next_off > stop)
1545 			goto out;
1546 
1547 		/*
1548 		 * is this block fully invalidated?
1549 		 */
1550 		if (offset <= curr_off)
1551 			discard_buffer(bh);
1552 		curr_off = next_off;
1553 		bh = next;
1554 	} while (bh != head);
1555 
1556 	/*
1557 	 * We release buffers only if the entire folio is being invalidated.
1558 	 * The get_block cached value has been unconditionally invalidated,
1559 	 * so real IO is not possible anymore.
1560 	 */
1561 	if (length == folio_size(folio))
1562 		filemap_release_folio(folio, 0);
1563 out:
1564 	folio_clear_mappedtodisk(folio);
1565 }
1566 EXPORT_SYMBOL(block_invalidate_folio);
1567 
1568 /*
1569  * We attach and possibly dirty the buffers atomically wrt
1570  * block_dirty_folio() via i_private_lock.  try_to_free_buffers
1571  * is already excluded via the folio lock.
1572  */
1573 struct buffer_head *create_empty_buffers(struct folio *folio,
1574 		unsigned long blocksize, unsigned long b_state)
1575 {
1576 	struct buffer_head *bh, *head, *tail;
1577 	gfp_t gfp = GFP_NOFS | __GFP_ACCOUNT | __GFP_NOFAIL;
1578 
1579 	head = folio_alloc_buffers(folio, blocksize, gfp);
1580 	bh = head;
1581 	do {
1582 		bh->b_state |= b_state;
1583 		tail = bh;
1584 		bh = bh->b_this_page;
1585 	} while (bh);
1586 	tail->b_this_page = head;
1587 
1588 	spin_lock(&folio->mapping->i_private_lock);
1589 	if (folio_test_uptodate(folio) || folio_test_dirty(folio)) {
1590 		bh = head;
1591 		do {
1592 			if (folio_test_dirty(folio))
1593 				set_buffer_dirty(bh);
1594 			if (folio_test_uptodate(folio))
1595 				set_buffer_uptodate(bh);
1596 			bh = bh->b_this_page;
1597 		} while (bh != head);
1598 	}
1599 	folio_attach_private(folio, head);
1600 	spin_unlock(&folio->mapping->i_private_lock);
1601 
1602 	return head;
1603 }
1604 EXPORT_SYMBOL(create_empty_buffers);
1605 
1606 /**
1607  * clean_bdev_aliases: clean a range of buffers in block device
1608  * @bdev: Block device to clean buffers in
1609  * @block: Start of a range of blocks to clean
1610  * @len: Number of blocks to clean
1611  *
1612  * We are taking a range of blocks for data and we don't want writeback of any
1613  * buffer-cache aliases starting from return from this function and until the
1614  * moment when something will explicitly mark the buffer dirty (hopefully that
1615  * will not happen until we will free that block ;-) We don't even need to mark
1616  * it not-uptodate - nobody can expect anything from a newly allocated buffer
1617  * anyway.
1618  *
1619  * Also..  Note that bforget() doesn't lock the buffer.  So there can be
1620  * writeout I/O going on against recently-freed buffers.  We don't wait on that
1621  * I/O in bforget() - it's more efficient to wait on the I/O only if we really
1622  * need to.  That happens here.
1623  */
1624 void clean_bdev_aliases(struct block_device *bdev, sector_t block, sector_t len)
1625 {
1626 	struct address_space *bd_mapping = bdev->bd_mapping;
1627 	const int blkbits = bd_mapping->host->i_blkbits;
1628 	struct folio_batch fbatch;
1629 	pgoff_t index = ((loff_t)block << blkbits) / PAGE_SIZE;
1630 	pgoff_t end;
1631 	int i, count;
1632 	struct buffer_head *bh;
1633 	struct buffer_head *head;
1634 
1635 	end = ((loff_t)(block + len - 1) << blkbits) / PAGE_SIZE;
1636 	folio_batch_init(&fbatch);
1637 	while (filemap_get_folios(bd_mapping, &index, end, &fbatch)) {
1638 		count = folio_batch_count(&fbatch);
1639 		for (i = 0; i < count; i++) {
1640 			struct folio *folio = fbatch.folios[i];
1641 
1642 			if (!folio_buffers(folio))
1643 				continue;
1644 			/*
1645 			 * We use folio lock instead of bd_mapping->i_private_lock
1646 			 * to pin buffers here since we can afford to sleep and
1647 			 * it scales better than a global spinlock lock.
1648 			 */
1649 			folio_lock(folio);
1650 			/* Recheck when the folio is locked which pins bhs */
1651 			head = folio_buffers(folio);
1652 			if (!head)
1653 				goto unlock_folio;
1654 			bh = head;
1655 			do {
1656 				if (!buffer_mapped(bh) || (bh->b_blocknr < block))
1657 					goto next;
1658 				if (bh->b_blocknr >= block + len)
1659 					break;
1660 				clear_buffer_dirty(bh);
1661 				wait_on_buffer(bh);
1662 				clear_buffer_req(bh);
1663 next:
1664 				bh = bh->b_this_page;
1665 			} while (bh != head);
1666 unlock_folio:
1667 			folio_unlock(folio);
1668 		}
1669 		folio_batch_release(&fbatch);
1670 		cond_resched();
1671 		/* End of range already reached? */
1672 		if (index > end || !index)
1673 			break;
1674 	}
1675 }
1676 EXPORT_SYMBOL(clean_bdev_aliases);
1677 
1678 static struct buffer_head *folio_create_buffers(struct folio *folio,
1679 						struct inode *inode,
1680 						unsigned int b_state)
1681 {
1682 	struct buffer_head *bh;
1683 
1684 	BUG_ON(!folio_test_locked(folio));
1685 
1686 	bh = folio_buffers(folio);
1687 	if (!bh)
1688 		bh = create_empty_buffers(folio,
1689 				1 << READ_ONCE(inode->i_blkbits), b_state);
1690 	return bh;
1691 }
1692 
1693 /*
1694  * NOTE! All mapped/uptodate combinations are valid:
1695  *
1696  *	Mapped	Uptodate	Meaning
1697  *
1698  *	No	No		"unknown" - must do get_block()
1699  *	No	Yes		"hole" - zero-filled
1700  *	Yes	No		"allocated" - allocated on disk, not read in
1701  *	Yes	Yes		"valid" - allocated and up-to-date in memory.
1702  *
1703  * "Dirty" is valid only with the last case (mapped+uptodate).
1704  */
1705 
1706 /*
1707  * While block_write_full_folio is writing back the dirty buffers under
1708  * the folio lock, whoever dirtied the buffers may decide to clean them
1709  * again at any time.  We handle that by only looking at the buffer
1710  * state inside lock_buffer().
1711  *
1712  * If block_write_full_folio() is called for regular writeback
1713  * (wbc->sync_mode == WB_SYNC_NONE) then it will redirty a folio which
1714  * has a locked buffer.   This can only happen if someone has written
1715  * the buffer directly, with bh_submit().  At the address_space level
1716  * the folio writeback flag prevents this contention from occurring.
1717  *
1718  * If block_write_full_folio() is called with wbc->sync_mode ==
1719  * WB_SYNC_ALL, the writes are posted using REQ_SYNC; this
1720  * causes the writes to be flagged as synchronous writes.
1721  */
1722 int __block_write_full_folio(struct inode *inode, struct folio *folio,
1723 			get_block_t *get_block, struct writeback_control *wbc)
1724 {
1725 	int err;
1726 	sector_t block;
1727 	sector_t last_block;
1728 	struct buffer_head *bh, *head;
1729 	size_t blocksize;
1730 	int nr_underway = 0;
1731 	blk_opf_t write_flags = wbc_to_write_flags(wbc);
1732 
1733 	head = folio_create_buffers(folio, inode,
1734 				    (1 << BH_Dirty) | (1 << BH_Uptodate));
1735 
1736 	/*
1737 	 * Be very careful.  We have no exclusion from block_dirty_folio
1738 	 * here, and the (potentially unmapped) buffers may become dirty at
1739 	 * any time.  If a buffer becomes dirty here after we've inspected it
1740 	 * then we just miss that fact, and the folio stays dirty.
1741 	 *
1742 	 * Buffers outside i_size may be dirtied by block_dirty_folio;
1743 	 * handle that here by just cleaning them.
1744 	 */
1745 
1746 	bh = head;
1747 	blocksize = bh->b_size;
1748 
1749 	block = div_u64(folio_pos(folio), blocksize);
1750 	last_block = div_u64(i_size_read(inode) - 1, blocksize);
1751 
1752 	/*
1753 	 * Get all the dirty buffers mapped to disk addresses and
1754 	 * handle any aliases from the underlying blockdev's mapping.
1755 	 */
1756 	do {
1757 		if (block > last_block) {
1758 			/*
1759 			 * mapped buffers outside i_size will occur, because
1760 			 * this folio can be outside i_size when there is a
1761 			 * truncate in progress.
1762 			 */
1763 			/*
1764 			 * The buffer was zeroed by block_write_full_folio()
1765 			 */
1766 			clear_buffer_dirty(bh);
1767 			set_buffer_uptodate(bh);
1768 		} else if ((!buffer_mapped(bh) || buffer_delay(bh)) &&
1769 			   buffer_dirty(bh)) {
1770 			WARN_ON(bh->b_size != blocksize);
1771 			err = get_block(inode, block, bh, 1);
1772 			if (err)
1773 				goto recover;
1774 			clear_buffer_delay(bh);
1775 			if (buffer_new(bh)) {
1776 				/* blockdev mappings never come here */
1777 				clear_buffer_new(bh);
1778 				clean_bdev_bh_alias(bh);
1779 			}
1780 		}
1781 		bh = bh->b_this_page;
1782 		block++;
1783 	} while (bh != head);
1784 
1785 	do {
1786 		if (!buffer_mapped(bh))
1787 			continue;
1788 		/*
1789 		 * If it's a fully non-blocking write attempt and we cannot
1790 		 * lock the buffer then redirty the folio.  Note that this can
1791 		 * potentially cause a busy-wait loop from writeback threads
1792 		 * and kswapd activity, but those code paths have their own
1793 		 * higher-level throttling.
1794 		 */
1795 		if (wbc->sync_mode != WB_SYNC_NONE) {
1796 			lock_buffer(bh);
1797 		} else if (!trylock_buffer(bh)) {
1798 			folio_redirty_for_writepage(wbc, folio);
1799 			continue;
1800 		}
1801 		if (test_clear_buffer_dirty(bh)) {
1802 			set_buffer_async_write(bh);
1803 		} else {
1804 			unlock_buffer(bh);
1805 		}
1806 	} while ((bh = bh->b_this_page) != head);
1807 
1808 	/*
1809 	 * The folio and its buffers are protected by the writeback flag,
1810 	 * so we can drop the bh refcounts early.
1811 	 */
1812 	BUG_ON(folio_test_writeback(folio));
1813 	folio_start_writeback(folio);
1814 
1815 	do {
1816 		struct buffer_head *next = bh->b_this_page;
1817 		if (buffer_async_write(bh)) {
1818 			__bh_submit(bh, REQ_OP_WRITE | write_flags,
1819 					inode->i_write_hint, wbc,
1820 					bh_end_async_write);
1821 			nr_underway++;
1822 		}
1823 		bh = next;
1824 	} while (bh != head);
1825 	folio_unlock(folio);
1826 
1827 	err = 0;
1828 done:
1829 	if (nr_underway == 0) {
1830 		/*
1831 		 * The folio was marked dirty, but the buffers were
1832 		 * clean.  Someone wrote them back by hand with
1833 		 * write_dirty_buffer/bh_submit.  A rare case.
1834 		 */
1835 		folio_end_writeback(folio);
1836 
1837 		/*
1838 		 * The folio and buffer_heads can be released at any time from
1839 		 * here on.
1840 		 */
1841 	}
1842 	return err;
1843 
1844 recover:
1845 	/*
1846 	 * ENOSPC, or some other error.  We may already have added some
1847 	 * blocks to the file, so we need to write these out to avoid
1848 	 * exposing stale data.
1849 	 * The folio is currently locked and not marked for writeback
1850 	 */
1851 	bh = head;
1852 	/* Recovery: lock and submit the mapped buffers */
1853 	do {
1854 		if (buffer_mapped(bh) && buffer_dirty(bh) &&
1855 		    !buffer_delay(bh)) {
1856 			lock_buffer(bh);
1857 			set_buffer_async_write(bh);
1858 		} else {
1859 			/*
1860 			 * The buffer may have been set dirty during
1861 			 * attachment to a dirty folio.
1862 			 */
1863 			clear_buffer_dirty(bh);
1864 		}
1865 	} while ((bh = bh->b_this_page) != head);
1866 	BUG_ON(folio_test_writeback(folio));
1867 	mapping_set_error(folio->mapping, err);
1868 	folio_start_writeback(folio);
1869 	do {
1870 		struct buffer_head *next = bh->b_this_page;
1871 		if (buffer_async_write(bh)) {
1872 			clear_buffer_dirty(bh);
1873 			__bh_submit(bh, REQ_OP_WRITE | write_flags,
1874 					inode->i_write_hint, wbc,
1875 					bh_end_async_write);
1876 			nr_underway++;
1877 		}
1878 		bh = next;
1879 	} while (bh != head);
1880 	folio_unlock(folio);
1881 	goto done;
1882 }
1883 EXPORT_SYMBOL(__block_write_full_folio);
1884 
1885 /*
1886  * If a folio has any new buffers, zero them out here, and mark them uptodate
1887  * and dirty so they'll be written out (in order to prevent uninitialised
1888  * block data from leaking). And clear the new bit.
1889  */
1890 void folio_zero_new_buffers(struct folio *folio, size_t from, size_t to)
1891 {
1892 	size_t block_start, block_end;
1893 	struct buffer_head *head, *bh;
1894 
1895 	BUG_ON(!folio_test_locked(folio));
1896 	head = folio_buffers(folio);
1897 	if (!head)
1898 		return;
1899 
1900 	bh = head;
1901 	block_start = 0;
1902 	do {
1903 		block_end = block_start + bh->b_size;
1904 
1905 		if (buffer_new(bh)) {
1906 			if (block_end > from && block_start < to) {
1907 				if (!folio_test_uptodate(folio)) {
1908 					size_t start, xend;
1909 
1910 					start = max(from, block_start);
1911 					xend = min(to, block_end);
1912 
1913 					folio_zero_segment(folio, start, xend);
1914 					set_buffer_uptodate(bh);
1915 				}
1916 
1917 				clear_buffer_new(bh);
1918 				mark_buffer_dirty(bh);
1919 			}
1920 		}
1921 
1922 		block_start = block_end;
1923 		bh = bh->b_this_page;
1924 	} while (bh != head);
1925 }
1926 EXPORT_SYMBOL(folio_zero_new_buffers);
1927 
1928 static int
1929 iomap_to_bh(struct inode *inode, sector_t block, struct buffer_head *bh,
1930 		const struct iomap *iomap)
1931 {
1932 	loff_t offset = (loff_t)block << inode->i_blkbits;
1933 
1934 	bh->b_bdev = iomap->bdev;
1935 
1936 	/*
1937 	 * Block points to offset in file we need to map, iomap contains
1938 	 * the offset at which the map starts. If the map ends before the
1939 	 * current block, then do not map the buffer and let the caller
1940 	 * handle it.
1941 	 */
1942 	if (offset >= iomap->offset + iomap->length)
1943 		return -EIO;
1944 
1945 	switch (iomap->type) {
1946 	case IOMAP_HOLE:
1947 		/*
1948 		 * If the buffer is not up to date or beyond the current EOF,
1949 		 * we need to mark it as new to ensure sub-block zeroing is
1950 		 * executed if necessary.
1951 		 */
1952 		if (!buffer_uptodate(bh) ||
1953 		    (offset >= i_size_read(inode)))
1954 			set_buffer_new(bh);
1955 		return 0;
1956 	case IOMAP_DELALLOC:
1957 		if (!buffer_uptodate(bh) ||
1958 		    (offset >= i_size_read(inode)))
1959 			set_buffer_new(bh);
1960 		set_buffer_uptodate(bh);
1961 		set_buffer_mapped(bh);
1962 		set_buffer_delay(bh);
1963 		return 0;
1964 	case IOMAP_UNWRITTEN:
1965 		/*
1966 		 * For unwritten regions, we always need to ensure that regions
1967 		 * in the block we are not writing to are zeroed. Mark the
1968 		 * buffer as new to ensure this.
1969 		 */
1970 		set_buffer_new(bh);
1971 		set_buffer_unwritten(bh);
1972 		fallthrough;
1973 	case IOMAP_MAPPED:
1974 		if ((iomap->flags & IOMAP_F_NEW) ||
1975 		    offset >= i_size_read(inode)) {
1976 			/*
1977 			 * This can happen if truncating the block device races
1978 			 * with the check in the caller as i_size updates on
1979 			 * block devices aren't synchronized by i_rwsem for
1980 			 * block devices.
1981 			 */
1982 			if (S_ISBLK(inode->i_mode))
1983 				return -EIO;
1984 			set_buffer_new(bh);
1985 		}
1986 		bh->b_blocknr = (iomap->addr + offset - iomap->offset) >>
1987 				inode->i_blkbits;
1988 		set_buffer_mapped(bh);
1989 		return 0;
1990 	default:
1991 		WARN_ON_ONCE(1);
1992 		return -EIO;
1993 	}
1994 }
1995 
1996 int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,
1997 		get_block_t *get_block, const struct iomap *iomap)
1998 {
1999 	size_t from = offset_in_folio(folio, pos);
2000 	size_t to = from + len;
2001 	struct inode *inode = folio->mapping->host;
2002 	size_t block_start, block_end;
2003 	sector_t block;
2004 	int err = 0;
2005 	size_t blocksize;
2006 	struct buffer_head *bh, *head, *wait[2], **wait_bh=wait;
2007 
2008 	BUG_ON(!folio_test_locked(folio));
2009 	BUG_ON(to > folio_size(folio));
2010 	BUG_ON(from > to);
2011 
2012 	head = folio_create_buffers(folio, inode, 0);
2013 	blocksize = head->b_size;
2014 	block = div_u64(folio_pos(folio), blocksize);
2015 
2016 	for (bh = head, block_start = 0; bh != head || !block_start;
2017 	    block++, block_start=block_end, bh = bh->b_this_page) {
2018 		block_end = block_start + blocksize;
2019 		if (block_end <= from || block_start >= to) {
2020 			if (folio_test_uptodate(folio)) {
2021 				if (!buffer_uptodate(bh))
2022 					set_buffer_uptodate(bh);
2023 			}
2024 			continue;
2025 		}
2026 		if (buffer_new(bh))
2027 			clear_buffer_new(bh);
2028 		if (!buffer_mapped(bh)) {
2029 			WARN_ON(bh->b_size != blocksize);
2030 			if (get_block)
2031 				err = get_block(inode, block, bh, 1);
2032 			else
2033 				err = iomap_to_bh(inode, block, bh, iomap);
2034 			if (err)
2035 				break;
2036 
2037 			if (buffer_new(bh)) {
2038 				clean_bdev_bh_alias(bh);
2039 				if (folio_test_uptodate(folio)) {
2040 					clear_buffer_new(bh);
2041 					set_buffer_uptodate(bh);
2042 					mark_buffer_dirty(bh);
2043 					continue;
2044 				}
2045 				if (block_end > to || block_start < from)
2046 					folio_zero_segments(folio,
2047 						to, block_end,
2048 						block_start, from);
2049 				continue;
2050 			}
2051 		}
2052 		if (folio_test_uptodate(folio)) {
2053 			if (!buffer_uptodate(bh))
2054 				set_buffer_uptodate(bh);
2055 			continue;
2056 		}
2057 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
2058 		    !buffer_unwritten(bh) &&
2059 		     (block_start < from || block_end > to)) {
2060 			bh_read_nowait(bh, 0);
2061 			*wait_bh++=bh;
2062 		}
2063 	}
2064 	/*
2065 	 * If we issued read requests - let them complete.
2066 	 */
2067 	while(wait_bh > wait) {
2068 		wait_on_buffer(*--wait_bh);
2069 		if (!buffer_uptodate(*wait_bh))
2070 			err = -EIO;
2071 	}
2072 	if (unlikely(err))
2073 		folio_zero_new_buffers(folio, from, to);
2074 	return err;
2075 }
2076 
2077 int __block_write_begin(struct folio *folio, loff_t pos, unsigned len,
2078 		get_block_t *get_block)
2079 {
2080 	return __block_write_begin_int(folio, pos, len, get_block, NULL);
2081 }
2082 EXPORT_SYMBOL(__block_write_begin);
2083 
2084 void block_commit_write(struct folio *folio, size_t from, size_t to)
2085 {
2086 	size_t block_start, block_end;
2087 	bool partial = false;
2088 	bool uptodate = folio_test_uptodate(folio);
2089 	unsigned blocksize;
2090 	struct buffer_head *bh, *head;
2091 
2092 	bh = head = folio_buffers(folio);
2093 	if (!bh)
2094 		return;
2095 	blocksize = bh->b_size;
2096 
2097 	block_start = 0;
2098 	do {
2099 		block_end = block_start + blocksize;
2100 		if (block_end <= from || block_start >= to) {
2101 			if (!buffer_uptodate(bh))
2102 				partial = true;
2103 		} else {
2104 			set_buffer_uptodate(bh);
2105 			mark_buffer_dirty(bh);
2106 		}
2107 		if (buffer_new(bh))
2108 			clear_buffer_new(bh);
2109 
2110 		block_start = block_end;
2111 		if (uptodate && block_start >= to)
2112 			break;
2113 		bh = bh->b_this_page;
2114 	} while (bh != head);
2115 
2116 	/*
2117 	 * If this is a partial write which happened to make all buffers
2118 	 * uptodate then we can optimize away a bogus read_folio() for
2119 	 * the next read(). Here we 'discover' whether the folio went
2120 	 * uptodate as a result of this (potentially partial) write.
2121 	 */
2122 	if (!partial)
2123 		folio_mark_uptodate(folio);
2124 }
2125 EXPORT_SYMBOL(block_commit_write);
2126 
2127 /*
2128  * block_write_begin takes care of the basic task of block allocation and
2129  * bringing partial write blocks uptodate first.
2130  *
2131  * The filesystem needs to handle block truncation upon failure.
2132  */
2133 int block_write_begin(struct address_space *mapping, loff_t pos, unsigned len,
2134 		struct folio **foliop, get_block_t *get_block)
2135 {
2136 	pgoff_t index = pos >> PAGE_SHIFT;
2137 	struct folio *folio;
2138 	int status;
2139 
2140 	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
2141 			mapping_gfp_mask(mapping));
2142 	if (IS_ERR(folio))
2143 		return PTR_ERR(folio);
2144 
2145 	status = __block_write_begin_int(folio, pos, len, get_block, NULL);
2146 	if (unlikely(status)) {
2147 		folio_unlock(folio);
2148 		folio_put(folio);
2149 		folio = NULL;
2150 	}
2151 
2152 	*foliop = folio;
2153 	return status;
2154 }
2155 EXPORT_SYMBOL(block_write_begin);
2156 
2157 int block_write_end(loff_t pos, unsigned len, unsigned copied,
2158 		struct folio *folio)
2159 {
2160 	size_t start = pos - folio_pos(folio);
2161 
2162 	if (unlikely(copied < len)) {
2163 		/*
2164 		 * The buffers that were written will now be uptodate, so
2165 		 * we don't have to worry about a read_folio reading them
2166 		 * and overwriting a partial write. However if we have
2167 		 * encountered a short write and only partially written
2168 		 * into a buffer, it will not be marked uptodate, so a
2169 		 * read_folio might come in and destroy our partial write.
2170 		 *
2171 		 * Do the simplest thing, and just treat any short write to a
2172 		 * non uptodate folio as a zero-length write, and force the
2173 		 * caller to redo the whole thing.
2174 		 */
2175 		if (!folio_test_uptodate(folio))
2176 			copied = 0;
2177 
2178 		folio_zero_new_buffers(folio, start+copied, start+len);
2179 	}
2180 	flush_dcache_folio(folio);
2181 
2182 	/* This could be a short (even 0-length) commit */
2183 	block_commit_write(folio, start, start + copied);
2184 
2185 	return copied;
2186 }
2187 EXPORT_SYMBOL(block_write_end);
2188 
2189 int generic_write_end(const struct kiocb *iocb, struct address_space *mapping,
2190 		      loff_t pos, unsigned len, unsigned copied,
2191 		      struct folio *folio, void *fsdata)
2192 {
2193 	struct inode *inode = mapping->host;
2194 	loff_t old_size = inode->i_size;
2195 	bool i_size_changed = false;
2196 
2197 	copied = block_write_end(pos, len, copied, folio);
2198 
2199 	/*
2200 	 * No need to use i_size_read() here, the i_size cannot change under us
2201 	 * because we hold i_rwsem.
2202 	 *
2203 	 * But it's important to update i_size while still holding folio lock:
2204 	 * page writeout could otherwise come in and zero beyond i_size.
2205 	 */
2206 	if (pos + copied > inode->i_size) {
2207 		i_size_write(inode, pos + copied);
2208 		i_size_changed = true;
2209 	}
2210 
2211 	folio_unlock(folio);
2212 	folio_put(folio);
2213 
2214 	if (old_size < pos)
2215 		pagecache_isize_extended(inode, old_size, pos);
2216 	/*
2217 	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
2218 	 * makes the holding time of folio lock longer. Second, it forces lock
2219 	 * ordering of folio lock and transaction start for journaling
2220 	 * filesystems.
2221 	 */
2222 	if (i_size_changed)
2223 		mark_inode_dirty(inode);
2224 	return copied;
2225 }
2226 EXPORT_SYMBOL(generic_write_end);
2227 
2228 /*
2229  * block_is_partially_uptodate checks whether buffers within a folio are
2230  * uptodate or not.
2231  *
2232  * Returns true if all buffers which correspond to the specified part
2233  * of the folio are uptodate.
2234  */
2235 bool block_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
2236 {
2237 	unsigned block_start, block_end, blocksize;
2238 	unsigned to;
2239 	struct buffer_head *bh, *head;
2240 	bool ret = true;
2241 
2242 	head = folio_buffers(folio);
2243 	if (!head)
2244 		return false;
2245 	blocksize = head->b_size;
2246 	to = min(folio_size(folio) - from, count);
2247 	to = from + to;
2248 	if (from < blocksize && to > folio_size(folio) - blocksize)
2249 		return false;
2250 
2251 	bh = head;
2252 	block_start = 0;
2253 	do {
2254 		block_end = block_start + blocksize;
2255 		if (block_end > from && block_start < to) {
2256 			if (!buffer_uptodate(bh)) {
2257 				ret = false;
2258 				break;
2259 			}
2260 			if (block_end >= to)
2261 				break;
2262 		}
2263 		block_start = block_end;
2264 		bh = bh->b_this_page;
2265 	} while (bh != head);
2266 
2267 	return ret;
2268 }
2269 EXPORT_SYMBOL(block_is_partially_uptodate);
2270 
2271 /*
2272  * Generic "read_folio" function for block devices that have the normal
2273  * get_block functionality. This is most of the block device filesystems.
2274  * Reads the folio asynchronously --- the unlock_buffer() and
2275  * set/clear_buffer_uptodate() functions propagate buffer state into the
2276  * folio once IO has completed.
2277  */
2278 int block_read_full_folio(struct folio *folio, get_block_t *get_block)
2279 {
2280 	struct inode *inode = folio->mapping->host;
2281 	sector_t iblock, lblock;
2282 	struct buffer_head *bh, *head, *prev = NULL;
2283 	size_t blocksize;
2284 	int fully_mapped = 1;
2285 	bool page_error = false;
2286 	loff_t limit = i_size_read(inode);
2287 
2288 	/* This is needed for ext4. */
2289 	if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
2290 		limit = inode->i_sb->s_maxbytes;
2291 
2292 	head = folio_create_buffers(folio, inode, 0);
2293 	blocksize = head->b_size;
2294 
2295 	iblock = div_u64(folio_pos(folio), blocksize);
2296 	lblock = div_u64(limit + blocksize - 1, blocksize);
2297 	bh = head;
2298 
2299 	do {
2300 		if (buffer_uptodate(bh))
2301 			continue;
2302 
2303 		if (!buffer_mapped(bh)) {
2304 			int err = 0;
2305 
2306 			fully_mapped = 0;
2307 			if (iblock < lblock) {
2308 				WARN_ON(bh->b_size != blocksize);
2309 				err = get_block(inode, iblock, bh, 0);
2310 				if (err)
2311 					page_error = true;
2312 			}
2313 			if (!buffer_mapped(bh)) {
2314 				folio_zero_range(folio, bh_offset(bh),
2315 						blocksize);
2316 				if (!err)
2317 					set_buffer_uptodate(bh);
2318 				continue;
2319 			}
2320 			/*
2321 			 * get_block() might have updated the buffer
2322 			 * synchronously
2323 			 */
2324 			if (buffer_uptodate(bh))
2325 				continue;
2326 		}
2327 
2328 		lock_buffer(bh);
2329 		if (buffer_uptodate(bh)) {
2330 			unlock_buffer(bh);
2331 			continue;
2332 		}
2333 
2334 		/*
2335 		 * If a folio's buffers are under async readin
2336 		 * (end_buffer_async_read completion) then there is a
2337 		 * possibility that another thread of control could lock
2338 		 * one of the buffers after it has completed but while
2339 		 * some of the other buffers have not completed.  This
2340 		 * locked buffer would confuse end_buffer_async_read()
2341 		 * into not unlocking the folio.  So the absence of
2342 		 * BH_Async_Read tells end_buffer_async_read() that this
2343 		 * buffer is not under async I/O.
2344 		 *
2345 		 * The folio is unlocked when it has no locked
2346 		 * buffer_async buffers left.
2347 		 *
2348 		 * The folio lock prevents anyone starting new async
2349 		 * I/O reads into any of the buffers.
2350 		 *
2351 		 * The writeback flag is used to prevent simultaneous
2352 		 * writeout of the same folio.
2353 		 *
2354 		 * The folio lock prevents anyone from starting writeback
2355 		 * of a folio which is under read I/O (the writeback
2356 		 * flag is only ever set on a locked folio).
2357 		 */
2358 		set_buffer_async_read(bh);
2359 		if (prev)
2360 			bh_submit(prev, REQ_OP_READ, bh_end_async_read);
2361 		prev = bh;
2362 	} while (iblock++, (bh = bh->b_this_page) != head);
2363 
2364 	if (fully_mapped)
2365 		folio_set_mappedtodisk(folio);
2366 
2367 	/*
2368 	 * All buffers are uptodate or get_block() returned an error
2369 	 * when trying to map them - we must finish the read because
2370 	 * end_buffer_async_read() will never be called on any buffer
2371 	 * in this folio.
2372 	 */
2373 	if (prev)
2374 		bh_submit(prev, REQ_OP_READ, bh_end_async_read);
2375 	else
2376 		folio_end_read(folio, !page_error);
2377 
2378 	return 0;
2379 }
2380 EXPORT_SYMBOL(block_read_full_folio);
2381 
2382 /* utility function for filesystems that need to do work on expanding
2383  * truncates.  Uses filesystem pagecache writes to allow the filesystem to
2384  * deal with the hole.
2385  */
2386 int generic_cont_expand_simple(struct inode *inode, loff_t size)
2387 {
2388 	struct address_space *mapping = inode->i_mapping;
2389 	const struct address_space_operations *aops = mapping->a_ops;
2390 	struct folio *folio;
2391 	void *fsdata = NULL;
2392 	int err;
2393 
2394 	err = inode_newsize_ok(inode, size);
2395 	if (err)
2396 		goto out;
2397 
2398 	err = aops->write_begin(NULL, mapping, size, 0, &folio, &fsdata);
2399 	if (err)
2400 		goto out;
2401 
2402 	err = aops->write_end(NULL, mapping, size, 0, 0, folio, fsdata);
2403 	BUG_ON(err > 0);
2404 
2405 out:
2406 	return err;
2407 }
2408 EXPORT_SYMBOL(generic_cont_expand_simple);
2409 
2410 static int cont_expand_zero(const struct kiocb *iocb,
2411 			    struct address_space *mapping,
2412 			    loff_t pos, loff_t *bytes)
2413 {
2414 	struct inode *inode = mapping->host;
2415 	const struct address_space_operations *aops = mapping->a_ops;
2416 	unsigned int blocksize = i_blocksize(inode);
2417 	struct folio *folio;
2418 	void *fsdata = NULL;
2419 	pgoff_t index, curidx;
2420 	loff_t curpos;
2421 	unsigned zerofrom, offset, len;
2422 	int err = 0;
2423 
2424 	index = pos >> PAGE_SHIFT;
2425 	offset = pos & ~PAGE_MASK;
2426 
2427 	while (index > (curidx = (curpos = *bytes)>>PAGE_SHIFT)) {
2428 		zerofrom = curpos & ~PAGE_MASK;
2429 		if (zerofrom & (blocksize-1)) {
2430 			*bytes |= (blocksize-1);
2431 			(*bytes)++;
2432 		}
2433 		len = PAGE_SIZE - zerofrom;
2434 
2435 		err = aops->write_begin(iocb, mapping, curpos, len,
2436 					    &folio, &fsdata);
2437 		if (err)
2438 			goto out;
2439 		folio_zero_range(folio, offset_in_folio(folio, curpos), len);
2440 		err = aops->write_end(iocb, mapping, curpos, len, len,
2441 						folio, fsdata);
2442 		if (err < 0)
2443 			goto out;
2444 		BUG_ON(err != len);
2445 		err = 0;
2446 
2447 		balance_dirty_pages_ratelimited(mapping);
2448 
2449 		if (fatal_signal_pending(current)) {
2450 			err = -EINTR;
2451 			goto out;
2452 		}
2453 	}
2454 
2455 	/* folio crosses the boundary, find the boundary offset */
2456 	if (index == curidx) {
2457 		zerofrom = curpos & ~PAGE_MASK;
2458 		/* if we will expand the thing last block will be filled */
2459 		if (offset <= zerofrom) {
2460 			goto out;
2461 		}
2462 		if (zerofrom & (blocksize-1)) {
2463 			*bytes |= (blocksize-1);
2464 			(*bytes)++;
2465 		}
2466 		len = offset - zerofrom;
2467 
2468 		err = aops->write_begin(iocb, mapping, curpos, len,
2469 					    &folio, &fsdata);
2470 		if (err)
2471 			goto out;
2472 		folio_zero_range(folio, offset_in_folio(folio, curpos), len);
2473 		err = aops->write_end(iocb, mapping, curpos, len, len,
2474 						folio, fsdata);
2475 		if (err < 0)
2476 			goto out;
2477 		BUG_ON(err != len);
2478 		err = 0;
2479 	}
2480 out:
2481 	return err;
2482 }
2483 
2484 /*
2485  * For moronic filesystems that do not allow holes in file.
2486  * We may have to extend the file.
2487  */
2488 int cont_write_begin(const struct kiocb *iocb, struct address_space *mapping,
2489 		     loff_t pos, unsigned len, struct folio **foliop,
2490 		     void **fsdata, get_block_t *get_block, loff_t *bytes)
2491 {
2492 	struct inode *inode = mapping->host;
2493 	unsigned int blocksize = i_blocksize(inode);
2494 	unsigned int zerofrom;
2495 	int err;
2496 
2497 	err = cont_expand_zero(iocb, mapping, pos, bytes);
2498 	if (err)
2499 		return err;
2500 
2501 	zerofrom = *bytes & ~PAGE_MASK;
2502 	if (pos+len > *bytes && zerofrom & (blocksize-1)) {
2503 		*bytes |= (blocksize-1);
2504 		(*bytes)++;
2505 	}
2506 
2507 	return block_write_begin(mapping, pos, len, foliop, get_block);
2508 }
2509 EXPORT_SYMBOL(cont_write_begin);
2510 
2511 /*
2512  * block_page_mkwrite() is not allowed to change the file size as it gets
2513  * called from a page fault handler when a folio is first dirtied. Hence we must
2514  * be careful to check for EOF conditions here. We set the folio up correctly
2515  * for a written folio which means we get ENOSPC checking when writing into
2516  * holes and correct delalloc and unwritten extent mapping on filesystems that
2517  * support these features.
2518  *
2519  * We are not allowed to take the i_rwsem here so we have to play games to
2520  * protect against truncate races as the folio could now be beyond EOF.  Because
2521  * truncate writes the inode size before removing folios, once we have the
2522  * folio lock we can determine safely if the folio is beyond EOF. If it is not
2523  * beyond EOF, then the folio is guaranteed safe against truncation until we
2524  * unlock the folio.
2525  *
2526  * Direct callers of this function should protect against filesystem freezing
2527  * using sb_start_pagefault() - sb_end_pagefault() functions.
2528  */
2529 int block_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf,
2530 			 get_block_t get_block)
2531 {
2532 	struct folio *folio = page_folio(vmf->page);
2533 	struct inode *inode = file_inode(vma->vm_file);
2534 	unsigned long end;
2535 	loff_t size;
2536 	int ret;
2537 
2538 	folio_lock(folio);
2539 	size = i_size_read(inode);
2540 	if ((folio->mapping != inode->i_mapping) ||
2541 	    (folio_pos(folio) >= size)) {
2542 		/* We overload EFAULT to mean folio got truncated */
2543 		ret = -EFAULT;
2544 		goto out_unlock;
2545 	}
2546 
2547 	end = folio_size(folio);
2548 	/* folio is wholly or partially inside EOF */
2549 	if (folio_pos(folio) + end > size)
2550 		end = size - folio_pos(folio);
2551 
2552 	ret = __block_write_begin_int(folio, 0, end, get_block, NULL);
2553 	if (unlikely(ret))
2554 		goto out_unlock;
2555 
2556 	block_commit_write(folio, 0, end);
2557 
2558 	folio_mark_dirty(folio);
2559 	folio_wait_stable(folio);
2560 	return 0;
2561 out_unlock:
2562 	folio_unlock(folio);
2563 	return ret;
2564 }
2565 EXPORT_SYMBOL(block_page_mkwrite);
2566 
2567 int block_truncate_page(struct address_space *mapping,
2568 			loff_t from, get_block_t *get_block)
2569 {
2570 	pgoff_t index = from >> PAGE_SHIFT;
2571 	unsigned blocksize;
2572 	sector_t iblock;
2573 	size_t offset, length, pos;
2574 	struct inode *inode = mapping->host;
2575 	struct folio *folio;
2576 	struct buffer_head *bh;
2577 	int err = 0;
2578 
2579 	blocksize = i_blocksize(inode);
2580 	length = from & (blocksize - 1);
2581 
2582 	/* Block boundary? Nothing to do */
2583 	if (!length)
2584 		return 0;
2585 
2586 	length = blocksize - length;
2587 	iblock = ((loff_t)index * PAGE_SIZE) >> inode->i_blkbits;
2588 
2589 	folio = filemap_grab_folio(mapping, index);
2590 	if (IS_ERR(folio))
2591 		return PTR_ERR(folio);
2592 
2593 	bh = folio_buffers(folio);
2594 	if (!bh)
2595 		bh = create_empty_buffers(folio, blocksize, 0);
2596 
2597 	/* Find the buffer that contains "offset" */
2598 	offset = offset_in_folio(folio, from);
2599 	pos = blocksize;
2600 	while (offset >= pos) {
2601 		bh = bh->b_this_page;
2602 		iblock++;
2603 		pos += blocksize;
2604 	}
2605 
2606 	if (!buffer_mapped(bh)) {
2607 		WARN_ON(bh->b_size != blocksize);
2608 		err = get_block(inode, iblock, bh, 0);
2609 		if (err)
2610 			goto unlock;
2611 		/* unmapped? It's a hole - nothing to do */
2612 		if (!buffer_mapped(bh))
2613 			goto unlock;
2614 	}
2615 
2616 	/* Ok, it's mapped. Make sure it's up-to-date */
2617 	if (folio_test_uptodate(folio))
2618 		set_buffer_uptodate(bh);
2619 
2620 	if (!buffer_uptodate(bh) && !buffer_delay(bh) && !buffer_unwritten(bh)) {
2621 		err = bh_read(bh, 0);
2622 		/* Uhhuh. Read error. Complain and punt. */
2623 		if (err < 0)
2624 			goto unlock;
2625 	}
2626 
2627 	folio_zero_range(folio, offset, length);
2628 	mark_buffer_dirty(bh);
2629 
2630 unlock:
2631 	folio_unlock(folio);
2632 	folio_put(folio);
2633 
2634 	return err;
2635 }
2636 EXPORT_SYMBOL(block_truncate_page);
2637 
2638 /*
2639  * The generic write folio function for buffer-backed address_spaces
2640  */
2641 int block_write_full_folio(struct folio *folio, struct writeback_control *wbc,
2642 		void *get_block)
2643 {
2644 	struct inode * const inode = folio->mapping->host;
2645 	loff_t i_size = i_size_read(inode);
2646 
2647 	/* Is the folio fully inside i_size? */
2648 	if (folio_next_pos(folio) <= i_size)
2649 		return __block_write_full_folio(inode, folio, get_block, wbc);
2650 
2651 	/* Is the folio fully outside i_size? (truncate in progress) */
2652 	if (folio_pos(folio) >= i_size) {
2653 		folio_unlock(folio);
2654 		return 0; /* don't care */
2655 	}
2656 
2657 	/*
2658 	 * The folio straddles i_size.  It must be zeroed out on each and every
2659 	 * writeback invocation because it may be mmapped.  "A file is mapped
2660 	 * in multiples of the page size.  For a file that is not a multiple of
2661 	 * the page size, the remaining memory is zeroed when mapped, and
2662 	 * writes to that region are not written out to the file."
2663 	 */
2664 	folio_zero_segment(folio, offset_in_folio(folio, i_size),
2665 			folio_size(folio));
2666 	return __block_write_full_folio(inode, folio, get_block, wbc);
2667 }
2668 
2669 sector_t generic_block_bmap(struct address_space *mapping, sector_t block,
2670 			    get_block_t *get_block)
2671 {
2672 	struct inode *inode = mapping->host;
2673 	struct buffer_head tmp = {
2674 		.b_size = i_blocksize(inode),
2675 	};
2676 
2677 	get_block(inode, block, &tmp, 0);
2678 	return tmp.b_blocknr;
2679 }
2680 EXPORT_SYMBOL(generic_block_bmap);
2681 
2682 void write_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
2683 {
2684 	lock_buffer(bh);
2685 	if (!test_clear_buffer_dirty(bh)) {
2686 		unlock_buffer(bh);
2687 		return;
2688 	}
2689 	bh_submit(bh, REQ_OP_WRITE | op_flags, bh_end_write);
2690 }
2691 EXPORT_SYMBOL(write_dirty_buffer);
2692 
2693 /*
2694  * For a data-integrity writeout, we need to wait upon any in-progress I/O
2695  * and then start new I/O and then wait upon it.  The caller must have a ref on
2696  * the buffer_head.
2697  */
2698 int __sync_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
2699 {
2700 	WARN_ON(atomic_read(&bh->b_count) < 1);
2701 	lock_buffer(bh);
2702 	if (test_clear_buffer_dirty(bh)) {
2703 		/*
2704 		 * The bh should be mapped, but it might not be if the
2705 		 * device was hot-removed. Not much we can do but fail the I/O.
2706 		 */
2707 		if (!buffer_mapped(bh)) {
2708 			unlock_buffer(bh);
2709 			return -EIO;
2710 		}
2711 
2712 		bh_submit(bh, REQ_OP_WRITE | op_flags, bh_end_write);
2713 		wait_on_buffer(bh);
2714 		if (buffer_write_io_error(bh))
2715 			return -EIO;
2716 	} else {
2717 		unlock_buffer(bh);
2718 	}
2719 	return 0;
2720 }
2721 EXPORT_SYMBOL(__sync_dirty_buffer);
2722 
2723 int sync_dirty_buffer(struct buffer_head *bh)
2724 {
2725 	return __sync_dirty_buffer(bh, REQ_SYNC);
2726 }
2727 EXPORT_SYMBOL(sync_dirty_buffer);
2728 
2729 static inline int buffer_busy(struct buffer_head *bh)
2730 {
2731 	return atomic_read(&bh->b_count) |
2732 		(bh->b_state & ((1 << BH_Dirty) | (1 << BH_Lock)));
2733 }
2734 
2735 static bool
2736 drop_buffers(struct folio *folio, struct buffer_head **buffers_to_free)
2737 {
2738 	struct buffer_head *head = folio_buffers(folio);
2739 	struct buffer_head *bh;
2740 
2741 	bh = head;
2742 	do {
2743 		if (buffer_busy(bh))
2744 			goto failed;
2745 		bh = bh->b_this_page;
2746 	} while (bh != head);
2747 
2748 	do {
2749 		struct buffer_head *next = bh->b_this_page;
2750 
2751 		remove_assoc_queue(bh);
2752 		bh = next;
2753 	} while (bh != head);
2754 	*buffers_to_free = head;
2755 	folio_detach_private(folio);
2756 	return true;
2757 failed:
2758 	return false;
2759 }
2760 
2761 /**
2762  * try_to_free_buffers - Release buffers attached to this folio.
2763  * @folio: The folio.
2764  *
2765  * If any buffers are in use (dirty, under writeback, elevated refcount),
2766  * no buffers will be freed.
2767  *
2768  * If the folio is dirty but all the buffers are clean then we need to
2769  * be sure to mark the folio clean as well.  This is because the folio
2770  * may be against a block device, and a later reattachment of buffers
2771  * to a dirty folio will set *all* buffers dirty.  Which would corrupt
2772  * filesystem data on the same device.
2773  *
2774  * The same applies to regular filesystem folios: if all the buffers are
2775  * clean then we set the folio clean and proceed.  To do that, we require
2776  * total exclusion from block_dirty_folio().  That is obtained with
2777  * i_private_lock.
2778  *
2779  * Exclusion against try_to_free_buffers may be obtained by either
2780  * locking the folio or by holding its mapping's i_private_lock.
2781  *
2782  * Context: Process context.  @folio must be locked.  Will not sleep.
2783  * Return: true if all buffers attached to this folio were freed.
2784  */
2785 bool try_to_free_buffers(struct folio *folio)
2786 {
2787 	struct address_space * const mapping = folio->mapping;
2788 	struct buffer_head *buffers_to_free = NULL;
2789 	bool ret = 0;
2790 
2791 	BUG_ON(!folio_test_locked(folio));
2792 	if (folio_test_writeback(folio))
2793 		return false;
2794 
2795 	/* Misconfigured folio check */
2796 	if (WARN_ON_ONCE(!folio_buffers(folio)))
2797 		return true;
2798 
2799 	if (mapping == NULL) {		/* can this still happen? */
2800 		ret = drop_buffers(folio, &buffers_to_free);
2801 		goto out;
2802 	}
2803 
2804 	spin_lock(&mapping->i_private_lock);
2805 	ret = drop_buffers(folio, &buffers_to_free);
2806 
2807 	/*
2808 	 * If the filesystem writes its buffers by hand (eg ext3)
2809 	 * then we can have clean buffers against a dirty folio.  We
2810 	 * clean the folio here; otherwise the VM will never notice
2811 	 * that the filesystem did any IO at all.
2812 	 *
2813 	 * Also, during truncate, discard_buffer will have marked all
2814 	 * the folio's buffers clean.  We discover that here and clean
2815 	 * the folio also.
2816 	 *
2817 	 * i_private_lock must be held over this entire operation in order
2818 	 * to synchronise against block_dirty_folio and prevent the
2819 	 * dirty bit from being lost.
2820 	 */
2821 	if (ret)
2822 		folio_cancel_dirty(folio);
2823 	spin_unlock(&mapping->i_private_lock);
2824 out:
2825 	if (buffers_to_free) {
2826 		struct buffer_head *bh = buffers_to_free;
2827 
2828 		do {
2829 			struct buffer_head *next = bh->b_this_page;
2830 			free_buffer_head(bh);
2831 			bh = next;
2832 		} while (bh != buffers_to_free);
2833 	}
2834 	return ret;
2835 }
2836 EXPORT_SYMBOL(try_to_free_buffers);
2837 
2838 /*
2839  * Buffer-head allocation
2840  */
2841 static struct kmem_cache *bh_cachep __ro_after_init;
2842 
2843 /*
2844  * Once the number of bh's in the machine exceeds this level, we start
2845  * stripping them in writeback.
2846  */
2847 static unsigned long max_buffer_heads __ro_after_init;
2848 
2849 int buffer_heads_over_limit;
2850 
2851 struct bh_accounting {
2852 	int nr;			/* Number of live bh's */
2853 	int ratelimit;		/* Limit cacheline bouncing */
2854 };
2855 
2856 static DEFINE_PER_CPU(struct bh_accounting, bh_accounting) = {0, 0};
2857 
2858 static void recalc_bh_state(void)
2859 {
2860 	int i;
2861 	int tot = 0;
2862 
2863 	if (__this_cpu_inc_return(bh_accounting.ratelimit) - 1 < 4096)
2864 		return;
2865 	__this_cpu_write(bh_accounting.ratelimit, 0);
2866 	for_each_online_cpu(i)
2867 		tot += per_cpu(bh_accounting, i).nr;
2868 	buffer_heads_over_limit = (tot > max_buffer_heads);
2869 }
2870 
2871 struct buffer_head *alloc_buffer_head(gfp_t gfp_flags)
2872 {
2873 	struct buffer_head *ret = kmem_cache_zalloc(bh_cachep, gfp_flags);
2874 	if (ret) {
2875 		INIT_LIST_HEAD(&ret->b_assoc_buffers);
2876 		spin_lock_init(&ret->b_uptodate_lock);
2877 		preempt_disable();
2878 		__this_cpu_inc(bh_accounting.nr);
2879 		recalc_bh_state();
2880 		preempt_enable();
2881 	}
2882 	return ret;
2883 }
2884 EXPORT_SYMBOL(alloc_buffer_head);
2885 
2886 void free_buffer_head(struct buffer_head *bh)
2887 {
2888 	BUG_ON(!list_empty(&bh->b_assoc_buffers));
2889 	kmem_cache_free(bh_cachep, bh);
2890 	preempt_disable();
2891 	__this_cpu_dec(bh_accounting.nr);
2892 	recalc_bh_state();
2893 	preempt_enable();
2894 }
2895 EXPORT_SYMBOL(free_buffer_head);
2896 
2897 static int buffer_exit_cpu_dead(unsigned int cpu)
2898 {
2899 	int i;
2900 	struct bh_lru *b = &per_cpu(bh_lrus, cpu);
2901 
2902 	for (i = 0; i < BH_LRU_SIZE; i++) {
2903 		brelse(b->bhs[i]);
2904 		b->bhs[i] = NULL;
2905 	}
2906 	this_cpu_add(bh_accounting.nr, per_cpu(bh_accounting, cpu).nr);
2907 	per_cpu(bh_accounting, cpu).nr = 0;
2908 	return 0;
2909 }
2910 
2911 /**
2912  * bh_uptodate_or_lock - Test whether the buffer is uptodate
2913  * @bh: struct buffer_head
2914  *
2915  * Return true if the buffer is up-to-date and false,
2916  * with the buffer locked, if not.
2917  */
2918 int bh_uptodate_or_lock(struct buffer_head *bh)
2919 {
2920 	if (!buffer_uptodate(bh)) {
2921 		lock_buffer(bh);
2922 		if (!buffer_uptodate(bh))
2923 			return 0;
2924 		unlock_buffer(bh);
2925 	}
2926 	return 1;
2927 }
2928 EXPORT_SYMBOL(bh_uptodate_or_lock);
2929 
2930 /**
2931  * __bh_read - Submit read for a locked buffer
2932  * @bh: struct buffer_head
2933  * @op_flags: appending REQ_OP_* flags besides REQ_OP_READ
2934  * @wait: wait until reading finish
2935  *
2936  * Returns zero on success or don't wait, and -EIO on error.
2937  */
2938 int __bh_read(struct buffer_head *bh, blk_opf_t op_flags, bool wait)
2939 {
2940 	int ret = 0;
2941 
2942 	BUG_ON(!buffer_locked(bh));
2943 
2944 	bh_submit(bh, REQ_OP_READ | op_flags, bh_end_read);
2945 	if (wait) {
2946 		wait_on_buffer(bh);
2947 		if (!buffer_uptodate(bh))
2948 			ret = -EIO;
2949 	}
2950 	return ret;
2951 }
2952 EXPORT_SYMBOL(__bh_read);
2953 
2954 /**
2955  * __bh_read_batch - Submit read for a batch of unlocked buffers
2956  * @nr: entry number of the buffer batch
2957  * @bhs: a batch of struct buffer_head
2958  * @op_flags: appending REQ_OP_* flags besides REQ_OP_READ
2959  * @force_lock: force to get a lock on the buffer if set, otherwise drops any
2960  *              buffer that cannot lock.
2961  *
2962  * Returns zero on success or don't wait, and -EIO on error.
2963  */
2964 void __bh_read_batch(int nr, struct buffer_head *bhs[],
2965 		     blk_opf_t op_flags, bool force_lock)
2966 {
2967 	int i;
2968 
2969 	for (i = 0; i < nr; i++) {
2970 		struct buffer_head *bh = bhs[i];
2971 
2972 		if (buffer_uptodate(bh))
2973 			continue;
2974 
2975 		if (force_lock)
2976 			lock_buffer(bh);
2977 		else
2978 			if (!trylock_buffer(bh))
2979 				continue;
2980 
2981 		if (buffer_uptodate(bh)) {
2982 			unlock_buffer(bh);
2983 			continue;
2984 		}
2985 
2986 		bh_submit(bh, REQ_OP_READ | op_flags, bh_end_read);
2987 	}
2988 }
2989 EXPORT_SYMBOL(__bh_read_batch);
2990 
2991 void __init buffer_init(void)
2992 {
2993 	unsigned long nrpages;
2994 	int ret;
2995 
2996 	bh_cachep = KMEM_CACHE(buffer_head,
2997 				SLAB_RECLAIM_ACCOUNT|SLAB_PANIC);
2998 	/*
2999 	 * Limit the bh occupancy to 10% of ZONE_NORMAL
3000 	 */
3001 	nrpages = (nr_free_buffer_pages() * 10) / 100;
3002 	max_buffer_heads = nrpages * (PAGE_SIZE / sizeof(struct buffer_head));
3003 	ret = cpuhp_setup_state_nocalls(CPUHP_FS_BUFF_DEAD, "fs/buffer:dead",
3004 					NULL, buffer_exit_cpu_dead);
3005 	WARN_ON(ret < 0);
3006 }
3007