USB: usbtmc: fix switch statment
[linux-2.6/mini2440.git] / fs / buffer.c
blob4eb899274fc4f6e9c7014096db5de7525906c163
1 /*
2 * linux/fs/buffer.c
4 * Copyright (C) 1991, 1992, 2002 Linus Torvalds
5 */
7 /*
8 * Start bdflush() with kernel_thread not syscall - Paul Gortmaker, 12/95
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
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
16 * Added 32k buffer block sizes - these are required older ARM systems. - RMK
18 * async buffer flushing, 1999 Andrea Arcangeli <andrea@suse.de>
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/module.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>
45 static int fsync_buffers_list(spinlock_t *lock, struct list_head *list);
47 #define BH_ENTRY(list) list_entry((list), struct buffer_head, b_assoc_buffers)
49 inline void
50 init_buffer(struct buffer_head *bh, bh_end_io_t *handler, void *private)
52 bh->b_end_io = handler;
53 bh->b_private = private;
56 static int sync_buffer(void *word)
58 struct block_device *bd;
59 struct buffer_head *bh
60 = container_of(word, struct buffer_head, b_state);
62 smp_mb();
63 bd = bh->b_bdev;
64 if (bd)
65 blk_run_address_space(bd->bd_inode->i_mapping);
66 io_schedule();
67 return 0;
70 void __lock_buffer(struct buffer_head *bh)
72 wait_on_bit_lock(&bh->b_state, BH_Lock, sync_buffer,
73 TASK_UNINTERRUPTIBLE);
75 EXPORT_SYMBOL(__lock_buffer);
77 void unlock_buffer(struct buffer_head *bh)
79 clear_bit_unlock(BH_Lock, &bh->b_state);
80 smp_mb__after_clear_bit();
81 wake_up_bit(&bh->b_state, BH_Lock);
85 * Block until a buffer comes unlocked. This doesn't stop it
86 * from becoming locked again - you have to lock it yourself
87 * if you want to preserve its state.
89 void __wait_on_buffer(struct buffer_head * bh)
91 wait_on_bit(&bh->b_state, BH_Lock, sync_buffer, TASK_UNINTERRUPTIBLE);
94 static void
95 __clear_page_buffers(struct page *page)
97 ClearPagePrivate(page);
98 set_page_private(page, 0);
99 page_cache_release(page);
103 static int quiet_error(struct buffer_head *bh)
105 if (!test_bit(BH_Quiet, &bh->b_state) && printk_ratelimit())
106 return 0;
107 return 1;
111 static void buffer_io_error(struct buffer_head *bh)
113 char b[BDEVNAME_SIZE];
114 printk(KERN_ERR "Buffer I/O error on device %s, logical block %Lu\n",
115 bdevname(bh->b_bdev, b),
116 (unsigned long long)bh->b_blocknr);
120 * End-of-IO handler helper function which does not touch the bh after
121 * unlocking it.
122 * Note: unlock_buffer() sort-of does touch the bh after unlocking it, but
123 * a race there is benign: unlock_buffer() only use the bh's address for
124 * hashing after unlocking the buffer, so it doesn't actually touch the bh
125 * itself.
127 static void __end_buffer_read_notouch(struct buffer_head *bh, int uptodate)
129 if (uptodate) {
130 set_buffer_uptodate(bh);
131 } else {
132 /* This happens, due to failed READA attempts. */
133 clear_buffer_uptodate(bh);
135 unlock_buffer(bh);
139 * Default synchronous end-of-IO handler.. Just mark it up-to-date and
140 * unlock the buffer. This is what ll_rw_block uses too.
142 void end_buffer_read_sync(struct buffer_head *bh, int uptodate)
144 __end_buffer_read_notouch(bh, uptodate);
145 put_bh(bh);
148 void end_buffer_write_sync(struct buffer_head *bh, int uptodate)
150 char b[BDEVNAME_SIZE];
152 if (uptodate) {
153 set_buffer_uptodate(bh);
154 } else {
155 if (!buffer_eopnotsupp(bh) && !quiet_error(bh)) {
156 buffer_io_error(bh);
157 printk(KERN_WARNING "lost page write due to "
158 "I/O error on %s\n",
159 bdevname(bh->b_bdev, b));
161 set_buffer_write_io_error(bh);
162 clear_buffer_uptodate(bh);
164 unlock_buffer(bh);
165 put_bh(bh);
169 * Write out and wait upon all the dirty data associated with a block
170 * device via its mapping. Does not take the superblock lock.
172 int sync_blockdev(struct block_device *bdev)
174 int ret = 0;
176 if (bdev)
177 ret = filemap_write_and_wait(bdev->bd_inode->i_mapping);
178 return ret;
180 EXPORT_SYMBOL(sync_blockdev);
183 * Write out and wait upon all dirty data associated with this
184 * device. Filesystem data as well as the underlying block
185 * device. Takes the superblock lock.
187 int fsync_bdev(struct block_device *bdev)
189 struct super_block *sb = get_super(bdev);
190 if (sb) {
191 int res = fsync_super(sb);
192 drop_super(sb);
193 return res;
195 return sync_blockdev(bdev);
199 * freeze_bdev -- lock a filesystem and force it into a consistent state
200 * @bdev: blockdevice to lock
202 * This takes the block device bd_mount_sem to make sure no new mounts
203 * happen on bdev until thaw_bdev() is called.
204 * If a superblock is found on this device, we take the s_umount semaphore
205 * on it to make sure nobody unmounts until the snapshot creation is done.
206 * The reference counter (bd_fsfreeze_count) guarantees that only the last
207 * unfreeze process can unfreeze the frozen filesystem actually when multiple
208 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
209 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
210 * actually.
212 struct super_block *freeze_bdev(struct block_device *bdev)
214 struct super_block *sb;
215 int error = 0;
217 mutex_lock(&bdev->bd_fsfreeze_mutex);
218 if (bdev->bd_fsfreeze_count > 0) {
219 bdev->bd_fsfreeze_count++;
220 sb = get_super(bdev);
221 mutex_unlock(&bdev->bd_fsfreeze_mutex);
222 return sb;
224 bdev->bd_fsfreeze_count++;
226 down(&bdev->bd_mount_sem);
227 sb = get_super(bdev);
228 if (sb && !(sb->s_flags & MS_RDONLY)) {
229 sb->s_frozen = SB_FREEZE_WRITE;
230 smp_wmb();
232 __fsync_super(sb);
234 sb->s_frozen = SB_FREEZE_TRANS;
235 smp_wmb();
237 sync_blockdev(sb->s_bdev);
239 if (sb->s_op->freeze_fs) {
240 error = sb->s_op->freeze_fs(sb);
241 if (error) {
242 printk(KERN_ERR
243 "VFS:Filesystem freeze failed\n");
244 sb->s_frozen = SB_UNFROZEN;
245 drop_super(sb);
246 up(&bdev->bd_mount_sem);
247 bdev->bd_fsfreeze_count--;
248 mutex_unlock(&bdev->bd_fsfreeze_mutex);
249 return ERR_PTR(error);
254 sync_blockdev(bdev);
255 mutex_unlock(&bdev->bd_fsfreeze_mutex);
257 return sb; /* thaw_bdev releases s->s_umount and bd_mount_sem */
259 EXPORT_SYMBOL(freeze_bdev);
262 * thaw_bdev -- unlock filesystem
263 * @bdev: blockdevice to unlock
264 * @sb: associated superblock
266 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
268 int thaw_bdev(struct block_device *bdev, struct super_block *sb)
270 int error = 0;
272 mutex_lock(&bdev->bd_fsfreeze_mutex);
273 if (!bdev->bd_fsfreeze_count) {
274 mutex_unlock(&bdev->bd_fsfreeze_mutex);
275 return -EINVAL;
278 bdev->bd_fsfreeze_count--;
279 if (bdev->bd_fsfreeze_count > 0) {
280 if (sb)
281 drop_super(sb);
282 mutex_unlock(&bdev->bd_fsfreeze_mutex);
283 return 0;
286 if (sb) {
287 BUG_ON(sb->s_bdev != bdev);
288 if (!(sb->s_flags & MS_RDONLY)) {
289 if (sb->s_op->unfreeze_fs) {
290 error = sb->s_op->unfreeze_fs(sb);
291 if (error) {
292 printk(KERN_ERR
293 "VFS:Filesystem thaw failed\n");
294 sb->s_frozen = SB_FREEZE_TRANS;
295 bdev->bd_fsfreeze_count++;
296 mutex_unlock(&bdev->bd_fsfreeze_mutex);
297 return error;
300 sb->s_frozen = SB_UNFROZEN;
301 smp_wmb();
302 wake_up(&sb->s_wait_unfrozen);
304 drop_super(sb);
307 up(&bdev->bd_mount_sem);
308 mutex_unlock(&bdev->bd_fsfreeze_mutex);
309 return 0;
311 EXPORT_SYMBOL(thaw_bdev);
314 * Various filesystems appear to want __find_get_block to be non-blocking.
315 * But it's the page lock which protects the buffers. To get around this,
316 * we get exclusion from try_to_free_buffers with the blockdev mapping's
317 * private_lock.
319 * Hack idea: for the blockdev mapping, i_bufferlist_lock contention
320 * may be quite high. This code could TryLock the page, and if that
321 * succeeds, there is no need to take private_lock. (But if
322 * private_lock is contended then so is mapping->tree_lock).
324 static struct buffer_head *
325 __find_get_block_slow(struct block_device *bdev, sector_t block)
327 struct inode *bd_inode = bdev->bd_inode;
328 struct address_space *bd_mapping = bd_inode->i_mapping;
329 struct buffer_head *ret = NULL;
330 pgoff_t index;
331 struct buffer_head *bh;
332 struct buffer_head *head;
333 struct page *page;
334 int all_mapped = 1;
336 index = block >> (PAGE_CACHE_SHIFT - bd_inode->i_blkbits);
337 page = find_get_page(bd_mapping, index);
338 if (!page)
339 goto out;
341 spin_lock(&bd_mapping->private_lock);
342 if (!page_has_buffers(page))
343 goto out_unlock;
344 head = page_buffers(page);
345 bh = head;
346 do {
347 if (bh->b_blocknr == block) {
348 ret = bh;
349 get_bh(bh);
350 goto out_unlock;
352 if (!buffer_mapped(bh))
353 all_mapped = 0;
354 bh = bh->b_this_page;
355 } while (bh != head);
357 /* we might be here because some of the buffers on this page are
358 * not mapped. This is due to various races between
359 * file io on the block device and getblk. It gets dealt with
360 * elsewhere, don't buffer_error if we had some unmapped buffers
362 if (all_mapped) {
363 printk("__find_get_block_slow() failed. "
364 "block=%llu, b_blocknr=%llu\n",
365 (unsigned long long)block,
366 (unsigned long long)bh->b_blocknr);
367 printk("b_state=0x%08lx, b_size=%zu\n",
368 bh->b_state, bh->b_size);
369 printk("device blocksize: %d\n", 1 << bd_inode->i_blkbits);
371 out_unlock:
372 spin_unlock(&bd_mapping->private_lock);
373 page_cache_release(page);
374 out:
375 return ret;
378 /* If invalidate_buffers() will trash dirty buffers, it means some kind
379 of fs corruption is going on. Trashing dirty data always imply losing
380 information that was supposed to be just stored on the physical layer
381 by the user.
383 Thus invalidate_buffers in general usage is not allwowed to trash
384 dirty buffers. For example ioctl(FLSBLKBUF) expects dirty data to
385 be preserved. These buffers are simply skipped.
387 We also skip buffers which are still in use. For example this can
388 happen if a userspace program is reading the block device.
390 NOTE: In the case where the user removed a removable-media-disk even if
391 there's still dirty data not synced on disk (due a bug in the device driver
392 or due an error of the user), by not destroying the dirty buffers we could
393 generate corruption also on the next media inserted, thus a parameter is
394 necessary to handle this case in the most safe way possible (trying
395 to not corrupt also the new disk inserted with the data belonging to
396 the old now corrupted disk). Also for the ramdisk the natural thing
397 to do in order to release the ramdisk memory is to destroy dirty buffers.
399 These are two special cases. Normal usage imply the device driver
400 to issue a sync on the device (without waiting I/O completion) and
401 then an invalidate_buffers call that doesn't trash dirty buffers.
403 For handling cache coherency with the blkdev pagecache the 'update' case
404 is been introduced. It is needed to re-read from disk any pinned
405 buffer. NOTE: re-reading from disk is destructive so we can do it only
406 when we assume nobody is changing the buffercache under our I/O and when
407 we think the disk contains more recent information than the buffercache.
408 The update == 1 pass marks the buffers we need to update, the update == 2
409 pass does the actual I/O. */
410 void invalidate_bdev(struct block_device *bdev)
412 struct address_space *mapping = bdev->bd_inode->i_mapping;
414 if (mapping->nrpages == 0)
415 return;
417 invalidate_bh_lrus();
418 invalidate_mapping_pages(mapping, 0, -1);
422 * Kick pdflush then try to free up some ZONE_NORMAL memory.
424 static void free_more_memory(void)
426 struct zone *zone;
427 int nid;
429 wakeup_pdflush(1024);
430 yield();
432 for_each_online_node(nid) {
433 (void)first_zones_zonelist(node_zonelist(nid, GFP_NOFS),
434 gfp_zone(GFP_NOFS), NULL,
435 &zone);
436 if (zone)
437 try_to_free_pages(node_zonelist(nid, GFP_NOFS), 0,
438 GFP_NOFS);
443 * I/O completion handler for block_read_full_page() - pages
444 * which come unlocked at the end of I/O.
446 static void end_buffer_async_read(struct buffer_head *bh, int uptodate)
448 unsigned long flags;
449 struct buffer_head *first;
450 struct buffer_head *tmp;
451 struct page *page;
452 int page_uptodate = 1;
454 BUG_ON(!buffer_async_read(bh));
456 page = bh->b_page;
457 if (uptodate) {
458 set_buffer_uptodate(bh);
459 } else {
460 clear_buffer_uptodate(bh);
461 if (!quiet_error(bh))
462 buffer_io_error(bh);
463 SetPageError(page);
467 * Be _very_ careful from here on. Bad things can happen if
468 * two buffer heads end IO at almost the same time and both
469 * decide that the page is now completely done.
471 first = page_buffers(page);
472 local_irq_save(flags);
473 bit_spin_lock(BH_Uptodate_Lock, &first->b_state);
474 clear_buffer_async_read(bh);
475 unlock_buffer(bh);
476 tmp = bh;
477 do {
478 if (!buffer_uptodate(tmp))
479 page_uptodate = 0;
480 if (buffer_async_read(tmp)) {
481 BUG_ON(!buffer_locked(tmp));
482 goto still_busy;
484 tmp = tmp->b_this_page;
485 } while (tmp != bh);
486 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
487 local_irq_restore(flags);
490 * If none of the buffers had errors and they are all
491 * uptodate then we can set the page uptodate.
493 if (page_uptodate && !PageError(page))
494 SetPageUptodate(page);
495 unlock_page(page);
496 return;
498 still_busy:
499 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
500 local_irq_restore(flags);
501 return;
505 * Completion handler for block_write_full_page() - pages which are unlocked
506 * during I/O, and which have PageWriteback cleared upon I/O completion.
508 static void end_buffer_async_write(struct buffer_head *bh, int uptodate)
510 char b[BDEVNAME_SIZE];
511 unsigned long flags;
512 struct buffer_head *first;
513 struct buffer_head *tmp;
514 struct page *page;
516 BUG_ON(!buffer_async_write(bh));
518 page = bh->b_page;
519 if (uptodate) {
520 set_buffer_uptodate(bh);
521 } else {
522 if (!quiet_error(bh)) {
523 buffer_io_error(bh);
524 printk(KERN_WARNING "lost page write due to "
525 "I/O error on %s\n",
526 bdevname(bh->b_bdev, b));
528 set_bit(AS_EIO, &page->mapping->flags);
529 set_buffer_write_io_error(bh);
530 clear_buffer_uptodate(bh);
531 SetPageError(page);
534 first = page_buffers(page);
535 local_irq_save(flags);
536 bit_spin_lock(BH_Uptodate_Lock, &first->b_state);
538 clear_buffer_async_write(bh);
539 unlock_buffer(bh);
540 tmp = bh->b_this_page;
541 while (tmp != bh) {
542 if (buffer_async_write(tmp)) {
543 BUG_ON(!buffer_locked(tmp));
544 goto still_busy;
546 tmp = tmp->b_this_page;
548 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
549 local_irq_restore(flags);
550 end_page_writeback(page);
551 return;
553 still_busy:
554 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
555 local_irq_restore(flags);
556 return;
560 * If a page's buffers are under async readin (end_buffer_async_read
561 * completion) then there is a possibility that another thread of
562 * control could lock one of the buffers after it has completed
563 * but while some of the other buffers have not completed. This
564 * locked buffer would confuse end_buffer_async_read() into not unlocking
565 * the page. So the absence of BH_Async_Read tells end_buffer_async_read()
566 * that this buffer is not under async I/O.
568 * The page comes unlocked when it has no locked buffer_async buffers
569 * left.
571 * PageLocked prevents anyone starting new async I/O reads any of
572 * the buffers.
574 * PageWriteback is used to prevent simultaneous writeout of the same
575 * page.
577 * PageLocked prevents anyone from starting writeback of a page which is
578 * under read I/O (PageWriteback is only ever set against a locked page).
580 static void mark_buffer_async_read(struct buffer_head *bh)
582 bh->b_end_io = end_buffer_async_read;
583 set_buffer_async_read(bh);
586 void mark_buffer_async_write(struct buffer_head *bh)
588 bh->b_end_io = end_buffer_async_write;
589 set_buffer_async_write(bh);
591 EXPORT_SYMBOL(mark_buffer_async_write);
595 * fs/buffer.c contains helper functions for buffer-backed address space's
596 * fsync functions. A common requirement for buffer-based filesystems is
597 * that certain data from the backing blockdev needs to be written out for
598 * a successful fsync(). For example, ext2 indirect blocks need to be
599 * written back and waited upon before fsync() returns.
601 * The functions mark_buffer_inode_dirty(), fsync_inode_buffers(),
602 * inode_has_buffers() and invalidate_inode_buffers() are provided for the
603 * management of a list of dependent buffers at ->i_mapping->private_list.
605 * Locking is a little subtle: try_to_free_buffers() will remove buffers
606 * from their controlling inode's queue when they are being freed. But
607 * try_to_free_buffers() will be operating against the *blockdev* mapping
608 * at the time, not against the S_ISREG file which depends on those buffers.
609 * So the locking for private_list is via the private_lock in the address_space
610 * which backs the buffers. Which is different from the address_space
611 * against which the buffers are listed. So for a particular address_space,
612 * mapping->private_lock does *not* protect mapping->private_list! In fact,
613 * mapping->private_list will always be protected by the backing blockdev's
614 * ->private_lock.
616 * Which introduces a requirement: all buffers on an address_space's
617 * ->private_list must be from the same address_space: the blockdev's.
619 * address_spaces which do not place buffers at ->private_list via these
620 * utility functions are free to use private_lock and private_list for
621 * whatever they want. The only requirement is that list_empty(private_list)
622 * be true at clear_inode() time.
624 * FIXME: clear_inode should not call invalidate_inode_buffers(). The
625 * filesystems should do that. invalidate_inode_buffers() should just go
626 * BUG_ON(!list_empty).
628 * FIXME: mark_buffer_dirty_inode() is a data-plane operation. It should
629 * take an address_space, not an inode. And it should be called
630 * mark_buffer_dirty_fsync() to clearly define why those buffers are being
631 * queued up.
633 * FIXME: mark_buffer_dirty_inode() doesn't need to add the buffer to the
634 * list if it is already on a list. Because if the buffer is on a list,
635 * it *must* already be on the right one. If not, the filesystem is being
636 * silly. This will save a ton of locking. But first we have to ensure
637 * that buffers are taken *off* the old inode's list when they are freed
638 * (presumably in truncate). That requires careful auditing of all
639 * filesystems (do it inside bforget()). It could also be done by bringing
640 * b_inode back.
644 * The buffer's backing address_space's private_lock must be held
646 static void __remove_assoc_queue(struct buffer_head *bh)
648 list_del_init(&bh->b_assoc_buffers);
649 WARN_ON(!bh->b_assoc_map);
650 if (buffer_write_io_error(bh))
651 set_bit(AS_EIO, &bh->b_assoc_map->flags);
652 bh->b_assoc_map = NULL;
655 int inode_has_buffers(struct inode *inode)
657 return !list_empty(&inode->i_data.private_list);
661 * osync is designed to support O_SYNC io. It waits synchronously for
662 * all already-submitted IO to complete, but does not queue any new
663 * writes to the disk.
665 * To do O_SYNC writes, just queue the buffer writes with ll_rw_block as
666 * you dirty the buffers, and then use osync_inode_buffers to wait for
667 * completion. Any other dirty buffers which are not yet queued for
668 * write will not be flushed to disk by the osync.
670 static int osync_buffers_list(spinlock_t *lock, struct list_head *list)
672 struct buffer_head *bh;
673 struct list_head *p;
674 int err = 0;
676 spin_lock(lock);
677 repeat:
678 list_for_each_prev(p, list) {
679 bh = BH_ENTRY(p);
680 if (buffer_locked(bh)) {
681 get_bh(bh);
682 spin_unlock(lock);
683 wait_on_buffer(bh);
684 if (!buffer_uptodate(bh))
685 err = -EIO;
686 brelse(bh);
687 spin_lock(lock);
688 goto repeat;
691 spin_unlock(lock);
692 return err;
696 * sync_mapping_buffers - write out & wait upon a mapping's "associated" buffers
697 * @mapping: the mapping which wants those buffers written
699 * Starts I/O against the buffers at mapping->private_list, and waits upon
700 * that I/O.
702 * Basically, this is a convenience function for fsync().
703 * @mapping is a file or directory which needs those buffers to be written for
704 * a successful fsync().
706 int sync_mapping_buffers(struct address_space *mapping)
708 struct address_space *buffer_mapping = mapping->assoc_mapping;
710 if (buffer_mapping == NULL || list_empty(&mapping->private_list))
711 return 0;
713 return fsync_buffers_list(&buffer_mapping->private_lock,
714 &mapping->private_list);
716 EXPORT_SYMBOL(sync_mapping_buffers);
719 * Called when we've recently written block `bblock', and it is known that
720 * `bblock' was for a buffer_boundary() buffer. This means that the block at
721 * `bblock + 1' is probably a dirty indirect block. Hunt it down and, if it's
722 * dirty, schedule it for IO. So that indirects merge nicely with their data.
724 void write_boundary_block(struct block_device *bdev,
725 sector_t bblock, unsigned blocksize)
727 struct buffer_head *bh = __find_get_block(bdev, bblock + 1, blocksize);
728 if (bh) {
729 if (buffer_dirty(bh))
730 ll_rw_block(WRITE, 1, &bh);
731 put_bh(bh);
735 void mark_buffer_dirty_inode(struct buffer_head *bh, struct inode *inode)
737 struct address_space *mapping = inode->i_mapping;
738 struct address_space *buffer_mapping = bh->b_page->mapping;
740 mark_buffer_dirty(bh);
741 if (!mapping->assoc_mapping) {
742 mapping->assoc_mapping = buffer_mapping;
743 } else {
744 BUG_ON(mapping->assoc_mapping != buffer_mapping);
746 if (!bh->b_assoc_map) {
747 spin_lock(&buffer_mapping->private_lock);
748 list_move_tail(&bh->b_assoc_buffers,
749 &mapping->private_list);
750 bh->b_assoc_map = mapping;
751 spin_unlock(&buffer_mapping->private_lock);
754 EXPORT_SYMBOL(mark_buffer_dirty_inode);
757 * Mark the page dirty, and set it dirty in the radix tree, and mark the inode
758 * dirty.
760 * If warn is true, then emit a warning if the page is not uptodate and has
761 * not been truncated.
763 static void __set_page_dirty(struct page *page,
764 struct address_space *mapping, int warn)
766 spin_lock_irq(&mapping->tree_lock);
767 if (page->mapping) { /* Race with truncate? */
768 WARN_ON_ONCE(warn && !PageUptodate(page));
770 if (mapping_cap_account_dirty(mapping)) {
771 __inc_zone_page_state(page, NR_FILE_DIRTY);
772 __inc_bdi_stat(mapping->backing_dev_info,
773 BDI_RECLAIMABLE);
774 task_dirty_inc(current);
775 task_io_account_write(PAGE_CACHE_SIZE);
777 radix_tree_tag_set(&mapping->page_tree,
778 page_index(page), PAGECACHE_TAG_DIRTY);
780 spin_unlock_irq(&mapping->tree_lock);
781 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
785 * Add a page to the dirty page list.
787 * It is a sad fact of life that this function is called from several places
788 * deeply under spinlocking. It may not sleep.
790 * If the page has buffers, the uptodate buffers are set dirty, to preserve
791 * dirty-state coherency between the page and the buffers. It the page does
792 * not have buffers then when they are later attached they will all be set
793 * dirty.
795 * The buffers are dirtied before the page is dirtied. There's a small race
796 * window in which a writepage caller may see the page cleanness but not the
797 * buffer dirtiness. That's fine. If this code were to set the page dirty
798 * before the buffers, a concurrent writepage caller could clear the page dirty
799 * bit, see a bunch of clean buffers and we'd end up with dirty buffers/clean
800 * page on the dirty page list.
802 * We use private_lock to lock against try_to_free_buffers while using the
803 * page's buffer list. Also use this to protect against clean buffers being
804 * added to the page after it was set dirty.
806 * FIXME: may need to call ->reservepage here as well. That's rather up to the
807 * address_space though.
809 int __set_page_dirty_buffers(struct page *page)
811 int newly_dirty;
812 struct address_space *mapping = page_mapping(page);
814 if (unlikely(!mapping))
815 return !TestSetPageDirty(page);
817 spin_lock(&mapping->private_lock);
818 if (page_has_buffers(page)) {
819 struct buffer_head *head = page_buffers(page);
820 struct buffer_head *bh = head;
822 do {
823 set_buffer_dirty(bh);
824 bh = bh->b_this_page;
825 } while (bh != head);
827 newly_dirty = !TestSetPageDirty(page);
828 spin_unlock(&mapping->private_lock);
830 if (newly_dirty)
831 __set_page_dirty(page, mapping, 1);
832 return newly_dirty;
834 EXPORT_SYMBOL(__set_page_dirty_buffers);
837 * Write out and wait upon a list of buffers.
839 * We have conflicting pressures: we want to make sure that all
840 * initially dirty buffers get waited on, but that any subsequently
841 * dirtied buffers don't. After all, we don't want fsync to last
842 * forever if somebody is actively writing to the file.
844 * Do this in two main stages: first we copy dirty buffers to a
845 * temporary inode list, queueing the writes as we go. Then we clean
846 * up, waiting for those writes to complete.
848 * During this second stage, any subsequent updates to the file may end
849 * up refiling the buffer on the original inode's dirty list again, so
850 * there is a chance we will end up with a buffer queued for write but
851 * not yet completed on that list. So, as a final cleanup we go through
852 * the osync code to catch these locked, dirty buffers without requeuing
853 * any newly dirty buffers for write.
855 static int fsync_buffers_list(spinlock_t *lock, struct list_head *list)
857 struct buffer_head *bh;
858 struct list_head tmp;
859 struct address_space *mapping;
860 int err = 0, err2;
862 INIT_LIST_HEAD(&tmp);
864 spin_lock(lock);
865 while (!list_empty(list)) {
866 bh = BH_ENTRY(list->next);
867 mapping = bh->b_assoc_map;
868 __remove_assoc_queue(bh);
869 /* Avoid race with mark_buffer_dirty_inode() which does
870 * a lockless check and we rely on seeing the dirty bit */
871 smp_mb();
872 if (buffer_dirty(bh) || buffer_locked(bh)) {
873 list_add(&bh->b_assoc_buffers, &tmp);
874 bh->b_assoc_map = mapping;
875 if (buffer_dirty(bh)) {
876 get_bh(bh);
877 spin_unlock(lock);
879 * Ensure any pending I/O completes so that
880 * ll_rw_block() actually writes the current
881 * contents - it is a noop if I/O is still in
882 * flight on potentially older contents.
884 ll_rw_block(SWRITE_SYNC, 1, &bh);
885 brelse(bh);
886 spin_lock(lock);
891 while (!list_empty(&tmp)) {
892 bh = BH_ENTRY(tmp.prev);
893 get_bh(bh);
894 mapping = bh->b_assoc_map;
895 __remove_assoc_queue(bh);
896 /* Avoid race with mark_buffer_dirty_inode() which does
897 * a lockless check and we rely on seeing the dirty bit */
898 smp_mb();
899 if (buffer_dirty(bh)) {
900 list_add(&bh->b_assoc_buffers,
901 &mapping->private_list);
902 bh->b_assoc_map = mapping;
904 spin_unlock(lock);
905 wait_on_buffer(bh);
906 if (!buffer_uptodate(bh))
907 err = -EIO;
908 brelse(bh);
909 spin_lock(lock);
912 spin_unlock(lock);
913 err2 = osync_buffers_list(lock, list);
914 if (err)
915 return err;
916 else
917 return err2;
921 * Invalidate any and all dirty buffers on a given inode. We are
922 * probably unmounting the fs, but that doesn't mean we have already
923 * done a sync(). Just drop the buffers from the inode list.
925 * NOTE: we take the inode's blockdev's mapping's private_lock. Which
926 * assumes that all the buffers are against the blockdev. Not true
927 * for reiserfs.
929 void invalidate_inode_buffers(struct inode *inode)
931 if (inode_has_buffers(inode)) {
932 struct address_space *mapping = &inode->i_data;
933 struct list_head *list = &mapping->private_list;
934 struct address_space *buffer_mapping = mapping->assoc_mapping;
936 spin_lock(&buffer_mapping->private_lock);
937 while (!list_empty(list))
938 __remove_assoc_queue(BH_ENTRY(list->next));
939 spin_unlock(&buffer_mapping->private_lock);
942 EXPORT_SYMBOL(invalidate_inode_buffers);
945 * Remove any clean buffers from the inode's buffer list. This is called
946 * when we're trying to free the inode itself. Those buffers can pin it.
948 * Returns true if all buffers were removed.
950 int remove_inode_buffers(struct inode *inode)
952 int ret = 1;
954 if (inode_has_buffers(inode)) {
955 struct address_space *mapping = &inode->i_data;
956 struct list_head *list = &mapping->private_list;
957 struct address_space *buffer_mapping = mapping->assoc_mapping;
959 spin_lock(&buffer_mapping->private_lock);
960 while (!list_empty(list)) {
961 struct buffer_head *bh = BH_ENTRY(list->next);
962 if (buffer_dirty(bh)) {
963 ret = 0;
964 break;
966 __remove_assoc_queue(bh);
968 spin_unlock(&buffer_mapping->private_lock);
970 return ret;
974 * Create the appropriate buffers when given a page for data area and
975 * the size of each buffer.. Use the bh->b_this_page linked list to
976 * follow the buffers created. Return NULL if unable to create more
977 * buffers.
979 * The retry flag is used to differentiate async IO (paging, swapping)
980 * which may not fail from ordinary buffer allocations.
982 struct buffer_head *alloc_page_buffers(struct page *page, unsigned long size,
983 int retry)
985 struct buffer_head *bh, *head;
986 long offset;
988 try_again:
989 head = NULL;
990 offset = PAGE_SIZE;
991 while ((offset -= size) >= 0) {
992 bh = alloc_buffer_head(GFP_NOFS);
993 if (!bh)
994 goto no_grow;
996 bh->b_bdev = NULL;
997 bh->b_this_page = head;
998 bh->b_blocknr = -1;
999 head = bh;
1001 bh->b_state = 0;
1002 atomic_set(&bh->b_count, 0);
1003 bh->b_private = NULL;
1004 bh->b_size = size;
1006 /* Link the buffer to its page */
1007 set_bh_page(bh, page, offset);
1009 init_buffer(bh, NULL, NULL);
1011 return head;
1013 * In case anything failed, we just free everything we got.
1015 no_grow:
1016 if (head) {
1017 do {
1018 bh = head;
1019 head = head->b_this_page;
1020 free_buffer_head(bh);
1021 } while (head);
1025 * Return failure for non-async IO requests. Async IO requests
1026 * are not allowed to fail, so we have to wait until buffer heads
1027 * become available. But we don't want tasks sleeping with
1028 * partially complete buffers, so all were released above.
1030 if (!retry)
1031 return NULL;
1033 /* We're _really_ low on memory. Now we just
1034 * wait for old buffer heads to become free due to
1035 * finishing IO. Since this is an async request and
1036 * the reserve list is empty, we're sure there are
1037 * async buffer heads in use.
1039 free_more_memory();
1040 goto try_again;
1042 EXPORT_SYMBOL_GPL(alloc_page_buffers);
1044 static inline void
1045 link_dev_buffers(struct page *page, struct buffer_head *head)
1047 struct buffer_head *bh, *tail;
1049 bh = head;
1050 do {
1051 tail = bh;
1052 bh = bh->b_this_page;
1053 } while (bh);
1054 tail->b_this_page = head;
1055 attach_page_buffers(page, head);
1059 * Initialise the state of a blockdev page's buffers.
1061 static void
1062 init_page_buffers(struct page *page, struct block_device *bdev,
1063 sector_t block, int size)
1065 struct buffer_head *head = page_buffers(page);
1066 struct buffer_head *bh = head;
1067 int uptodate = PageUptodate(page);
1069 do {
1070 if (!buffer_mapped(bh)) {
1071 init_buffer(bh, NULL, NULL);
1072 bh->b_bdev = bdev;
1073 bh->b_blocknr = block;
1074 if (uptodate)
1075 set_buffer_uptodate(bh);
1076 set_buffer_mapped(bh);
1078 block++;
1079 bh = bh->b_this_page;
1080 } while (bh != head);
1084 * Create the page-cache page that contains the requested block.
1086 * This is user purely for blockdev mappings.
1088 static struct page *
1089 grow_dev_page(struct block_device *bdev, sector_t block,
1090 pgoff_t index, int size)
1092 struct inode *inode = bdev->bd_inode;
1093 struct page *page;
1094 struct buffer_head *bh;
1096 page = find_or_create_page(inode->i_mapping, index,
1097 (mapping_gfp_mask(inode->i_mapping) & ~__GFP_FS)|__GFP_MOVABLE);
1098 if (!page)
1099 return NULL;
1101 BUG_ON(!PageLocked(page));
1103 if (page_has_buffers(page)) {
1104 bh = page_buffers(page);
1105 if (bh->b_size == size) {
1106 init_page_buffers(page, bdev, block, size);
1107 return page;
1109 if (!try_to_free_buffers(page))
1110 goto failed;
1114 * Allocate some buffers for this page
1116 bh = alloc_page_buffers(page, size, 0);
1117 if (!bh)
1118 goto failed;
1121 * Link the page to the buffers and initialise them. Take the
1122 * lock to be atomic wrt __find_get_block(), which does not
1123 * run under the page lock.
1125 spin_lock(&inode->i_mapping->private_lock);
1126 link_dev_buffers(page, bh);
1127 init_page_buffers(page, bdev, block, size);
1128 spin_unlock(&inode->i_mapping->private_lock);
1129 return page;
1131 failed:
1132 BUG();
1133 unlock_page(page);
1134 page_cache_release(page);
1135 return NULL;
1139 * Create buffers for the specified block device block's page. If
1140 * that page was dirty, the buffers are set dirty also.
1142 static int
1143 grow_buffers(struct block_device *bdev, sector_t block, int size)
1145 struct page *page;
1146 pgoff_t index;
1147 int sizebits;
1149 sizebits = -1;
1150 do {
1151 sizebits++;
1152 } while ((size << sizebits) < PAGE_SIZE);
1154 index = block >> sizebits;
1157 * Check for a block which wants to lie outside our maximum possible
1158 * pagecache index. (this comparison is done using sector_t types).
1160 if (unlikely(index != block >> sizebits)) {
1161 char b[BDEVNAME_SIZE];
1163 printk(KERN_ERR "%s: requested out-of-range block %llu for "
1164 "device %s\n",
1165 __func__, (unsigned long long)block,
1166 bdevname(bdev, b));
1167 return -EIO;
1169 block = index << sizebits;
1170 /* Create a page with the proper size buffers.. */
1171 page = grow_dev_page(bdev, block, index, size);
1172 if (!page)
1173 return 0;
1174 unlock_page(page);
1175 page_cache_release(page);
1176 return 1;
1179 static struct buffer_head *
1180 __getblk_slow(struct block_device *bdev, sector_t block, int size)
1182 /* Size must be multiple of hard sectorsize */
1183 if (unlikely(size & (bdev_hardsect_size(bdev)-1) ||
1184 (size < 512 || size > PAGE_SIZE))) {
1185 printk(KERN_ERR "getblk(): invalid block size %d requested\n",
1186 size);
1187 printk(KERN_ERR "hardsect size: %d\n",
1188 bdev_hardsect_size(bdev));
1190 dump_stack();
1191 return NULL;
1194 for (;;) {
1195 struct buffer_head * bh;
1196 int ret;
1198 bh = __find_get_block(bdev, block, size);
1199 if (bh)
1200 return bh;
1202 ret = grow_buffers(bdev, block, size);
1203 if (ret < 0)
1204 return NULL;
1205 if (ret == 0)
1206 free_more_memory();
1211 * The relationship between dirty buffers and dirty pages:
1213 * Whenever a page has any dirty buffers, the page's dirty bit is set, and
1214 * the page is tagged dirty in its radix tree.
1216 * At all times, the dirtiness of the buffers represents the dirtiness of
1217 * subsections of the page. If the page has buffers, the page dirty bit is
1218 * merely a hint about the true dirty state.
1220 * When a page is set dirty in its entirety, all its buffers are marked dirty
1221 * (if the page has buffers).
1223 * When a buffer is marked dirty, its page is dirtied, but the page's other
1224 * buffers are not.
1226 * Also. When blockdev buffers are explicitly read with bread(), they
1227 * individually become uptodate. But their backing page remains not
1228 * uptodate - even if all of its buffers are uptodate. A subsequent
1229 * block_read_full_page() against that page will discover all the uptodate
1230 * buffers, will set the page uptodate and will perform no I/O.
1234 * mark_buffer_dirty - mark a buffer_head as needing writeout
1235 * @bh: the buffer_head to mark dirty
1237 * mark_buffer_dirty() will set the dirty bit against the buffer, then set its
1238 * backing page dirty, then tag the page as dirty in its address_space's radix
1239 * tree and then attach the address_space's inode to its superblock's dirty
1240 * inode list.
1242 * mark_buffer_dirty() is atomic. It takes bh->b_page->mapping->private_lock,
1243 * mapping->tree_lock and the global inode_lock.
1245 void mark_buffer_dirty(struct buffer_head *bh)
1247 WARN_ON_ONCE(!buffer_uptodate(bh));
1250 * Very *carefully* optimize the it-is-already-dirty case.
1252 * Don't let the final "is it dirty" escape to before we
1253 * perhaps modified the buffer.
1255 if (buffer_dirty(bh)) {
1256 smp_mb();
1257 if (buffer_dirty(bh))
1258 return;
1261 if (!test_set_buffer_dirty(bh)) {
1262 struct page *page = bh->b_page;
1263 if (!TestSetPageDirty(page))
1264 __set_page_dirty(page, page_mapping(page), 0);
1269 * Decrement a buffer_head's reference count. If all buffers against a page
1270 * have zero reference count, are clean and unlocked, and if the page is clean
1271 * and unlocked then try_to_free_buffers() may strip the buffers from the page
1272 * in preparation for freeing it (sometimes, rarely, buffers are removed from
1273 * a page but it ends up not being freed, and buffers may later be reattached).
1275 void __brelse(struct buffer_head * buf)
1277 if (atomic_read(&buf->b_count)) {
1278 put_bh(buf);
1279 return;
1281 WARN(1, KERN_ERR "VFS: brelse: Trying to free free buffer\n");
1285 * bforget() is like brelse(), except it discards any
1286 * potentially dirty data.
1288 void __bforget(struct buffer_head *bh)
1290 clear_buffer_dirty(bh);
1291 if (bh->b_assoc_map) {
1292 struct address_space *buffer_mapping = bh->b_page->mapping;
1294 spin_lock(&buffer_mapping->private_lock);
1295 list_del_init(&bh->b_assoc_buffers);
1296 bh->b_assoc_map = NULL;
1297 spin_unlock(&buffer_mapping->private_lock);
1299 __brelse(bh);
1302 static struct buffer_head *__bread_slow(struct buffer_head *bh)
1304 lock_buffer(bh);
1305 if (buffer_uptodate(bh)) {
1306 unlock_buffer(bh);
1307 return bh;
1308 } else {
1309 get_bh(bh);
1310 bh->b_end_io = end_buffer_read_sync;
1311 submit_bh(READ, bh);
1312 wait_on_buffer(bh);
1313 if (buffer_uptodate(bh))
1314 return bh;
1316 brelse(bh);
1317 return NULL;
1321 * Per-cpu buffer LRU implementation. To reduce the cost of __find_get_block().
1322 * The bhs[] array is sorted - newest buffer is at bhs[0]. Buffers have their
1323 * refcount elevated by one when they're in an LRU. A buffer can only appear
1324 * once in a particular CPU's LRU. A single buffer can be present in multiple
1325 * CPU's LRUs at the same time.
1327 * This is a transparent caching front-end to sb_bread(), sb_getblk() and
1328 * sb_find_get_block().
1330 * The LRUs themselves only need locking against invalidate_bh_lrus. We use
1331 * a local interrupt disable for that.
1334 #define BH_LRU_SIZE 8
1336 struct bh_lru {
1337 struct buffer_head *bhs[BH_LRU_SIZE];
1340 static DEFINE_PER_CPU(struct bh_lru, bh_lrus) = {{ NULL }};
1342 #ifdef CONFIG_SMP
1343 #define bh_lru_lock() local_irq_disable()
1344 #define bh_lru_unlock() local_irq_enable()
1345 #else
1346 #define bh_lru_lock() preempt_disable()
1347 #define bh_lru_unlock() preempt_enable()
1348 #endif
1350 static inline void check_irqs_on(void)
1352 #ifdef irqs_disabled
1353 BUG_ON(irqs_disabled());
1354 #endif
1358 * The LRU management algorithm is dopey-but-simple. Sorry.
1360 static void bh_lru_install(struct buffer_head *bh)
1362 struct buffer_head *evictee = NULL;
1363 struct bh_lru *lru;
1365 check_irqs_on();
1366 bh_lru_lock();
1367 lru = &__get_cpu_var(bh_lrus);
1368 if (lru->bhs[0] != bh) {
1369 struct buffer_head *bhs[BH_LRU_SIZE];
1370 int in;
1371 int out = 0;
1373 get_bh(bh);
1374 bhs[out++] = bh;
1375 for (in = 0; in < BH_LRU_SIZE; in++) {
1376 struct buffer_head *bh2 = lru->bhs[in];
1378 if (bh2 == bh) {
1379 __brelse(bh2);
1380 } else {
1381 if (out >= BH_LRU_SIZE) {
1382 BUG_ON(evictee != NULL);
1383 evictee = bh2;
1384 } else {
1385 bhs[out++] = bh2;
1389 while (out < BH_LRU_SIZE)
1390 bhs[out++] = NULL;
1391 memcpy(lru->bhs, bhs, sizeof(bhs));
1393 bh_lru_unlock();
1395 if (evictee)
1396 __brelse(evictee);
1400 * Look up the bh in this cpu's LRU. If it's there, move it to the head.
1402 static struct buffer_head *
1403 lookup_bh_lru(struct block_device *bdev, sector_t block, unsigned size)
1405 struct buffer_head *ret = NULL;
1406 struct bh_lru *lru;
1407 unsigned int i;
1409 check_irqs_on();
1410 bh_lru_lock();
1411 lru = &__get_cpu_var(bh_lrus);
1412 for (i = 0; i < BH_LRU_SIZE; i++) {
1413 struct buffer_head *bh = lru->bhs[i];
1415 if (bh && bh->b_bdev == bdev &&
1416 bh->b_blocknr == block && bh->b_size == size) {
1417 if (i) {
1418 while (i) {
1419 lru->bhs[i] = lru->bhs[i - 1];
1420 i--;
1422 lru->bhs[0] = bh;
1424 get_bh(bh);
1425 ret = bh;
1426 break;
1429 bh_lru_unlock();
1430 return ret;
1434 * Perform a pagecache lookup for the matching buffer. If it's there, refresh
1435 * it in the LRU and mark it as accessed. If it is not present then return
1436 * NULL
1438 struct buffer_head *
1439 __find_get_block(struct block_device *bdev, sector_t block, unsigned size)
1441 struct buffer_head *bh = lookup_bh_lru(bdev, block, size);
1443 if (bh == NULL) {
1444 bh = __find_get_block_slow(bdev, block);
1445 if (bh)
1446 bh_lru_install(bh);
1448 if (bh)
1449 touch_buffer(bh);
1450 return bh;
1452 EXPORT_SYMBOL(__find_get_block);
1455 * __getblk will locate (and, if necessary, create) the buffer_head
1456 * which corresponds to the passed block_device, block and size. The
1457 * returned buffer has its reference count incremented.
1459 * __getblk() cannot fail - it just keeps trying. If you pass it an
1460 * illegal block number, __getblk() will happily return a buffer_head
1461 * which represents the non-existent block. Very weird.
1463 * __getblk() will lock up the machine if grow_dev_page's try_to_free_buffers()
1464 * attempt is failing. FIXME, perhaps?
1466 struct buffer_head *
1467 __getblk(struct block_device *bdev, sector_t block, unsigned size)
1469 struct buffer_head *bh = __find_get_block(bdev, block, size);
1471 might_sleep();
1472 if (bh == NULL)
1473 bh = __getblk_slow(bdev, block, size);
1474 return bh;
1476 EXPORT_SYMBOL(__getblk);
1479 * Do async read-ahead on a buffer..
1481 void __breadahead(struct block_device *bdev, sector_t block, unsigned size)
1483 struct buffer_head *bh = __getblk(bdev, block, size);
1484 if (likely(bh)) {
1485 ll_rw_block(READA, 1, &bh);
1486 brelse(bh);
1489 EXPORT_SYMBOL(__breadahead);
1492 * __bread() - reads a specified block and returns the bh
1493 * @bdev: the block_device to read from
1494 * @block: number of block
1495 * @size: size (in bytes) to read
1497 * Reads a specified block, and returns buffer head that contains it.
1498 * It returns NULL if the block was unreadable.
1500 struct buffer_head *
1501 __bread(struct block_device *bdev, sector_t block, unsigned size)
1503 struct buffer_head *bh = __getblk(bdev, block, size);
1505 if (likely(bh) && !buffer_uptodate(bh))
1506 bh = __bread_slow(bh);
1507 return bh;
1509 EXPORT_SYMBOL(__bread);
1512 * invalidate_bh_lrus() is called rarely - but not only at unmount.
1513 * This doesn't race because it runs in each cpu either in irq
1514 * or with preempt disabled.
1516 static void invalidate_bh_lru(void *arg)
1518 struct bh_lru *b = &get_cpu_var(bh_lrus);
1519 int i;
1521 for (i = 0; i < BH_LRU_SIZE; i++) {
1522 brelse(b->bhs[i]);
1523 b->bhs[i] = NULL;
1525 put_cpu_var(bh_lrus);
1528 void invalidate_bh_lrus(void)
1530 on_each_cpu(invalidate_bh_lru, NULL, 1);
1532 EXPORT_SYMBOL_GPL(invalidate_bh_lrus);
1534 void set_bh_page(struct buffer_head *bh,
1535 struct page *page, unsigned long offset)
1537 bh->b_page = page;
1538 BUG_ON(offset >= PAGE_SIZE);
1539 if (PageHighMem(page))
1541 * This catches illegal uses and preserves the offset:
1543 bh->b_data = (char *)(0 + offset);
1544 else
1545 bh->b_data = page_address(page) + offset;
1547 EXPORT_SYMBOL(set_bh_page);
1550 * Called when truncating a buffer on a page completely.
1552 static void discard_buffer(struct buffer_head * bh)
1554 lock_buffer(bh);
1555 clear_buffer_dirty(bh);
1556 bh->b_bdev = NULL;
1557 clear_buffer_mapped(bh);
1558 clear_buffer_req(bh);
1559 clear_buffer_new(bh);
1560 clear_buffer_delay(bh);
1561 clear_buffer_unwritten(bh);
1562 unlock_buffer(bh);
1566 * block_invalidatepage - invalidate part of all of a buffer-backed page
1568 * @page: the page which is affected
1569 * @offset: the index of the truncation point
1571 * block_invalidatepage() is called when all or part of the page has become
1572 * invalidatedby a truncate operation.
1574 * block_invalidatepage() does not have to release all buffers, but it must
1575 * ensure that no dirty buffer is left outside @offset and that no I/O
1576 * is underway against any of the blocks which are outside the truncation
1577 * point. Because the caller is about to free (and possibly reuse) those
1578 * blocks on-disk.
1580 void block_invalidatepage(struct page *page, unsigned long offset)
1582 struct buffer_head *head, *bh, *next;
1583 unsigned int curr_off = 0;
1585 BUG_ON(!PageLocked(page));
1586 if (!page_has_buffers(page))
1587 goto out;
1589 head = page_buffers(page);
1590 bh = head;
1591 do {
1592 unsigned int next_off = curr_off + bh->b_size;
1593 next = bh->b_this_page;
1596 * is this block fully invalidated?
1598 if (offset <= curr_off)
1599 discard_buffer(bh);
1600 curr_off = next_off;
1601 bh = next;
1602 } while (bh != head);
1605 * We release buffers only if the entire page is being invalidated.
1606 * The get_block cached value has been unconditionally invalidated,
1607 * so real IO is not possible anymore.
1609 if (offset == 0)
1610 try_to_release_page(page, 0);
1611 out:
1612 return;
1614 EXPORT_SYMBOL(block_invalidatepage);
1617 * We attach and possibly dirty the buffers atomically wrt
1618 * __set_page_dirty_buffers() via private_lock. try_to_free_buffers
1619 * is already excluded via the page lock.
1621 void create_empty_buffers(struct page *page,
1622 unsigned long blocksize, unsigned long b_state)
1624 struct buffer_head *bh, *head, *tail;
1626 head = alloc_page_buffers(page, blocksize, 1);
1627 bh = head;
1628 do {
1629 bh->b_state |= b_state;
1630 tail = bh;
1631 bh = bh->b_this_page;
1632 } while (bh);
1633 tail->b_this_page = head;
1635 spin_lock(&page->mapping->private_lock);
1636 if (PageUptodate(page) || PageDirty(page)) {
1637 bh = head;
1638 do {
1639 if (PageDirty(page))
1640 set_buffer_dirty(bh);
1641 if (PageUptodate(page))
1642 set_buffer_uptodate(bh);
1643 bh = bh->b_this_page;
1644 } while (bh != head);
1646 attach_page_buffers(page, head);
1647 spin_unlock(&page->mapping->private_lock);
1649 EXPORT_SYMBOL(create_empty_buffers);
1652 * We are taking a block for data and we don't want any output from any
1653 * buffer-cache aliases starting from return from that function and
1654 * until the moment when something will explicitly mark the buffer
1655 * dirty (hopefully that will not happen until we will free that block ;-)
1656 * We don't even need to mark it not-uptodate - nobody can expect
1657 * anything from a newly allocated buffer anyway. We used to used
1658 * unmap_buffer() for such invalidation, but that was wrong. We definitely
1659 * don't want to mark the alias unmapped, for example - it would confuse
1660 * anyone who might pick it with bread() afterwards...
1662 * Also.. Note that bforget() doesn't lock the buffer. So there can
1663 * be writeout I/O going on against recently-freed buffers. We don't
1664 * wait on that I/O in bforget() - it's more efficient to wait on the I/O
1665 * only if we really need to. That happens here.
1667 void unmap_underlying_metadata(struct block_device *bdev, sector_t block)
1669 struct buffer_head *old_bh;
1671 might_sleep();
1673 old_bh = __find_get_block_slow(bdev, block);
1674 if (old_bh) {
1675 clear_buffer_dirty(old_bh);
1676 wait_on_buffer(old_bh);
1677 clear_buffer_req(old_bh);
1678 __brelse(old_bh);
1681 EXPORT_SYMBOL(unmap_underlying_metadata);
1684 * NOTE! All mapped/uptodate combinations are valid:
1686 * Mapped Uptodate Meaning
1688 * No No "unknown" - must do get_block()
1689 * No Yes "hole" - zero-filled
1690 * Yes No "allocated" - allocated on disk, not read in
1691 * Yes Yes "valid" - allocated and up-to-date in memory.
1693 * "Dirty" is valid only with the last case (mapped+uptodate).
1697 * While block_write_full_page is writing back the dirty buffers under
1698 * the page lock, whoever dirtied the buffers may decide to clean them
1699 * again at any time. We handle that by only looking at the buffer
1700 * state inside lock_buffer().
1702 * If block_write_full_page() is called for regular writeback
1703 * (wbc->sync_mode == WB_SYNC_NONE) then it will redirty a page which has a
1704 * locked buffer. This only can happen if someone has written the buffer
1705 * directly, with submit_bh(). At the address_space level PageWriteback
1706 * prevents this contention from occurring.
1708 static int __block_write_full_page(struct inode *inode, struct page *page,
1709 get_block_t *get_block, struct writeback_control *wbc)
1711 int err;
1712 sector_t block;
1713 sector_t last_block;
1714 struct buffer_head *bh, *head;
1715 const unsigned blocksize = 1 << inode->i_blkbits;
1716 int nr_underway = 0;
1718 BUG_ON(!PageLocked(page));
1720 last_block = (i_size_read(inode) - 1) >> inode->i_blkbits;
1722 if (!page_has_buffers(page)) {
1723 create_empty_buffers(page, blocksize,
1724 (1 << BH_Dirty)|(1 << BH_Uptodate));
1728 * Be very careful. We have no exclusion from __set_page_dirty_buffers
1729 * here, and the (potentially unmapped) buffers may become dirty at
1730 * any time. If a buffer becomes dirty here after we've inspected it
1731 * then we just miss that fact, and the page stays dirty.
1733 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
1734 * handle that here by just cleaning them.
1737 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1738 head = page_buffers(page);
1739 bh = head;
1742 * Get all the dirty buffers mapped to disk addresses and
1743 * handle any aliases from the underlying blockdev's mapping.
1745 do {
1746 if (block > last_block) {
1748 * mapped buffers outside i_size will occur, because
1749 * this page can be outside i_size when there is a
1750 * truncate in progress.
1753 * The buffer was zeroed by block_write_full_page()
1755 clear_buffer_dirty(bh);
1756 set_buffer_uptodate(bh);
1757 } else if ((!buffer_mapped(bh) || buffer_delay(bh)) &&
1758 buffer_dirty(bh)) {
1759 WARN_ON(bh->b_size != blocksize);
1760 err = get_block(inode, block, bh, 1);
1761 if (err)
1762 goto recover;
1763 clear_buffer_delay(bh);
1764 if (buffer_new(bh)) {
1765 /* blockdev mappings never come here */
1766 clear_buffer_new(bh);
1767 unmap_underlying_metadata(bh->b_bdev,
1768 bh->b_blocknr);
1771 bh = bh->b_this_page;
1772 block++;
1773 } while (bh != head);
1775 do {
1776 if (!buffer_mapped(bh))
1777 continue;
1779 * If it's a fully non-blocking write attempt and we cannot
1780 * lock the buffer then redirty the page. Note that this can
1781 * potentially cause a busy-wait loop from pdflush and kswapd
1782 * activity, but those code paths have their own higher-level
1783 * throttling.
1785 if (wbc->sync_mode != WB_SYNC_NONE || !wbc->nonblocking) {
1786 lock_buffer(bh);
1787 } else if (!trylock_buffer(bh)) {
1788 redirty_page_for_writepage(wbc, page);
1789 continue;
1791 if (test_clear_buffer_dirty(bh)) {
1792 mark_buffer_async_write(bh);
1793 } else {
1794 unlock_buffer(bh);
1796 } while ((bh = bh->b_this_page) != head);
1799 * The page and its buffers are protected by PageWriteback(), so we can
1800 * drop the bh refcounts early.
1802 BUG_ON(PageWriteback(page));
1803 set_page_writeback(page);
1805 do {
1806 struct buffer_head *next = bh->b_this_page;
1807 if (buffer_async_write(bh)) {
1808 submit_bh(WRITE, bh);
1809 nr_underway++;
1811 bh = next;
1812 } while (bh != head);
1813 unlock_page(page);
1815 err = 0;
1816 done:
1817 if (nr_underway == 0) {
1819 * The page was marked dirty, but the buffers were
1820 * clean. Someone wrote them back by hand with
1821 * ll_rw_block/submit_bh. A rare case.
1823 end_page_writeback(page);
1826 * The page and buffer_heads can be released at any time from
1827 * here on.
1830 return err;
1832 recover:
1834 * ENOSPC, or some other error. We may already have added some
1835 * blocks to the file, so we need to write these out to avoid
1836 * exposing stale data.
1837 * The page is currently locked and not marked for writeback
1839 bh = head;
1840 /* Recovery: lock and submit the mapped buffers */
1841 do {
1842 if (buffer_mapped(bh) && buffer_dirty(bh) &&
1843 !buffer_delay(bh)) {
1844 lock_buffer(bh);
1845 mark_buffer_async_write(bh);
1846 } else {
1848 * The buffer may have been set dirty during
1849 * attachment to a dirty page.
1851 clear_buffer_dirty(bh);
1853 } while ((bh = bh->b_this_page) != head);
1854 SetPageError(page);
1855 BUG_ON(PageWriteback(page));
1856 mapping_set_error(page->mapping, err);
1857 set_page_writeback(page);
1858 do {
1859 struct buffer_head *next = bh->b_this_page;
1860 if (buffer_async_write(bh)) {
1861 clear_buffer_dirty(bh);
1862 submit_bh(WRITE, bh);
1863 nr_underway++;
1865 bh = next;
1866 } while (bh != head);
1867 unlock_page(page);
1868 goto done;
1872 * If a page has any new buffers, zero them out here, and mark them uptodate
1873 * and dirty so they'll be written out (in order to prevent uninitialised
1874 * block data from leaking). And clear the new bit.
1876 void page_zero_new_buffers(struct page *page, unsigned from, unsigned to)
1878 unsigned int block_start, block_end;
1879 struct buffer_head *head, *bh;
1881 BUG_ON(!PageLocked(page));
1882 if (!page_has_buffers(page))
1883 return;
1885 bh = head = page_buffers(page);
1886 block_start = 0;
1887 do {
1888 block_end = block_start + bh->b_size;
1890 if (buffer_new(bh)) {
1891 if (block_end > from && block_start < to) {
1892 if (!PageUptodate(page)) {
1893 unsigned start, size;
1895 start = max(from, block_start);
1896 size = min(to, block_end) - start;
1898 zero_user(page, start, size);
1899 set_buffer_uptodate(bh);
1902 clear_buffer_new(bh);
1903 mark_buffer_dirty(bh);
1907 block_start = block_end;
1908 bh = bh->b_this_page;
1909 } while (bh != head);
1911 EXPORT_SYMBOL(page_zero_new_buffers);
1913 static int __block_prepare_write(struct inode *inode, struct page *page,
1914 unsigned from, unsigned to, get_block_t *get_block)
1916 unsigned block_start, block_end;
1917 sector_t block;
1918 int err = 0;
1919 unsigned blocksize, bbits;
1920 struct buffer_head *bh, *head, *wait[2], **wait_bh=wait;
1922 BUG_ON(!PageLocked(page));
1923 BUG_ON(from > PAGE_CACHE_SIZE);
1924 BUG_ON(to > PAGE_CACHE_SIZE);
1925 BUG_ON(from > to);
1927 blocksize = 1 << inode->i_blkbits;
1928 if (!page_has_buffers(page))
1929 create_empty_buffers(page, blocksize, 0);
1930 head = page_buffers(page);
1932 bbits = inode->i_blkbits;
1933 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
1935 for(bh = head, block_start = 0; bh != head || !block_start;
1936 block++, block_start=block_end, bh = bh->b_this_page) {
1937 block_end = block_start + blocksize;
1938 if (block_end <= from || block_start >= to) {
1939 if (PageUptodate(page)) {
1940 if (!buffer_uptodate(bh))
1941 set_buffer_uptodate(bh);
1943 continue;
1945 if (buffer_new(bh))
1946 clear_buffer_new(bh);
1947 if (!buffer_mapped(bh)) {
1948 WARN_ON(bh->b_size != blocksize);
1949 err = get_block(inode, block, bh, 1);
1950 if (err)
1951 break;
1952 if (buffer_new(bh)) {
1953 unmap_underlying_metadata(bh->b_bdev,
1954 bh->b_blocknr);
1955 if (PageUptodate(page)) {
1956 clear_buffer_new(bh);
1957 set_buffer_uptodate(bh);
1958 mark_buffer_dirty(bh);
1959 continue;
1961 if (block_end > to || block_start < from)
1962 zero_user_segments(page,
1963 to, block_end,
1964 block_start, from);
1965 continue;
1968 if (PageUptodate(page)) {
1969 if (!buffer_uptodate(bh))
1970 set_buffer_uptodate(bh);
1971 continue;
1973 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1974 !buffer_unwritten(bh) &&
1975 (block_start < from || block_end > to)) {
1976 ll_rw_block(READ, 1, &bh);
1977 *wait_bh++=bh;
1981 * If we issued read requests - let them complete.
1983 while(wait_bh > wait) {
1984 wait_on_buffer(*--wait_bh);
1985 if (!buffer_uptodate(*wait_bh))
1986 err = -EIO;
1988 if (unlikely(err))
1989 page_zero_new_buffers(page, from, to);
1990 return err;
1993 static int __block_commit_write(struct inode *inode, struct page *page,
1994 unsigned from, unsigned to)
1996 unsigned block_start, block_end;
1997 int partial = 0;
1998 unsigned blocksize;
1999 struct buffer_head *bh, *head;
2001 blocksize = 1 << inode->i_blkbits;
2003 for(bh = head = page_buffers(page), block_start = 0;
2004 bh != head || !block_start;
2005 block_start=block_end, bh = bh->b_this_page) {
2006 block_end = block_start + blocksize;
2007 if (block_end <= from || block_start >= to) {
2008 if (!buffer_uptodate(bh))
2009 partial = 1;
2010 } else {
2011 set_buffer_uptodate(bh);
2012 mark_buffer_dirty(bh);
2014 clear_buffer_new(bh);
2018 * If this is a partial write which happened to make all buffers
2019 * uptodate then we can optimize away a bogus readpage() for
2020 * the next read(). Here we 'discover' whether the page went
2021 * uptodate as a result of this (potentially partial) write.
2023 if (!partial)
2024 SetPageUptodate(page);
2025 return 0;
2029 * block_write_begin takes care of the basic task of block allocation and
2030 * bringing partial write blocks uptodate first.
2032 * If *pagep is not NULL, then block_write_begin uses the locked page
2033 * at *pagep rather than allocating its own. In this case, the page will
2034 * not be unlocked or deallocated on failure.
2036 int block_write_begin(struct file *file, struct address_space *mapping,
2037 loff_t pos, unsigned len, unsigned flags,
2038 struct page **pagep, void **fsdata,
2039 get_block_t *get_block)
2041 struct inode *inode = mapping->host;
2042 int status = 0;
2043 struct page *page;
2044 pgoff_t index;
2045 unsigned start, end;
2046 int ownpage = 0;
2048 index = pos >> PAGE_CACHE_SHIFT;
2049 start = pos & (PAGE_CACHE_SIZE - 1);
2050 end = start + len;
2052 page = *pagep;
2053 if (page == NULL) {
2054 ownpage = 1;
2055 page = grab_cache_page_write_begin(mapping, index, flags);
2056 if (!page) {
2057 status = -ENOMEM;
2058 goto out;
2060 *pagep = page;
2061 } else
2062 BUG_ON(!PageLocked(page));
2064 status = __block_prepare_write(inode, page, start, end, get_block);
2065 if (unlikely(status)) {
2066 ClearPageUptodate(page);
2068 if (ownpage) {
2069 unlock_page(page);
2070 page_cache_release(page);
2071 *pagep = NULL;
2074 * prepare_write() may have instantiated a few blocks
2075 * outside i_size. Trim these off again. Don't need
2076 * i_size_read because we hold i_mutex.
2078 if (pos + len > inode->i_size)
2079 vmtruncate(inode, inode->i_size);
2083 out:
2084 return status;
2086 EXPORT_SYMBOL(block_write_begin);
2088 int block_write_end(struct file *file, struct address_space *mapping,
2089 loff_t pos, unsigned len, unsigned copied,
2090 struct page *page, void *fsdata)
2092 struct inode *inode = mapping->host;
2093 unsigned start;
2095 start = pos & (PAGE_CACHE_SIZE - 1);
2097 if (unlikely(copied < len)) {
2099 * The buffers that were written will now be uptodate, so we
2100 * don't have to worry about a readpage reading them and
2101 * overwriting a partial write. However if we have encountered
2102 * a short write and only partially written into a buffer, it
2103 * will not be marked uptodate, so a readpage might come in and
2104 * destroy our partial write.
2106 * Do the simplest thing, and just treat any short write to a
2107 * non uptodate page as a zero-length write, and force the
2108 * caller to redo the whole thing.
2110 if (!PageUptodate(page))
2111 copied = 0;
2113 page_zero_new_buffers(page, start+copied, start+len);
2115 flush_dcache_page(page);
2117 /* This could be a short (even 0-length) commit */
2118 __block_commit_write(inode, page, start, start+copied);
2120 return copied;
2122 EXPORT_SYMBOL(block_write_end);
2124 int generic_write_end(struct file *file, struct address_space *mapping,
2125 loff_t pos, unsigned len, unsigned copied,
2126 struct page *page, void *fsdata)
2128 struct inode *inode = mapping->host;
2129 int i_size_changed = 0;
2131 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
2134 * No need to use i_size_read() here, the i_size
2135 * cannot change under us because we hold i_mutex.
2137 * But it's important to update i_size while still holding page lock:
2138 * page writeout could otherwise come in and zero beyond i_size.
2140 if (pos+copied > inode->i_size) {
2141 i_size_write(inode, pos+copied);
2142 i_size_changed = 1;
2145 unlock_page(page);
2146 page_cache_release(page);
2149 * Don't mark the inode dirty under page lock. First, it unnecessarily
2150 * makes the holding time of page lock longer. Second, it forces lock
2151 * ordering of page lock and transaction start for journaling
2152 * filesystems.
2154 if (i_size_changed)
2155 mark_inode_dirty(inode);
2157 return copied;
2159 EXPORT_SYMBOL(generic_write_end);
2162 * block_is_partially_uptodate checks whether buffers within a page are
2163 * uptodate or not.
2165 * Returns true if all buffers which correspond to a file portion
2166 * we want to read are uptodate.
2168 int block_is_partially_uptodate(struct page *page, read_descriptor_t *desc,
2169 unsigned long from)
2171 struct inode *inode = page->mapping->host;
2172 unsigned block_start, block_end, blocksize;
2173 unsigned to;
2174 struct buffer_head *bh, *head;
2175 int ret = 1;
2177 if (!page_has_buffers(page))
2178 return 0;
2180 blocksize = 1 << inode->i_blkbits;
2181 to = min_t(unsigned, PAGE_CACHE_SIZE - from, desc->count);
2182 to = from + to;
2183 if (from < blocksize && to > PAGE_CACHE_SIZE - blocksize)
2184 return 0;
2186 head = page_buffers(page);
2187 bh = head;
2188 block_start = 0;
2189 do {
2190 block_end = block_start + blocksize;
2191 if (block_end > from && block_start < to) {
2192 if (!buffer_uptodate(bh)) {
2193 ret = 0;
2194 break;
2196 if (block_end >= to)
2197 break;
2199 block_start = block_end;
2200 bh = bh->b_this_page;
2201 } while (bh != head);
2203 return ret;
2205 EXPORT_SYMBOL(block_is_partially_uptodate);
2208 * Generic "read page" function for block devices that have the normal
2209 * get_block functionality. This is most of the block device filesystems.
2210 * Reads the page asynchronously --- the unlock_buffer() and
2211 * set/clear_buffer_uptodate() functions propagate buffer state into the
2212 * page struct once IO has completed.
2214 int block_read_full_page(struct page *page, get_block_t *get_block)
2216 struct inode *inode = page->mapping->host;
2217 sector_t iblock, lblock;
2218 struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
2219 unsigned int blocksize;
2220 int nr, i;
2221 int fully_mapped = 1;
2223 BUG_ON(!PageLocked(page));
2224 blocksize = 1 << inode->i_blkbits;
2225 if (!page_has_buffers(page))
2226 create_empty_buffers(page, blocksize, 0);
2227 head = page_buffers(page);
2229 iblock = (sector_t)page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2230 lblock = (i_size_read(inode)+blocksize-1) >> inode->i_blkbits;
2231 bh = head;
2232 nr = 0;
2233 i = 0;
2235 do {
2236 if (buffer_uptodate(bh))
2237 continue;
2239 if (!buffer_mapped(bh)) {
2240 int err = 0;
2242 fully_mapped = 0;
2243 if (iblock < lblock) {
2244 WARN_ON(bh->b_size != blocksize);
2245 err = get_block(inode, iblock, bh, 0);
2246 if (err)
2247 SetPageError(page);
2249 if (!buffer_mapped(bh)) {
2250 zero_user(page, i * blocksize, blocksize);
2251 if (!err)
2252 set_buffer_uptodate(bh);
2253 continue;
2256 * get_block() might have updated the buffer
2257 * synchronously
2259 if (buffer_uptodate(bh))
2260 continue;
2262 arr[nr++] = bh;
2263 } while (i++, iblock++, (bh = bh->b_this_page) != head);
2265 if (fully_mapped)
2266 SetPageMappedToDisk(page);
2268 if (!nr) {
2270 * All buffers are uptodate - we can set the page uptodate
2271 * as well. But not if get_block() returned an error.
2273 if (!PageError(page))
2274 SetPageUptodate(page);
2275 unlock_page(page);
2276 return 0;
2279 /* Stage two: lock the buffers */
2280 for (i = 0; i < nr; i++) {
2281 bh = arr[i];
2282 lock_buffer(bh);
2283 mark_buffer_async_read(bh);
2287 * Stage 3: start the IO. Check for uptodateness
2288 * inside the buffer lock in case another process reading
2289 * the underlying blockdev brought it uptodate (the sct fix).
2291 for (i = 0; i < nr; i++) {
2292 bh = arr[i];
2293 if (buffer_uptodate(bh))
2294 end_buffer_async_read(bh, 1);
2295 else
2296 submit_bh(READ, bh);
2298 return 0;
2301 /* utility function for filesystems that need to do work on expanding
2302 * truncates. Uses filesystem pagecache writes to allow the filesystem to
2303 * deal with the hole.
2305 int generic_cont_expand_simple(struct inode *inode, loff_t size)
2307 struct address_space *mapping = inode->i_mapping;
2308 struct page *page;
2309 void *fsdata;
2310 unsigned long limit;
2311 int err;
2313 err = -EFBIG;
2314 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
2315 if (limit != RLIM_INFINITY && size > (loff_t)limit) {
2316 send_sig(SIGXFSZ, current, 0);
2317 goto out;
2319 if (size > inode->i_sb->s_maxbytes)
2320 goto out;
2322 err = pagecache_write_begin(NULL, mapping, size, 0,
2323 AOP_FLAG_UNINTERRUPTIBLE|AOP_FLAG_CONT_EXPAND,
2324 &page, &fsdata);
2325 if (err)
2326 goto out;
2328 err = pagecache_write_end(NULL, mapping, size, 0, 0, page, fsdata);
2329 BUG_ON(err > 0);
2331 out:
2332 return err;
2335 static int cont_expand_zero(struct file *file, struct address_space *mapping,
2336 loff_t pos, loff_t *bytes)
2338 struct inode *inode = mapping->host;
2339 unsigned blocksize = 1 << inode->i_blkbits;
2340 struct page *page;
2341 void *fsdata;
2342 pgoff_t index, curidx;
2343 loff_t curpos;
2344 unsigned zerofrom, offset, len;
2345 int err = 0;
2347 index = pos >> PAGE_CACHE_SHIFT;
2348 offset = pos & ~PAGE_CACHE_MASK;
2350 while (index > (curidx = (curpos = *bytes)>>PAGE_CACHE_SHIFT)) {
2351 zerofrom = curpos & ~PAGE_CACHE_MASK;
2352 if (zerofrom & (blocksize-1)) {
2353 *bytes |= (blocksize-1);
2354 (*bytes)++;
2356 len = PAGE_CACHE_SIZE - zerofrom;
2358 err = pagecache_write_begin(file, mapping, curpos, len,
2359 AOP_FLAG_UNINTERRUPTIBLE,
2360 &page, &fsdata);
2361 if (err)
2362 goto out;
2363 zero_user(page, zerofrom, len);
2364 err = pagecache_write_end(file, mapping, curpos, len, len,
2365 page, fsdata);
2366 if (err < 0)
2367 goto out;
2368 BUG_ON(err != len);
2369 err = 0;
2371 balance_dirty_pages_ratelimited(mapping);
2374 /* page covers the boundary, find the boundary offset */
2375 if (index == curidx) {
2376 zerofrom = curpos & ~PAGE_CACHE_MASK;
2377 /* if we will expand the thing last block will be filled */
2378 if (offset <= zerofrom) {
2379 goto out;
2381 if (zerofrom & (blocksize-1)) {
2382 *bytes |= (blocksize-1);
2383 (*bytes)++;
2385 len = offset - zerofrom;
2387 err = pagecache_write_begin(file, mapping, curpos, len,
2388 AOP_FLAG_UNINTERRUPTIBLE,
2389 &page, &fsdata);
2390 if (err)
2391 goto out;
2392 zero_user(page, zerofrom, len);
2393 err = pagecache_write_end(file, mapping, curpos, len, len,
2394 page, fsdata);
2395 if (err < 0)
2396 goto out;
2397 BUG_ON(err != len);
2398 err = 0;
2400 out:
2401 return err;
2405 * For moronic filesystems that do not allow holes in file.
2406 * We may have to extend the file.
2408 int cont_write_begin(struct file *file, struct address_space *mapping,
2409 loff_t pos, unsigned len, unsigned flags,
2410 struct page **pagep, void **fsdata,
2411 get_block_t *get_block, loff_t *bytes)
2413 struct inode *inode = mapping->host;
2414 unsigned blocksize = 1 << inode->i_blkbits;
2415 unsigned zerofrom;
2416 int err;
2418 err = cont_expand_zero(file, mapping, pos, bytes);
2419 if (err)
2420 goto out;
2422 zerofrom = *bytes & ~PAGE_CACHE_MASK;
2423 if (pos+len > *bytes && zerofrom & (blocksize-1)) {
2424 *bytes |= (blocksize-1);
2425 (*bytes)++;
2428 *pagep = NULL;
2429 err = block_write_begin(file, mapping, pos, len,
2430 flags, pagep, fsdata, get_block);
2431 out:
2432 return err;
2435 int block_prepare_write(struct page *page, unsigned from, unsigned to,
2436 get_block_t *get_block)
2438 struct inode *inode = page->mapping->host;
2439 int err = __block_prepare_write(inode, page, from, to, get_block);
2440 if (err)
2441 ClearPageUptodate(page);
2442 return err;
2445 int block_commit_write(struct page *page, unsigned from, unsigned to)
2447 struct inode *inode = page->mapping->host;
2448 __block_commit_write(inode,page,from,to);
2449 return 0;
2453 * block_page_mkwrite() is not allowed to change the file size as it gets
2454 * called from a page fault handler when a page is first dirtied. Hence we must
2455 * be careful to check for EOF conditions here. We set the page up correctly
2456 * for a written page which means we get ENOSPC checking when writing into
2457 * holes and correct delalloc and unwritten extent mapping on filesystems that
2458 * support these features.
2460 * We are not allowed to take the i_mutex here so we have to play games to
2461 * protect against truncate races as the page could now be beyond EOF. Because
2462 * vmtruncate() writes the inode size before removing pages, once we have the
2463 * page lock we can determine safely if the page is beyond EOF. If it is not
2464 * beyond EOF, then the page is guaranteed safe against truncation until we
2465 * unlock the page.
2468 block_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf,
2469 get_block_t get_block)
2471 struct page *page = vmf->page;
2472 struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
2473 unsigned long end;
2474 loff_t size;
2475 int ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
2477 lock_page(page);
2478 size = i_size_read(inode);
2479 if ((page->mapping != inode->i_mapping) ||
2480 (page_offset(page) > size)) {
2481 /* page got truncated out from underneath us */
2482 unlock_page(page);
2483 goto out;
2486 /* page is wholly or partially inside EOF */
2487 if (((page->index + 1) << PAGE_CACHE_SHIFT) > size)
2488 end = size & ~PAGE_CACHE_MASK;
2489 else
2490 end = PAGE_CACHE_SIZE;
2492 ret = block_prepare_write(page, 0, end, get_block);
2493 if (!ret)
2494 ret = block_commit_write(page, 0, end);
2496 if (unlikely(ret)) {
2497 unlock_page(page);
2498 if (ret == -ENOMEM)
2499 ret = VM_FAULT_OOM;
2500 else /* -ENOSPC, -EIO, etc */
2501 ret = VM_FAULT_SIGBUS;
2502 } else
2503 ret = VM_FAULT_LOCKED;
2505 out:
2506 return ret;
2510 * nobh_write_begin()'s prereads are special: the buffer_heads are freed
2511 * immediately, while under the page lock. So it needs a special end_io
2512 * handler which does not touch the bh after unlocking it.
2514 static void end_buffer_read_nobh(struct buffer_head *bh, int uptodate)
2516 __end_buffer_read_notouch(bh, uptodate);
2520 * Attach the singly-linked list of buffers created by nobh_write_begin, to
2521 * the page (converting it to circular linked list and taking care of page
2522 * dirty races).
2524 static void attach_nobh_buffers(struct page *page, struct buffer_head *head)
2526 struct buffer_head *bh;
2528 BUG_ON(!PageLocked(page));
2530 spin_lock(&page->mapping->private_lock);
2531 bh = head;
2532 do {
2533 if (PageDirty(page))
2534 set_buffer_dirty(bh);
2535 if (!bh->b_this_page)
2536 bh->b_this_page = head;
2537 bh = bh->b_this_page;
2538 } while (bh != head);
2539 attach_page_buffers(page, head);
2540 spin_unlock(&page->mapping->private_lock);
2544 * On entry, the page is fully not uptodate.
2545 * On exit the page is fully uptodate in the areas outside (from,to)
2547 int nobh_write_begin(struct file *file, struct address_space *mapping,
2548 loff_t pos, unsigned len, unsigned flags,
2549 struct page **pagep, void **fsdata,
2550 get_block_t *get_block)
2552 struct inode *inode = mapping->host;
2553 const unsigned blkbits = inode->i_blkbits;
2554 const unsigned blocksize = 1 << blkbits;
2555 struct buffer_head *head, *bh;
2556 struct page *page;
2557 pgoff_t index;
2558 unsigned from, to;
2559 unsigned block_in_page;
2560 unsigned block_start, block_end;
2561 sector_t block_in_file;
2562 int nr_reads = 0;
2563 int ret = 0;
2564 int is_mapped_to_disk = 1;
2566 index = pos >> PAGE_CACHE_SHIFT;
2567 from = pos & (PAGE_CACHE_SIZE - 1);
2568 to = from + len;
2570 page = grab_cache_page_write_begin(mapping, index, flags);
2571 if (!page)
2572 return -ENOMEM;
2573 *pagep = page;
2574 *fsdata = NULL;
2576 if (page_has_buffers(page)) {
2577 unlock_page(page);
2578 page_cache_release(page);
2579 *pagep = NULL;
2580 return block_write_begin(file, mapping, pos, len, flags, pagep,
2581 fsdata, get_block);
2584 if (PageMappedToDisk(page))
2585 return 0;
2588 * Allocate buffers so that we can keep track of state, and potentially
2589 * attach them to the page if an error occurs. In the common case of
2590 * no error, they will just be freed again without ever being attached
2591 * to the page (which is all OK, because we're under the page lock).
2593 * Be careful: the buffer linked list is a NULL terminated one, rather
2594 * than the circular one we're used to.
2596 head = alloc_page_buffers(page, blocksize, 0);
2597 if (!head) {
2598 ret = -ENOMEM;
2599 goto out_release;
2602 block_in_file = (sector_t)page->index << (PAGE_CACHE_SHIFT - blkbits);
2605 * We loop across all blocks in the page, whether or not they are
2606 * part of the affected region. This is so we can discover if the
2607 * page is fully mapped-to-disk.
2609 for (block_start = 0, block_in_page = 0, bh = head;
2610 block_start < PAGE_CACHE_SIZE;
2611 block_in_page++, block_start += blocksize, bh = bh->b_this_page) {
2612 int create;
2614 block_end = block_start + blocksize;
2615 bh->b_state = 0;
2616 create = 1;
2617 if (block_start >= to)
2618 create = 0;
2619 ret = get_block(inode, block_in_file + block_in_page,
2620 bh, create);
2621 if (ret)
2622 goto failed;
2623 if (!buffer_mapped(bh))
2624 is_mapped_to_disk = 0;
2625 if (buffer_new(bh))
2626 unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
2627 if (PageUptodate(page)) {
2628 set_buffer_uptodate(bh);
2629 continue;
2631 if (buffer_new(bh) || !buffer_mapped(bh)) {
2632 zero_user_segments(page, block_start, from,
2633 to, block_end);
2634 continue;
2636 if (buffer_uptodate(bh))
2637 continue; /* reiserfs does this */
2638 if (block_start < from || block_end > to) {
2639 lock_buffer(bh);
2640 bh->b_end_io = end_buffer_read_nobh;
2641 submit_bh(READ, bh);
2642 nr_reads++;
2646 if (nr_reads) {
2648 * The page is locked, so these buffers are protected from
2649 * any VM or truncate activity. Hence we don't need to care
2650 * for the buffer_head refcounts.
2652 for (bh = head; bh; bh = bh->b_this_page) {
2653 wait_on_buffer(bh);
2654 if (!buffer_uptodate(bh))
2655 ret = -EIO;
2657 if (ret)
2658 goto failed;
2661 if (is_mapped_to_disk)
2662 SetPageMappedToDisk(page);
2664 *fsdata = head; /* to be released by nobh_write_end */
2666 return 0;
2668 failed:
2669 BUG_ON(!ret);
2671 * Error recovery is a bit difficult. We need to zero out blocks that
2672 * were newly allocated, and dirty them to ensure they get written out.
2673 * Buffers need to be attached to the page at this point, otherwise
2674 * the handling of potential IO errors during writeout would be hard
2675 * (could try doing synchronous writeout, but what if that fails too?)
2677 attach_nobh_buffers(page, head);
2678 page_zero_new_buffers(page, from, to);
2680 out_release:
2681 unlock_page(page);
2682 page_cache_release(page);
2683 *pagep = NULL;
2685 if (pos + len > inode->i_size)
2686 vmtruncate(inode, inode->i_size);
2688 return ret;
2690 EXPORT_SYMBOL(nobh_write_begin);
2692 int nobh_write_end(struct file *file, struct address_space *mapping,
2693 loff_t pos, unsigned len, unsigned copied,
2694 struct page *page, void *fsdata)
2696 struct inode *inode = page->mapping->host;
2697 struct buffer_head *head = fsdata;
2698 struct buffer_head *bh;
2699 BUG_ON(fsdata != NULL && page_has_buffers(page));
2701 if (unlikely(copied < len) && head)
2702 attach_nobh_buffers(page, head);
2703 if (page_has_buffers(page))
2704 return generic_write_end(file, mapping, pos, len,
2705 copied, page, fsdata);
2707 SetPageUptodate(page);
2708 set_page_dirty(page);
2709 if (pos+copied > inode->i_size) {
2710 i_size_write(inode, pos+copied);
2711 mark_inode_dirty(inode);
2714 unlock_page(page);
2715 page_cache_release(page);
2717 while (head) {
2718 bh = head;
2719 head = head->b_this_page;
2720 free_buffer_head(bh);
2723 return copied;
2725 EXPORT_SYMBOL(nobh_write_end);
2728 * nobh_writepage() - based on block_full_write_page() except
2729 * that it tries to operate without attaching bufferheads to
2730 * the page.
2732 int nobh_writepage(struct page *page, get_block_t *get_block,
2733 struct writeback_control *wbc)
2735 struct inode * const inode = page->mapping->host;
2736 loff_t i_size = i_size_read(inode);
2737 const pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
2738 unsigned offset;
2739 int ret;
2741 /* Is the page fully inside i_size? */
2742 if (page->index < end_index)
2743 goto out;
2745 /* Is the page fully outside i_size? (truncate in progress) */
2746 offset = i_size & (PAGE_CACHE_SIZE-1);
2747 if (page->index >= end_index+1 || !offset) {
2749 * The page may have dirty, unmapped buffers. For example,
2750 * they may have been added in ext3_writepage(). Make them
2751 * freeable here, so the page does not leak.
2753 #if 0
2754 /* Not really sure about this - do we need this ? */
2755 if (page->mapping->a_ops->invalidatepage)
2756 page->mapping->a_ops->invalidatepage(page, offset);
2757 #endif
2758 unlock_page(page);
2759 return 0; /* don't care */
2763 * The page straddles i_size. It must be zeroed out on each and every
2764 * writepage invocation because it may be mmapped. "A file is mapped
2765 * in multiples of the page size. For a file that is not a multiple of
2766 * the page size, the remaining memory is zeroed when mapped, and
2767 * writes to that region are not written out to the file."
2769 zero_user_segment(page, offset, PAGE_CACHE_SIZE);
2770 out:
2771 ret = mpage_writepage(page, get_block, wbc);
2772 if (ret == -EAGAIN)
2773 ret = __block_write_full_page(inode, page, get_block, wbc);
2774 return ret;
2776 EXPORT_SYMBOL(nobh_writepage);
2778 int nobh_truncate_page(struct address_space *mapping,
2779 loff_t from, get_block_t *get_block)
2781 pgoff_t index = from >> PAGE_CACHE_SHIFT;
2782 unsigned offset = from & (PAGE_CACHE_SIZE-1);
2783 unsigned blocksize;
2784 sector_t iblock;
2785 unsigned length, pos;
2786 struct inode *inode = mapping->host;
2787 struct page *page;
2788 struct buffer_head map_bh;
2789 int err;
2791 blocksize = 1 << inode->i_blkbits;
2792 length = offset & (blocksize - 1);
2794 /* Block boundary? Nothing to do */
2795 if (!length)
2796 return 0;
2798 length = blocksize - length;
2799 iblock = (sector_t)index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2801 page = grab_cache_page(mapping, index);
2802 err = -ENOMEM;
2803 if (!page)
2804 goto out;
2806 if (page_has_buffers(page)) {
2807 has_buffers:
2808 unlock_page(page);
2809 page_cache_release(page);
2810 return block_truncate_page(mapping, from, get_block);
2813 /* Find the buffer that contains "offset" */
2814 pos = blocksize;
2815 while (offset >= pos) {
2816 iblock++;
2817 pos += blocksize;
2820 err = get_block(inode, iblock, &map_bh, 0);
2821 if (err)
2822 goto unlock;
2823 /* unmapped? It's a hole - nothing to do */
2824 if (!buffer_mapped(&map_bh))
2825 goto unlock;
2827 /* Ok, it's mapped. Make sure it's up-to-date */
2828 if (!PageUptodate(page)) {
2829 err = mapping->a_ops->readpage(NULL, page);
2830 if (err) {
2831 page_cache_release(page);
2832 goto out;
2834 lock_page(page);
2835 if (!PageUptodate(page)) {
2836 err = -EIO;
2837 goto unlock;
2839 if (page_has_buffers(page))
2840 goto has_buffers;
2842 zero_user(page, offset, length);
2843 set_page_dirty(page);
2844 err = 0;
2846 unlock:
2847 unlock_page(page);
2848 page_cache_release(page);
2849 out:
2850 return err;
2852 EXPORT_SYMBOL(nobh_truncate_page);
2854 int block_truncate_page(struct address_space *mapping,
2855 loff_t from, get_block_t *get_block)
2857 pgoff_t index = from >> PAGE_CACHE_SHIFT;
2858 unsigned offset = from & (PAGE_CACHE_SIZE-1);
2859 unsigned blocksize;
2860 sector_t iblock;
2861 unsigned length, pos;
2862 struct inode *inode = mapping->host;
2863 struct page *page;
2864 struct buffer_head *bh;
2865 int err;
2867 blocksize = 1 << inode->i_blkbits;
2868 length = offset & (blocksize - 1);
2870 /* Block boundary? Nothing to do */
2871 if (!length)
2872 return 0;
2874 length = blocksize - length;
2875 iblock = (sector_t)index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2877 page = grab_cache_page(mapping, index);
2878 err = -ENOMEM;
2879 if (!page)
2880 goto out;
2882 if (!page_has_buffers(page))
2883 create_empty_buffers(page, blocksize, 0);
2885 /* Find the buffer that contains "offset" */
2886 bh = page_buffers(page);
2887 pos = blocksize;
2888 while (offset >= pos) {
2889 bh = bh->b_this_page;
2890 iblock++;
2891 pos += blocksize;
2894 err = 0;
2895 if (!buffer_mapped(bh)) {
2896 WARN_ON(bh->b_size != blocksize);
2897 err = get_block(inode, iblock, bh, 0);
2898 if (err)
2899 goto unlock;
2900 /* unmapped? It's a hole - nothing to do */
2901 if (!buffer_mapped(bh))
2902 goto unlock;
2905 /* Ok, it's mapped. Make sure it's up-to-date */
2906 if (PageUptodate(page))
2907 set_buffer_uptodate(bh);
2909 if (!buffer_uptodate(bh) && !buffer_delay(bh) && !buffer_unwritten(bh)) {
2910 err = -EIO;
2911 ll_rw_block(READ, 1, &bh);
2912 wait_on_buffer(bh);
2913 /* Uhhuh. Read error. Complain and punt. */
2914 if (!buffer_uptodate(bh))
2915 goto unlock;
2918 zero_user(page, offset, length);
2919 mark_buffer_dirty(bh);
2920 err = 0;
2922 unlock:
2923 unlock_page(page);
2924 page_cache_release(page);
2925 out:
2926 return err;
2930 * The generic ->writepage function for buffer-backed address_spaces
2932 int block_write_full_page(struct page *page, get_block_t *get_block,
2933 struct writeback_control *wbc)
2935 struct inode * const inode = page->mapping->host;
2936 loff_t i_size = i_size_read(inode);
2937 const pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
2938 unsigned offset;
2940 /* Is the page fully inside i_size? */
2941 if (page->index < end_index)
2942 return __block_write_full_page(inode, page, get_block, wbc);
2944 /* Is the page fully outside i_size? (truncate in progress) */
2945 offset = i_size & (PAGE_CACHE_SIZE-1);
2946 if (page->index >= end_index+1 || !offset) {
2948 * The page may have dirty, unmapped buffers. For example,
2949 * they may have been added in ext3_writepage(). Make them
2950 * freeable here, so the page does not leak.
2952 do_invalidatepage(page, 0);
2953 unlock_page(page);
2954 return 0; /* don't care */
2958 * The page straddles i_size. It must be zeroed out on each and every
2959 * writepage invokation because it may be mmapped. "A file is mapped
2960 * in multiples of the page size. For a file that is not a multiple of
2961 * the page size, the remaining memory is zeroed when mapped, and
2962 * writes to that region are not written out to the file."
2964 zero_user_segment(page, offset, PAGE_CACHE_SIZE);
2965 return __block_write_full_page(inode, page, get_block, wbc);
2968 sector_t generic_block_bmap(struct address_space *mapping, sector_t block,
2969 get_block_t *get_block)
2971 struct buffer_head tmp;
2972 struct inode *inode = mapping->host;
2973 tmp.b_state = 0;
2974 tmp.b_blocknr = 0;
2975 tmp.b_size = 1 << inode->i_blkbits;
2976 get_block(inode, block, &tmp, 0);
2977 return tmp.b_blocknr;
2980 static void end_bio_bh_io_sync(struct bio *bio, int err)
2982 struct buffer_head *bh = bio->bi_private;
2984 if (err == -EOPNOTSUPP) {
2985 set_bit(BIO_EOPNOTSUPP, &bio->bi_flags);
2986 set_bit(BH_Eopnotsupp, &bh->b_state);
2989 if (unlikely (test_bit(BIO_QUIET,&bio->bi_flags)))
2990 set_bit(BH_Quiet, &bh->b_state);
2992 bh->b_end_io(bh, test_bit(BIO_UPTODATE, &bio->bi_flags));
2993 bio_put(bio);
2996 int submit_bh(int rw, struct buffer_head * bh)
2998 struct bio *bio;
2999 int ret = 0;
3001 BUG_ON(!buffer_locked(bh));
3002 BUG_ON(!buffer_mapped(bh));
3003 BUG_ON(!bh->b_end_io);
3006 * Mask in barrier bit for a write (could be either a WRITE or a
3007 * WRITE_SYNC
3009 if (buffer_ordered(bh) && (rw & WRITE))
3010 rw |= WRITE_BARRIER;
3013 * Only clear out a write error when rewriting
3015 if (test_set_buffer_req(bh) && (rw & WRITE))
3016 clear_buffer_write_io_error(bh);
3019 * from here on down, it's all bio -- do the initial mapping,
3020 * submit_bio -> generic_make_request may further map this bio around
3022 bio = bio_alloc(GFP_NOIO, 1);
3024 bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9);
3025 bio->bi_bdev = bh->b_bdev;
3026 bio->bi_io_vec[0].bv_page = bh->b_page;
3027 bio->bi_io_vec[0].bv_len = bh->b_size;
3028 bio->bi_io_vec[0].bv_offset = bh_offset(bh);
3030 bio->bi_vcnt = 1;
3031 bio->bi_idx = 0;
3032 bio->bi_size = bh->b_size;
3034 bio->bi_end_io = end_bio_bh_io_sync;
3035 bio->bi_private = bh;
3037 bio_get(bio);
3038 submit_bio(rw, bio);
3040 if (bio_flagged(bio, BIO_EOPNOTSUPP))
3041 ret = -EOPNOTSUPP;
3043 bio_put(bio);
3044 return ret;
3048 * ll_rw_block: low-level access to block devices (DEPRECATED)
3049 * @rw: whether to %READ or %WRITE or %SWRITE or maybe %READA (readahead)
3050 * @nr: number of &struct buffer_heads in the array
3051 * @bhs: array of pointers to &struct buffer_head
3053 * ll_rw_block() takes an array of pointers to &struct buffer_heads, and
3054 * requests an I/O operation on them, either a %READ or a %WRITE. The third
3055 * %SWRITE is like %WRITE only we make sure that the *current* data in buffers
3056 * are sent to disk. The fourth %READA option is described in the documentation
3057 * for generic_make_request() which ll_rw_block() calls.
3059 * This function drops any buffer that it cannot get a lock on (with the
3060 * BH_Lock state bit) unless SWRITE is required, any buffer that appears to be
3061 * clean when doing a write request, and any buffer that appears to be
3062 * up-to-date when doing read request. Further it marks as clean buffers that
3063 * are processed for writing (the buffer cache won't assume that they are
3064 * actually clean until the buffer gets unlocked).
3066 * ll_rw_block sets b_end_io to simple completion handler that marks
3067 * the buffer up-to-date (if approriate), unlocks the buffer and wakes
3068 * any waiters.
3070 * All of the buffers must be for the same device, and must also be a
3071 * multiple of the current approved size for the device.
3073 void ll_rw_block(int rw, int nr, struct buffer_head *bhs[])
3075 int i;
3077 for (i = 0; i < nr; i++) {
3078 struct buffer_head *bh = bhs[i];
3080 if (rw == SWRITE || rw == SWRITE_SYNC)
3081 lock_buffer(bh);
3082 else if (!trylock_buffer(bh))
3083 continue;
3085 if (rw == WRITE || rw == SWRITE || rw == SWRITE_SYNC) {
3086 if (test_clear_buffer_dirty(bh)) {
3087 bh->b_end_io = end_buffer_write_sync;
3088 get_bh(bh);
3089 if (rw == SWRITE_SYNC)
3090 submit_bh(WRITE_SYNC, bh);
3091 else
3092 submit_bh(WRITE, bh);
3093 continue;
3095 } else {
3096 if (!buffer_uptodate(bh)) {
3097 bh->b_end_io = end_buffer_read_sync;
3098 get_bh(bh);
3099 submit_bh(rw, bh);
3100 continue;
3103 unlock_buffer(bh);
3108 * For a data-integrity writeout, we need to wait upon any in-progress I/O
3109 * and then start new I/O and then wait upon it. The caller must have a ref on
3110 * the buffer_head.
3112 int sync_dirty_buffer(struct buffer_head *bh)
3114 int ret = 0;
3116 WARN_ON(atomic_read(&bh->b_count) < 1);
3117 lock_buffer(bh);
3118 if (test_clear_buffer_dirty(bh)) {
3119 get_bh(bh);
3120 bh->b_end_io = end_buffer_write_sync;
3121 ret = submit_bh(WRITE, bh);
3122 wait_on_buffer(bh);
3123 if (buffer_eopnotsupp(bh)) {
3124 clear_buffer_eopnotsupp(bh);
3125 ret = -EOPNOTSUPP;
3127 if (!ret && !buffer_uptodate(bh))
3128 ret = -EIO;
3129 } else {
3130 unlock_buffer(bh);
3132 return ret;
3136 * try_to_free_buffers() checks if all the buffers on this particular page
3137 * are unused, and releases them if so.
3139 * Exclusion against try_to_free_buffers may be obtained by either
3140 * locking the page or by holding its mapping's private_lock.
3142 * If the page is dirty but all the buffers are clean then we need to
3143 * be sure to mark the page clean as well. This is because the page
3144 * may be against a block device, and a later reattachment of buffers
3145 * to a dirty page will set *all* buffers dirty. Which would corrupt
3146 * filesystem data on the same device.
3148 * The same applies to regular filesystem pages: if all the buffers are
3149 * clean then we set the page clean and proceed. To do that, we require
3150 * total exclusion from __set_page_dirty_buffers(). That is obtained with
3151 * private_lock.
3153 * try_to_free_buffers() is non-blocking.
3155 static inline int buffer_busy(struct buffer_head *bh)
3157 return atomic_read(&bh->b_count) |
3158 (bh->b_state & ((1 << BH_Dirty) | (1 << BH_Lock)));
3161 static int
3162 drop_buffers(struct page *page, struct buffer_head **buffers_to_free)
3164 struct buffer_head *head = page_buffers(page);
3165 struct buffer_head *bh;
3167 bh = head;
3168 do {
3169 if (buffer_write_io_error(bh) && page->mapping)
3170 set_bit(AS_EIO, &page->mapping->flags);
3171 if (buffer_busy(bh))
3172 goto failed;
3173 bh = bh->b_this_page;
3174 } while (bh != head);
3176 do {
3177 struct buffer_head *next = bh->b_this_page;
3179 if (bh->b_assoc_map)
3180 __remove_assoc_queue(bh);
3181 bh = next;
3182 } while (bh != head);
3183 *buffers_to_free = head;
3184 __clear_page_buffers(page);
3185 return 1;
3186 failed:
3187 return 0;
3190 int try_to_free_buffers(struct page *page)
3192 struct address_space * const mapping = page->mapping;
3193 struct buffer_head *buffers_to_free = NULL;
3194 int ret = 0;
3196 BUG_ON(!PageLocked(page));
3197 if (PageWriteback(page))
3198 return 0;
3200 if (mapping == NULL) { /* can this still happen? */
3201 ret = drop_buffers(page, &buffers_to_free);
3202 goto out;
3205 spin_lock(&mapping->private_lock);
3206 ret = drop_buffers(page, &buffers_to_free);
3209 * If the filesystem writes its buffers by hand (eg ext3)
3210 * then we can have clean buffers against a dirty page. We
3211 * clean the page here; otherwise the VM will never notice
3212 * that the filesystem did any IO at all.
3214 * Also, during truncate, discard_buffer will have marked all
3215 * the page's buffers clean. We discover that here and clean
3216 * the page also.
3218 * private_lock must be held over this entire operation in order
3219 * to synchronise against __set_page_dirty_buffers and prevent the
3220 * dirty bit from being lost.
3222 if (ret)
3223 cancel_dirty_page(page, PAGE_CACHE_SIZE);
3224 spin_unlock(&mapping->private_lock);
3225 out:
3226 if (buffers_to_free) {
3227 struct buffer_head *bh = buffers_to_free;
3229 do {
3230 struct buffer_head *next = bh->b_this_page;
3231 free_buffer_head(bh);
3232 bh = next;
3233 } while (bh != buffers_to_free);
3235 return ret;
3237 EXPORT_SYMBOL(try_to_free_buffers);
3239 void block_sync_page(struct page *page)
3241 struct address_space *mapping;
3243 smp_mb();
3244 mapping = page_mapping(page);
3245 if (mapping)
3246 blk_run_backing_dev(mapping->backing_dev_info, page);
3250 * There are no bdflush tunables left. But distributions are
3251 * still running obsolete flush daemons, so we terminate them here.
3253 * Use of bdflush() is deprecated and will be removed in a future kernel.
3254 * The `pdflush' kernel threads fully replace bdflush daemons and this call.
3256 SYSCALL_DEFINE2(bdflush, int, func, long, data)
3258 static int msg_count;
3260 if (!capable(CAP_SYS_ADMIN))
3261 return -EPERM;
3263 if (msg_count < 5) {
3264 msg_count++;
3265 printk(KERN_INFO
3266 "warning: process `%s' used the obsolete bdflush"
3267 " system call\n", current->comm);
3268 printk(KERN_INFO "Fix your initscripts?\n");
3271 if (func == 1)
3272 do_exit(0);
3273 return 0;
3277 * Buffer-head allocation
3279 static struct kmem_cache *bh_cachep;
3282 * Once the number of bh's in the machine exceeds this level, we start
3283 * stripping them in writeback.
3285 static int max_buffer_heads;
3287 int buffer_heads_over_limit;
3289 struct bh_accounting {
3290 int nr; /* Number of live bh's */
3291 int ratelimit; /* Limit cacheline bouncing */
3294 static DEFINE_PER_CPU(struct bh_accounting, bh_accounting) = {0, 0};
3296 static void recalc_bh_state(void)
3298 int i;
3299 int tot = 0;
3301 if (__get_cpu_var(bh_accounting).ratelimit++ < 4096)
3302 return;
3303 __get_cpu_var(bh_accounting).ratelimit = 0;
3304 for_each_online_cpu(i)
3305 tot += per_cpu(bh_accounting, i).nr;
3306 buffer_heads_over_limit = (tot > max_buffer_heads);
3309 struct buffer_head *alloc_buffer_head(gfp_t gfp_flags)
3311 struct buffer_head *ret = kmem_cache_alloc(bh_cachep, gfp_flags);
3312 if (ret) {
3313 INIT_LIST_HEAD(&ret->b_assoc_buffers);
3314 get_cpu_var(bh_accounting).nr++;
3315 recalc_bh_state();
3316 put_cpu_var(bh_accounting);
3318 return ret;
3320 EXPORT_SYMBOL(alloc_buffer_head);
3322 void free_buffer_head(struct buffer_head *bh)
3324 BUG_ON(!list_empty(&bh->b_assoc_buffers));
3325 kmem_cache_free(bh_cachep, bh);
3326 get_cpu_var(bh_accounting).nr--;
3327 recalc_bh_state();
3328 put_cpu_var(bh_accounting);
3330 EXPORT_SYMBOL(free_buffer_head);
3332 static void buffer_exit_cpu(int cpu)
3334 int i;
3335 struct bh_lru *b = &per_cpu(bh_lrus, cpu);
3337 for (i = 0; i < BH_LRU_SIZE; i++) {
3338 brelse(b->bhs[i]);
3339 b->bhs[i] = NULL;
3341 get_cpu_var(bh_accounting).nr += per_cpu(bh_accounting, cpu).nr;
3342 per_cpu(bh_accounting, cpu).nr = 0;
3343 put_cpu_var(bh_accounting);
3346 static int buffer_cpu_notify(struct notifier_block *self,
3347 unsigned long action, void *hcpu)
3349 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN)
3350 buffer_exit_cpu((unsigned long)hcpu);
3351 return NOTIFY_OK;
3355 * bh_uptodate_or_lock - Test whether the buffer is uptodate
3356 * @bh: struct buffer_head
3358 * Return true if the buffer is up-to-date and false,
3359 * with the buffer locked, if not.
3361 int bh_uptodate_or_lock(struct buffer_head *bh)
3363 if (!buffer_uptodate(bh)) {
3364 lock_buffer(bh);
3365 if (!buffer_uptodate(bh))
3366 return 0;
3367 unlock_buffer(bh);
3369 return 1;
3371 EXPORT_SYMBOL(bh_uptodate_or_lock);
3374 * bh_submit_read - Submit a locked buffer for reading
3375 * @bh: struct buffer_head
3377 * Returns zero on success and -EIO on error.
3379 int bh_submit_read(struct buffer_head *bh)
3381 BUG_ON(!buffer_locked(bh));
3383 if (buffer_uptodate(bh)) {
3384 unlock_buffer(bh);
3385 return 0;
3388 get_bh(bh);
3389 bh->b_end_io = end_buffer_read_sync;
3390 submit_bh(READ, bh);
3391 wait_on_buffer(bh);
3392 if (buffer_uptodate(bh))
3393 return 0;
3394 return -EIO;
3396 EXPORT_SYMBOL(bh_submit_read);
3398 static void
3399 init_buffer_head(void *data)
3401 struct buffer_head *bh = data;
3403 memset(bh, 0, sizeof(*bh));
3404 INIT_LIST_HEAD(&bh->b_assoc_buffers);
3407 void __init buffer_init(void)
3409 int nrpages;
3411 bh_cachep = kmem_cache_create("buffer_head",
3412 sizeof(struct buffer_head), 0,
3413 (SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|
3414 SLAB_MEM_SPREAD),
3415 init_buffer_head);
3418 * Limit the bh occupancy to 10% of ZONE_NORMAL
3420 nrpages = (nr_free_buffer_pages() * 10) / 100;
3421 max_buffer_heads = nrpages * (PAGE_SIZE / sizeof(struct buffer_head));
3422 hotcpu_notifier(buffer_cpu_notify, 0);
3425 EXPORT_SYMBOL(__bforget);
3426 EXPORT_SYMBOL(__brelse);
3427 EXPORT_SYMBOL(__wait_on_buffer);
3428 EXPORT_SYMBOL(block_commit_write);
3429 EXPORT_SYMBOL(block_prepare_write);
3430 EXPORT_SYMBOL(block_page_mkwrite);
3431 EXPORT_SYMBOL(block_read_full_page);
3432 EXPORT_SYMBOL(block_sync_page);
3433 EXPORT_SYMBOL(block_truncate_page);
3434 EXPORT_SYMBOL(block_write_full_page);
3435 EXPORT_SYMBOL(cont_write_begin);
3436 EXPORT_SYMBOL(end_buffer_read_sync);
3437 EXPORT_SYMBOL(end_buffer_write_sync);
3438 EXPORT_SYMBOL(file_fsync);
3439 EXPORT_SYMBOL(fsync_bdev);
3440 EXPORT_SYMBOL(generic_block_bmap);
3441 EXPORT_SYMBOL(generic_cont_expand_simple);
3442 EXPORT_SYMBOL(init_buffer);
3443 EXPORT_SYMBOL(invalidate_bdev);
3444 EXPORT_SYMBOL(ll_rw_block);
3445 EXPORT_SYMBOL(mark_buffer_dirty);
3446 EXPORT_SYMBOL(submit_bh);
3447 EXPORT_SYMBOL(sync_dirty_buffer);
3448 EXPORT_SYMBOL(unlock_buffer);