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