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