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