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