OSDN Git Service

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