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