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