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