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