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