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