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