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