mfd: wm8350-i2c: Make sure the i2c regmap functions are compiled
[linux/fpc-iii.git] / mm / filemap.c
blobaf9e11ea4ecf8713c1d441cf8f3fe71142924845
1 /*
2 * linux/mm/filemap.c
4 * Copyright (C) 1994-1999 Linus Torvalds
5 */
7 /*
8 * This file handles the generic file mmap semantics used by
9 * most "normal" filesystems (but you don't /have/ to use this:
10 * the NFS filesystem used to do this differently, for example)
12 #include <linux/export.h>
13 #include <linux/compiler.h>
14 #include <linux/fs.h>
15 #include <linux/uaccess.h>
16 #include <linux/aio.h>
17 #include <linux/capability.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/gfp.h>
20 #include <linux/mm.h>
21 #include <linux/swap.h>
22 #include <linux/mman.h>
23 #include <linux/pagemap.h>
24 #include <linux/file.h>
25 #include <linux/uio.h>
26 #include <linux/hash.h>
27 #include <linux/writeback.h>
28 #include <linux/backing-dev.h>
29 #include <linux/pagevec.h>
30 #include <linux/blkdev.h>
31 #include <linux/security.h>
32 #include <linux/cpuset.h>
33 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
34 #include <linux/memcontrol.h>
35 #include <linux/cleancache.h>
36 #include "internal.h"
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/filemap.h>
42 * FIXME: remove all knowledge of the buffer layer from the core VM
44 #include <linux/buffer_head.h> /* for try_to_free_buffers */
46 #include <asm/mman.h>
49 * Shared mappings implemented 30.11.1994. It's not fully working yet,
50 * though.
52 * Shared mappings now work. 15.8.1995 Bruno.
54 * finished 'unifying' the page and buffer cache and SMP-threaded the
55 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
57 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
61 * Lock ordering:
63 * ->i_mmap_mutex (truncate_pagecache)
64 * ->private_lock (__free_pte->__set_page_dirty_buffers)
65 * ->swap_lock (exclusive_swap_page, others)
66 * ->mapping->tree_lock
68 * ->i_mutex
69 * ->i_mmap_mutex (truncate->unmap_mapping_range)
71 * ->mmap_sem
72 * ->i_mmap_mutex
73 * ->page_table_lock or pte_lock (various, mainly in memory.c)
74 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
76 * ->mmap_sem
77 * ->lock_page (access_process_vm)
79 * ->i_mutex (generic_file_buffered_write)
80 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
82 * bdi->wb.list_lock
83 * sb_lock (fs/fs-writeback.c)
84 * ->mapping->tree_lock (__sync_single_inode)
86 * ->i_mmap_mutex
87 * ->anon_vma.lock (vma_adjust)
89 * ->anon_vma.lock
90 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
92 * ->page_table_lock or pte_lock
93 * ->swap_lock (try_to_unmap_one)
94 * ->private_lock (try_to_unmap_one)
95 * ->tree_lock (try_to_unmap_one)
96 * ->zone.lru_lock (follow_page->mark_page_accessed)
97 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
98 * ->private_lock (page_remove_rmap->set_page_dirty)
99 * ->tree_lock (page_remove_rmap->set_page_dirty)
100 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
101 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
102 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
103 * ->inode->i_lock (zap_pte_range->set_page_dirty)
104 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
106 * ->i_mmap_mutex
107 * ->tasklist_lock (memory_failure, collect_procs_ao)
111 * Delete a page from the page cache and free it. Caller has to make
112 * sure the page is locked and that nobody else uses it - or that usage
113 * is safe. The caller must hold the mapping's tree_lock.
115 void __delete_from_page_cache(struct page *page)
117 struct address_space *mapping = page->mapping;
119 trace_mm_filemap_delete_from_page_cache(page);
121 * if we're uptodate, flush out into the cleancache, otherwise
122 * invalidate any existing cleancache entries. We can't leave
123 * stale data around in the cleancache once our page is gone
125 if (PageUptodate(page) && PageMappedToDisk(page))
126 cleancache_put_page(page);
127 else
128 cleancache_invalidate_page(mapping, page);
130 radix_tree_delete(&mapping->page_tree, page->index);
131 page->mapping = NULL;
132 /* Leave page->index set: truncation lookup relies upon it */
133 mapping->nrpages--;
134 __dec_zone_page_state(page, NR_FILE_PAGES);
135 if (PageSwapBacked(page))
136 __dec_zone_page_state(page, NR_SHMEM);
137 BUG_ON(page_mapped(page));
140 * Some filesystems seem to re-dirty the page even after
141 * the VM has canceled the dirty bit (eg ext3 journaling).
143 * Fix it up by doing a final dirty accounting check after
144 * having removed the page entirely.
146 if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
147 dec_zone_page_state(page, NR_FILE_DIRTY);
148 dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
153 * delete_from_page_cache - delete page from page cache
154 * @page: the page which the kernel is trying to remove from page cache
156 * This must be called only on pages that have been verified to be in the page
157 * cache and locked. It will never put the page into the free list, the caller
158 * has a reference on the page.
160 void delete_from_page_cache(struct page *page)
162 struct address_space *mapping = page->mapping;
163 void (*freepage)(struct page *);
165 BUG_ON(!PageLocked(page));
167 freepage = mapping->a_ops->freepage;
168 spin_lock_irq(&mapping->tree_lock);
169 __delete_from_page_cache(page);
170 spin_unlock_irq(&mapping->tree_lock);
171 mem_cgroup_uncharge_cache_page(page);
173 if (freepage)
174 freepage(page);
175 page_cache_release(page);
177 EXPORT_SYMBOL(delete_from_page_cache);
179 static int sleep_on_page(void *word)
181 io_schedule();
182 return 0;
185 static int sleep_on_page_killable(void *word)
187 sleep_on_page(word);
188 return fatal_signal_pending(current) ? -EINTR : 0;
191 static int filemap_check_errors(struct address_space *mapping)
193 int ret = 0;
194 /* Check for outstanding write errors */
195 if (test_bit(AS_ENOSPC, &mapping->flags) &&
196 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
197 ret = -ENOSPC;
198 if (test_bit(AS_EIO, &mapping->flags) &&
199 test_and_clear_bit(AS_EIO, &mapping->flags))
200 ret = -EIO;
201 return ret;
205 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
206 * @mapping: address space structure to write
207 * @start: offset in bytes where the range starts
208 * @end: offset in bytes where the range ends (inclusive)
209 * @sync_mode: enable synchronous operation
211 * Start writeback against all of a mapping's dirty pages that lie
212 * within the byte offsets <start, end> inclusive.
214 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
215 * opposed to a regular memory cleansing writeback. The difference between
216 * these two operations is that if a dirty page/buffer is encountered, it must
217 * be waited upon, and not just skipped over.
219 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
220 loff_t end, int sync_mode)
222 int ret;
223 struct writeback_control wbc = {
224 .sync_mode = sync_mode,
225 .nr_to_write = LONG_MAX,
226 .range_start = start,
227 .range_end = end,
230 if (!mapping_cap_writeback_dirty(mapping))
231 return 0;
233 ret = do_writepages(mapping, &wbc);
234 return ret;
237 static inline int __filemap_fdatawrite(struct address_space *mapping,
238 int sync_mode)
240 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
243 int filemap_fdatawrite(struct address_space *mapping)
245 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
247 EXPORT_SYMBOL(filemap_fdatawrite);
249 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
250 loff_t end)
252 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
254 EXPORT_SYMBOL(filemap_fdatawrite_range);
257 * filemap_flush - mostly a non-blocking flush
258 * @mapping: target address_space
260 * This is a mostly non-blocking flush. Not suitable for data-integrity
261 * purposes - I/O may not be started against all dirty pages.
263 int filemap_flush(struct address_space *mapping)
265 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
267 EXPORT_SYMBOL(filemap_flush);
270 * filemap_fdatawait_range - wait for writeback to complete
271 * @mapping: address space structure to wait for
272 * @start_byte: offset in bytes where the range starts
273 * @end_byte: offset in bytes where the range ends (inclusive)
275 * Walk the list of under-writeback pages of the given address space
276 * in the given range and wait for all of them.
278 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
279 loff_t end_byte)
281 pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
282 pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
283 struct pagevec pvec;
284 int nr_pages;
285 int ret2, ret = 0;
287 if (end_byte < start_byte)
288 goto out;
290 pagevec_init(&pvec, 0);
291 while ((index <= end) &&
292 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
293 PAGECACHE_TAG_WRITEBACK,
294 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
295 unsigned i;
297 for (i = 0; i < nr_pages; i++) {
298 struct page *page = pvec.pages[i];
300 /* until radix tree lookup accepts end_index */
301 if (page->index > end)
302 continue;
304 wait_on_page_writeback(page);
305 if (TestClearPageError(page))
306 ret = -EIO;
308 pagevec_release(&pvec);
309 cond_resched();
311 out:
312 ret2 = filemap_check_errors(mapping);
313 if (!ret)
314 ret = ret2;
316 return ret;
318 EXPORT_SYMBOL(filemap_fdatawait_range);
321 * filemap_fdatawait - wait for all under-writeback pages to complete
322 * @mapping: address space structure to wait for
324 * Walk the list of under-writeback pages of the given address space
325 * and wait for all of them.
327 int filemap_fdatawait(struct address_space *mapping)
329 loff_t i_size = i_size_read(mapping->host);
331 if (i_size == 0)
332 return 0;
334 return filemap_fdatawait_range(mapping, 0, i_size - 1);
336 EXPORT_SYMBOL(filemap_fdatawait);
338 int filemap_write_and_wait(struct address_space *mapping)
340 int err = 0;
342 if (mapping->nrpages) {
343 err = filemap_fdatawrite(mapping);
345 * Even if the above returned error, the pages may be
346 * written partially (e.g. -ENOSPC), so we wait for it.
347 * But the -EIO is special case, it may indicate the worst
348 * thing (e.g. bug) happened, so we avoid waiting for it.
350 if (err != -EIO) {
351 int err2 = filemap_fdatawait(mapping);
352 if (!err)
353 err = err2;
355 } else {
356 err = filemap_check_errors(mapping);
358 return err;
360 EXPORT_SYMBOL(filemap_write_and_wait);
363 * filemap_write_and_wait_range - write out & wait on a file range
364 * @mapping: the address_space for the pages
365 * @lstart: offset in bytes where the range starts
366 * @lend: offset in bytes where the range ends (inclusive)
368 * Write out and wait upon file offsets lstart->lend, inclusive.
370 * Note that `lend' is inclusive (describes the last byte to be written) so
371 * that this function can be used to write to the very end-of-file (end = -1).
373 int filemap_write_and_wait_range(struct address_space *mapping,
374 loff_t lstart, loff_t lend)
376 int err = 0;
378 if (mapping->nrpages) {
379 err = __filemap_fdatawrite_range(mapping, lstart, lend,
380 WB_SYNC_ALL);
381 /* See comment of filemap_write_and_wait() */
382 if (err != -EIO) {
383 int err2 = filemap_fdatawait_range(mapping,
384 lstart, lend);
385 if (!err)
386 err = err2;
388 } else {
389 err = filemap_check_errors(mapping);
391 return err;
393 EXPORT_SYMBOL(filemap_write_and_wait_range);
396 * replace_page_cache_page - replace a pagecache page with a new one
397 * @old: page to be replaced
398 * @new: page to replace with
399 * @gfp_mask: allocation mode
401 * This function replaces a page in the pagecache with a new one. On
402 * success it acquires the pagecache reference for the new page and
403 * drops it for the old page. Both the old and new pages must be
404 * locked. This function does not add the new page to the LRU, the
405 * caller must do that.
407 * The remove + add is atomic. The only way this function can fail is
408 * memory allocation failure.
410 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
412 int error;
414 VM_BUG_ON(!PageLocked(old));
415 VM_BUG_ON(!PageLocked(new));
416 VM_BUG_ON(new->mapping);
418 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
419 if (!error) {
420 struct address_space *mapping = old->mapping;
421 void (*freepage)(struct page *);
423 pgoff_t offset = old->index;
424 freepage = mapping->a_ops->freepage;
426 page_cache_get(new);
427 new->mapping = mapping;
428 new->index = offset;
430 spin_lock_irq(&mapping->tree_lock);
431 __delete_from_page_cache(old);
432 error = radix_tree_insert(&mapping->page_tree, offset, new);
433 BUG_ON(error);
434 mapping->nrpages++;
435 __inc_zone_page_state(new, NR_FILE_PAGES);
436 if (PageSwapBacked(new))
437 __inc_zone_page_state(new, NR_SHMEM);
438 spin_unlock_irq(&mapping->tree_lock);
439 /* mem_cgroup codes must not be called under tree_lock */
440 mem_cgroup_replace_page_cache(old, new);
441 radix_tree_preload_end();
442 if (freepage)
443 freepage(old);
444 page_cache_release(old);
447 return error;
449 EXPORT_SYMBOL_GPL(replace_page_cache_page);
451 static int page_cache_tree_insert(struct address_space *mapping,
452 struct page *page)
454 void **slot;
455 int error;
457 slot = radix_tree_lookup_slot(&mapping->page_tree, page->index);
458 if (slot) {
459 void *p;
461 p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
462 if (!radix_tree_exceptional_entry(p))
463 return -EEXIST;
464 radix_tree_replace_slot(slot, page);
465 mapping->nrpages++;
466 return 0;
468 error = radix_tree_insert(&mapping->page_tree, page->index, page);
469 if (!error)
470 mapping->nrpages++;
471 return error;
475 * add_to_page_cache_locked - add a locked page to the pagecache
476 * @page: page to add
477 * @mapping: the page's address_space
478 * @offset: page index
479 * @gfp_mask: page allocation mode
481 * This function is used to add a page to the pagecache. It must be locked.
482 * This function does not add the page to the LRU. The caller must do that.
484 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
485 pgoff_t offset, gfp_t gfp_mask)
487 int error;
489 VM_BUG_ON(!PageLocked(page));
490 VM_BUG_ON(PageSwapBacked(page));
492 error = mem_cgroup_cache_charge(page, current->mm,
493 gfp_mask & GFP_RECLAIM_MASK);
494 if (error)
495 return error;
497 error = radix_tree_maybe_preload(gfp_mask & ~__GFP_HIGHMEM);
498 if (error) {
499 mem_cgroup_uncharge_cache_page(page);
500 return error;
503 page_cache_get(page);
504 page->mapping = mapping;
505 page->index = offset;
507 spin_lock_irq(&mapping->tree_lock);
508 error = page_cache_tree_insert(mapping, page);
509 radix_tree_preload_end();
510 if (unlikely(error))
511 goto err_insert;
512 __inc_zone_page_state(page, NR_FILE_PAGES);
513 spin_unlock_irq(&mapping->tree_lock);
514 trace_mm_filemap_add_to_page_cache(page);
515 return 0;
516 err_insert:
517 page->mapping = NULL;
518 /* Leave page->index set: truncation relies upon it */
519 spin_unlock_irq(&mapping->tree_lock);
520 mem_cgroup_uncharge_cache_page(page);
521 page_cache_release(page);
522 return error;
524 EXPORT_SYMBOL(add_to_page_cache_locked);
526 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
527 pgoff_t offset, gfp_t gfp_mask)
529 int ret;
531 ret = add_to_page_cache(page, mapping, offset, gfp_mask);
532 if (ret == 0)
533 lru_cache_add_file(page);
534 return ret;
536 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
538 #ifdef CONFIG_NUMA
539 struct page *__page_cache_alloc(gfp_t gfp)
541 int n;
542 struct page *page;
544 if (cpuset_do_page_mem_spread()) {
545 unsigned int cpuset_mems_cookie;
546 do {
547 cpuset_mems_cookie = read_mems_allowed_begin();
548 n = cpuset_mem_spread_node();
549 page = alloc_pages_exact_node(n, gfp, 0);
550 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
552 return page;
554 return alloc_pages(gfp, 0);
556 EXPORT_SYMBOL(__page_cache_alloc);
557 #endif
560 * In order to wait for pages to become available there must be
561 * waitqueues associated with pages. By using a hash table of
562 * waitqueues where the bucket discipline is to maintain all
563 * waiters on the same queue and wake all when any of the pages
564 * become available, and for the woken contexts to check to be
565 * sure the appropriate page became available, this saves space
566 * at a cost of "thundering herd" phenomena during rare hash
567 * collisions.
569 static wait_queue_head_t *page_waitqueue(struct page *page)
571 const struct zone *zone = page_zone(page);
573 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
576 static inline void wake_up_page(struct page *page, int bit)
578 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
581 void wait_on_page_bit(struct page *page, int bit_nr)
583 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
585 if (test_bit(bit_nr, &page->flags))
586 __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,
587 TASK_UNINTERRUPTIBLE);
589 EXPORT_SYMBOL(wait_on_page_bit);
591 int wait_on_page_bit_killable(struct page *page, int bit_nr)
593 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
595 if (!test_bit(bit_nr, &page->flags))
596 return 0;
598 return __wait_on_bit(page_waitqueue(page), &wait,
599 sleep_on_page_killable, TASK_KILLABLE);
603 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
604 * @page: Page defining the wait queue of interest
605 * @waiter: Waiter to add to the queue
607 * Add an arbitrary @waiter to the wait queue for the nominated @page.
609 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
611 wait_queue_head_t *q = page_waitqueue(page);
612 unsigned long flags;
614 spin_lock_irqsave(&q->lock, flags);
615 __add_wait_queue(q, waiter);
616 spin_unlock_irqrestore(&q->lock, flags);
618 EXPORT_SYMBOL_GPL(add_page_wait_queue);
621 * unlock_page - unlock a locked page
622 * @page: the page
624 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
625 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
626 * mechananism between PageLocked pages and PageWriteback pages is shared.
627 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
629 * The mb is necessary to enforce ordering between the clear_bit and the read
630 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
632 void unlock_page(struct page *page)
634 VM_BUG_ON(!PageLocked(page));
635 clear_bit_unlock(PG_locked, &page->flags);
636 smp_mb__after_clear_bit();
637 wake_up_page(page, PG_locked);
639 EXPORT_SYMBOL(unlock_page);
642 * end_page_writeback - end writeback against a page
643 * @page: the page
645 void end_page_writeback(struct page *page)
648 * TestClearPageReclaim could be used here but it is an atomic
649 * operation and overkill in this particular case. Failing to
650 * shuffle a page marked for immediate reclaim is too mild to
651 * justify taking an atomic operation penalty at the end of
652 * ever page writeback.
654 if (PageReclaim(page)) {
655 ClearPageReclaim(page);
656 rotate_reclaimable_page(page);
659 if (!test_clear_page_writeback(page))
660 BUG();
662 smp_mb__after_clear_bit();
663 wake_up_page(page, PG_writeback);
665 EXPORT_SYMBOL(end_page_writeback);
668 * __lock_page - get a lock on the page, assuming we need to sleep to get it
669 * @page: the page to lock
671 void __lock_page(struct page *page)
673 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
675 __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,
676 TASK_UNINTERRUPTIBLE);
678 EXPORT_SYMBOL(__lock_page);
680 int __lock_page_killable(struct page *page)
682 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
684 return __wait_on_bit_lock(page_waitqueue(page), &wait,
685 sleep_on_page_killable, TASK_KILLABLE);
687 EXPORT_SYMBOL_GPL(__lock_page_killable);
689 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
690 unsigned int flags)
692 if (flags & FAULT_FLAG_ALLOW_RETRY) {
694 * CAUTION! In this case, mmap_sem is not released
695 * even though return 0.
697 if (flags & FAULT_FLAG_RETRY_NOWAIT)
698 return 0;
700 up_read(&mm->mmap_sem);
701 if (flags & FAULT_FLAG_KILLABLE)
702 wait_on_page_locked_killable(page);
703 else
704 wait_on_page_locked(page);
705 return 0;
706 } else {
707 if (flags & FAULT_FLAG_KILLABLE) {
708 int ret;
710 ret = __lock_page_killable(page);
711 if (ret) {
712 up_read(&mm->mmap_sem);
713 return 0;
715 } else
716 __lock_page(page);
717 return 1;
722 * page_cache_next_hole - find the next hole (not-present entry)
723 * @mapping: mapping
724 * @index: index
725 * @max_scan: maximum range to search
727 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
728 * lowest indexed hole.
730 * Returns: the index of the hole if found, otherwise returns an index
731 * outside of the set specified (in which case 'return - index >=
732 * max_scan' will be true). In rare cases of index wrap-around, 0 will
733 * be returned.
735 * page_cache_next_hole may be called under rcu_read_lock. However,
736 * like radix_tree_gang_lookup, this will not atomically search a
737 * snapshot of the tree at a single point in time. For example, if a
738 * hole is created at index 5, then subsequently a hole is created at
739 * index 10, page_cache_next_hole covering both indexes may return 10
740 * if called under rcu_read_lock.
742 pgoff_t page_cache_next_hole(struct address_space *mapping,
743 pgoff_t index, unsigned long max_scan)
745 unsigned long i;
747 for (i = 0; i < max_scan; i++) {
748 struct page *page;
750 page = radix_tree_lookup(&mapping->page_tree, index);
751 if (!page || radix_tree_exceptional_entry(page))
752 break;
753 index++;
754 if (index == 0)
755 break;
758 return index;
760 EXPORT_SYMBOL(page_cache_next_hole);
763 * page_cache_prev_hole - find the prev hole (not-present entry)
764 * @mapping: mapping
765 * @index: index
766 * @max_scan: maximum range to search
768 * Search backwards in the range [max(index-max_scan+1, 0), index] for
769 * the first hole.
771 * Returns: the index of the hole if found, otherwise returns an index
772 * outside of the set specified (in which case 'index - return >=
773 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
774 * will be returned.
776 * page_cache_prev_hole may be called under rcu_read_lock. However,
777 * like radix_tree_gang_lookup, this will not atomically search a
778 * snapshot of the tree at a single point in time. For example, if a
779 * hole is created at index 10, then subsequently a hole is created at
780 * index 5, page_cache_prev_hole covering both indexes may return 5 if
781 * called under rcu_read_lock.
783 pgoff_t page_cache_prev_hole(struct address_space *mapping,
784 pgoff_t index, unsigned long max_scan)
786 unsigned long i;
788 for (i = 0; i < max_scan; i++) {
789 struct page *page;
791 page = radix_tree_lookup(&mapping->page_tree, index);
792 if (!page || radix_tree_exceptional_entry(page))
793 break;
794 index--;
795 if (index == ULONG_MAX)
796 break;
799 return index;
801 EXPORT_SYMBOL(page_cache_prev_hole);
804 * find_get_entry - find and get a page cache entry
805 * @mapping: the address_space to search
806 * @offset: the page cache index
808 * Looks up the page cache slot at @mapping & @offset. If there is a
809 * page cache page, it is returned with an increased refcount.
811 * If the slot holds a shadow entry of a previously evicted page, it
812 * is returned.
814 * Otherwise, %NULL is returned.
816 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
818 void **pagep;
819 struct page *page;
821 rcu_read_lock();
822 repeat:
823 page = NULL;
824 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
825 if (pagep) {
826 page = radix_tree_deref_slot(pagep);
827 if (unlikely(!page))
828 goto out;
829 if (radix_tree_exception(page)) {
830 if (radix_tree_deref_retry(page))
831 goto repeat;
833 * Otherwise, shmem/tmpfs must be storing a swap entry
834 * here as an exceptional entry: so return it without
835 * attempting to raise page count.
837 goto out;
839 if (!page_cache_get_speculative(page))
840 goto repeat;
843 * Has the page moved?
844 * This is part of the lockless pagecache protocol. See
845 * include/linux/pagemap.h for details.
847 if (unlikely(page != *pagep)) {
848 page_cache_release(page);
849 goto repeat;
852 out:
853 rcu_read_unlock();
855 return page;
857 EXPORT_SYMBOL(find_get_entry);
860 * find_lock_entry - locate, pin and lock a page cache entry
861 * @mapping: the address_space to search
862 * @offset: the page cache index
864 * Looks up the page cache slot at @mapping & @offset. If there is a
865 * page cache page, it is returned locked and with an increased
866 * refcount.
868 * If the slot holds a shadow entry of a previously evicted page, it
869 * is returned.
871 * Otherwise, %NULL is returned.
873 * find_lock_entry() may sleep.
875 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
877 struct page *page;
879 repeat:
880 page = find_get_entry(mapping, offset);
881 if (page && !radix_tree_exception(page)) {
882 lock_page(page);
883 /* Has the page been truncated? */
884 if (unlikely(page->mapping != mapping)) {
885 unlock_page(page);
886 page_cache_release(page);
887 goto repeat;
889 VM_BUG_ON(page->index != offset);
891 return page;
893 EXPORT_SYMBOL(find_lock_entry);
896 * pagecache_get_page - find and get a page reference
897 * @mapping: the address_space to search
898 * @offset: the page index
899 * @fgp_flags: PCG flags
900 * @gfp_mask: gfp mask to use for the page cache data page allocation
902 * Looks up the page cache slot at @mapping & @offset.
904 * PCG flags modify how the page is returned
906 * FGP_ACCESSED: the page will be marked accessed
907 * FGP_LOCK: Page is return locked
908 * FGP_CREAT: If page is not present then a new page is allocated using
909 * @gfp_mask and added to the page cache and the VM's LRU
910 * list. The page is returned locked and with an increased
911 * refcount. Otherwise, %NULL is returned.
913 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
914 * if the GFP flags specified for FGP_CREAT are atomic.
916 * If there is a page cache page, it is returned with an increased refcount.
918 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
919 int fgp_flags, gfp_t gfp_mask)
921 struct page *page;
923 repeat:
924 page = find_get_entry(mapping, offset);
925 if (radix_tree_exceptional_entry(page))
926 page = NULL;
927 if (!page)
928 goto no_page;
930 if (fgp_flags & FGP_LOCK) {
931 if (fgp_flags & FGP_NOWAIT) {
932 if (!trylock_page(page)) {
933 page_cache_release(page);
934 return NULL;
936 } else {
937 lock_page(page);
940 /* Has the page been truncated? */
941 if (unlikely(page->mapping != mapping)) {
942 unlock_page(page);
943 page_cache_release(page);
944 goto repeat;
946 VM_BUG_ON(page->index != offset);
949 if (page && (fgp_flags & FGP_ACCESSED))
950 mark_page_accessed(page);
952 no_page:
953 if (!page && (fgp_flags & FGP_CREAT)) {
954 int err;
955 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
956 gfp_mask |= __GFP_WRITE;
957 if (fgp_flags & FGP_NOFS)
958 gfp_mask &= ~__GFP_FS;
960 page = __page_cache_alloc(gfp_mask);
961 if (!page)
962 return NULL;
964 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
965 fgp_flags |= FGP_LOCK;
967 /* Init accessed so avoit atomic mark_page_accessed later */
968 if (fgp_flags & FGP_ACCESSED)
969 init_page_accessed(page);
971 err = add_to_page_cache_lru(page, mapping, offset,
972 gfp_mask & GFP_RECLAIM_MASK);
973 if (unlikely(err)) {
974 page_cache_release(page);
975 page = NULL;
976 if (err == -EEXIST)
977 goto repeat;
981 return page;
983 EXPORT_SYMBOL(pagecache_get_page);
986 * find_get_entries - gang pagecache lookup
987 * @mapping: The address_space to search
988 * @start: The starting page cache index
989 * @nr_entries: The maximum number of entries
990 * @entries: Where the resulting entries are placed
991 * @indices: The cache indices corresponding to the entries in @entries
993 * find_get_entries() will search for and return a group of up to
994 * @nr_entries entries in the mapping. The entries are placed at
995 * @entries. find_get_entries() takes a reference against any actual
996 * pages it returns.
998 * The search returns a group of mapping-contiguous page cache entries
999 * with ascending indexes. There may be holes in the indices due to
1000 * not-present pages.
1002 * Any shadow entries of evicted pages are included in the returned
1003 * array.
1005 * find_get_entries() returns the number of pages and shadow entries
1006 * which were found.
1008 unsigned find_get_entries(struct address_space *mapping,
1009 pgoff_t start, unsigned int nr_entries,
1010 struct page **entries, pgoff_t *indices)
1012 void **slot;
1013 unsigned int ret = 0;
1014 struct radix_tree_iter iter;
1016 if (!nr_entries)
1017 return 0;
1019 rcu_read_lock();
1020 restart:
1021 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1022 struct page *page;
1023 repeat:
1024 page = radix_tree_deref_slot(slot);
1025 if (unlikely(!page))
1026 continue;
1027 if (radix_tree_exception(page)) {
1028 if (radix_tree_deref_retry(page))
1029 goto restart;
1031 * Otherwise, we must be storing a swap entry
1032 * here as an exceptional entry: so return it
1033 * without attempting to raise page count.
1035 goto export;
1037 if (!page_cache_get_speculative(page))
1038 goto repeat;
1040 /* Has the page moved? */
1041 if (unlikely(page != *slot)) {
1042 page_cache_release(page);
1043 goto repeat;
1045 export:
1046 indices[ret] = iter.index;
1047 entries[ret] = page;
1048 if (++ret == nr_entries)
1049 break;
1051 rcu_read_unlock();
1052 return ret;
1056 * find_get_pages - gang pagecache lookup
1057 * @mapping: The address_space to search
1058 * @start: The starting page index
1059 * @nr_pages: The maximum number of pages
1060 * @pages: Where the resulting pages are placed
1062 * find_get_pages() will search for and return a group of up to
1063 * @nr_pages pages in the mapping. The pages are placed at @pages.
1064 * find_get_pages() takes a reference against the returned pages.
1066 * The search returns a group of mapping-contiguous pages with ascending
1067 * indexes. There may be holes in the indices due to not-present pages.
1069 * find_get_pages() returns the number of pages which were found.
1071 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
1072 unsigned int nr_pages, struct page **pages)
1074 struct radix_tree_iter iter;
1075 void **slot;
1076 unsigned ret = 0;
1078 if (unlikely(!nr_pages))
1079 return 0;
1081 rcu_read_lock();
1082 restart:
1083 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1084 struct page *page;
1085 repeat:
1086 page = radix_tree_deref_slot(slot);
1087 if (unlikely(!page))
1088 continue;
1090 if (radix_tree_exception(page)) {
1091 if (radix_tree_deref_retry(page)) {
1093 * Transient condition which can only trigger
1094 * when entry at index 0 moves out of or back
1095 * to root: none yet gotten, safe to restart.
1097 WARN_ON(iter.index);
1098 goto restart;
1101 * Otherwise, shmem/tmpfs must be storing a swap entry
1102 * here as an exceptional entry: so skip over it -
1103 * we only reach this from invalidate_mapping_pages().
1105 continue;
1108 if (!page_cache_get_speculative(page))
1109 goto repeat;
1111 /* Has the page moved? */
1112 if (unlikely(page != *slot)) {
1113 page_cache_release(page);
1114 goto repeat;
1117 pages[ret] = page;
1118 if (++ret == nr_pages)
1119 break;
1122 rcu_read_unlock();
1123 return ret;
1127 * find_get_pages_contig - gang contiguous pagecache lookup
1128 * @mapping: The address_space to search
1129 * @index: The starting page index
1130 * @nr_pages: The maximum number of pages
1131 * @pages: Where the resulting pages are placed
1133 * find_get_pages_contig() works exactly like find_get_pages(), except
1134 * that the returned number of pages are guaranteed to be contiguous.
1136 * find_get_pages_contig() returns the number of pages which were found.
1138 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1139 unsigned int nr_pages, struct page **pages)
1141 struct radix_tree_iter iter;
1142 void **slot;
1143 unsigned int ret = 0;
1145 if (unlikely(!nr_pages))
1146 return 0;
1148 rcu_read_lock();
1149 restart:
1150 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1151 struct page *page;
1152 repeat:
1153 page = radix_tree_deref_slot(slot);
1154 /* The hole, there no reason to continue */
1155 if (unlikely(!page))
1156 break;
1158 if (radix_tree_exception(page)) {
1159 if (radix_tree_deref_retry(page)) {
1161 * Transient condition which can only trigger
1162 * when entry at index 0 moves out of or back
1163 * to root: none yet gotten, safe to restart.
1165 goto restart;
1168 * Otherwise, shmem/tmpfs must be storing a swap entry
1169 * here as an exceptional entry: so stop looking for
1170 * contiguous pages.
1172 break;
1175 if (!page_cache_get_speculative(page))
1176 goto repeat;
1178 /* Has the page moved? */
1179 if (unlikely(page != *slot)) {
1180 page_cache_release(page);
1181 goto repeat;
1185 * must check mapping and index after taking the ref.
1186 * otherwise we can get both false positives and false
1187 * negatives, which is just confusing to the caller.
1189 if (page->mapping == NULL || page->index != iter.index) {
1190 page_cache_release(page);
1191 break;
1194 pages[ret] = page;
1195 if (++ret == nr_pages)
1196 break;
1198 rcu_read_unlock();
1199 return ret;
1201 EXPORT_SYMBOL(find_get_pages_contig);
1204 * find_get_pages_tag - find and return pages that match @tag
1205 * @mapping: the address_space to search
1206 * @index: the starting page index
1207 * @tag: the tag index
1208 * @nr_pages: the maximum number of pages
1209 * @pages: where the resulting pages are placed
1211 * Like find_get_pages, except we only return pages which are tagged with
1212 * @tag. We update @index to index the next page for the traversal.
1214 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1215 int tag, unsigned int nr_pages, struct page **pages)
1217 struct radix_tree_iter iter;
1218 void **slot;
1219 unsigned ret = 0;
1221 if (unlikely(!nr_pages))
1222 return 0;
1224 rcu_read_lock();
1225 restart:
1226 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1227 &iter, *index, tag) {
1228 struct page *page;
1229 repeat:
1230 page = radix_tree_deref_slot(slot);
1231 if (unlikely(!page))
1232 continue;
1234 if (radix_tree_exception(page)) {
1235 if (radix_tree_deref_retry(page)) {
1237 * Transient condition which can only trigger
1238 * when entry at index 0 moves out of or back
1239 * to root: none yet gotten, safe to restart.
1241 goto restart;
1244 * This function is never used on a shmem/tmpfs
1245 * mapping, so a swap entry won't be found here.
1247 BUG();
1250 if (!page_cache_get_speculative(page))
1251 goto repeat;
1253 /* Has the page moved? */
1254 if (unlikely(page != *slot)) {
1255 page_cache_release(page);
1256 goto repeat;
1259 pages[ret] = page;
1260 if (++ret == nr_pages)
1261 break;
1264 rcu_read_unlock();
1266 if (ret)
1267 *index = pages[ret - 1]->index + 1;
1269 return ret;
1271 EXPORT_SYMBOL(find_get_pages_tag);
1274 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1275 * a _large_ part of the i/o request. Imagine the worst scenario:
1277 * ---R__________________________________________B__________
1278 * ^ reading here ^ bad block(assume 4k)
1280 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1281 * => failing the whole request => read(R) => read(R+1) =>
1282 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1283 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1284 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1286 * It is going insane. Fix it by quickly scaling down the readahead size.
1288 static void shrink_readahead_size_eio(struct file *filp,
1289 struct file_ra_state *ra)
1291 ra->ra_pages /= 4;
1295 * do_generic_file_read - generic file read routine
1296 * @filp: the file to read
1297 * @ppos: current file position
1298 * @desc: read_descriptor
1299 * @actor: read method
1301 * This is a generic file read routine, and uses the
1302 * mapping->a_ops->readpage() function for the actual low-level stuff.
1304 * This is really ugly. But the goto's actually try to clarify some
1305 * of the logic when it comes to error handling etc.
1307 static void do_generic_file_read(struct file *filp, loff_t *ppos,
1308 read_descriptor_t *desc, read_actor_t actor)
1310 struct address_space *mapping = filp->f_mapping;
1311 struct inode *inode = mapping->host;
1312 struct file_ra_state *ra = &filp->f_ra;
1313 pgoff_t index;
1314 pgoff_t last_index;
1315 pgoff_t prev_index;
1316 unsigned long offset; /* offset into pagecache page */
1317 unsigned int prev_offset;
1318 int error;
1320 index = *ppos >> PAGE_CACHE_SHIFT;
1321 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
1322 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1323 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
1324 offset = *ppos & ~PAGE_CACHE_MASK;
1326 for (;;) {
1327 struct page *page;
1328 pgoff_t end_index;
1329 loff_t isize;
1330 unsigned long nr, ret;
1332 cond_resched();
1333 find_page:
1334 page = find_get_page(mapping, index);
1335 if (!page) {
1336 page_cache_sync_readahead(mapping,
1337 ra, filp,
1338 index, last_index - index);
1339 page = find_get_page(mapping, index);
1340 if (unlikely(page == NULL))
1341 goto no_cached_page;
1343 if (PageReadahead(page)) {
1344 page_cache_async_readahead(mapping,
1345 ra, filp, page,
1346 index, last_index - index);
1348 if (!PageUptodate(page)) {
1349 if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
1350 !mapping->a_ops->is_partially_uptodate)
1351 goto page_not_up_to_date;
1352 if (!trylock_page(page))
1353 goto page_not_up_to_date;
1354 /* Did it get truncated before we got the lock? */
1355 if (!page->mapping)
1356 goto page_not_up_to_date_locked;
1357 if (!mapping->a_ops->is_partially_uptodate(page,
1358 desc, offset))
1359 goto page_not_up_to_date_locked;
1360 unlock_page(page);
1362 page_ok:
1364 * i_size must be checked after we know the page is Uptodate.
1366 * Checking i_size after the check allows us to calculate
1367 * the correct value for "nr", which means the zero-filled
1368 * part of the page is not copied back to userspace (unless
1369 * another truncate extends the file - this is desired though).
1372 isize = i_size_read(inode);
1373 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1374 if (unlikely(!isize || index > end_index)) {
1375 page_cache_release(page);
1376 goto out;
1379 /* nr is the maximum number of bytes to copy from this page */
1380 nr = PAGE_CACHE_SIZE;
1381 if (index == end_index) {
1382 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1383 if (nr <= offset) {
1384 page_cache_release(page);
1385 goto out;
1388 nr = nr - offset;
1390 /* If users can be writing to this page using arbitrary
1391 * virtual addresses, take care about potential aliasing
1392 * before reading the page on the kernel side.
1394 if (mapping_writably_mapped(mapping))
1395 flush_dcache_page(page);
1398 * When a sequential read accesses a page several times,
1399 * only mark it as accessed the first time.
1401 if (prev_index != index || offset != prev_offset)
1402 mark_page_accessed(page);
1403 prev_index = index;
1406 * Ok, we have the page, and it's up-to-date, so
1407 * now we can copy it to user space...
1409 * The actor routine returns how many bytes were actually used..
1410 * NOTE! This may not be the same as how much of a user buffer
1411 * we filled up (we may be padding etc), so we can only update
1412 * "pos" here (the actor routine has to update the user buffer
1413 * pointers and the remaining count).
1415 ret = actor(desc, page, offset, nr);
1416 offset += ret;
1417 index += offset >> PAGE_CACHE_SHIFT;
1418 offset &= ~PAGE_CACHE_MASK;
1419 prev_offset = offset;
1421 page_cache_release(page);
1422 if (ret == nr && desc->count)
1423 continue;
1424 goto out;
1426 page_not_up_to_date:
1427 /* Get exclusive access to the page ... */
1428 error = lock_page_killable(page);
1429 if (unlikely(error))
1430 goto readpage_error;
1432 page_not_up_to_date_locked:
1433 /* Did it get truncated before we got the lock? */
1434 if (!page->mapping) {
1435 unlock_page(page);
1436 page_cache_release(page);
1437 continue;
1440 /* Did somebody else fill it already? */
1441 if (PageUptodate(page)) {
1442 unlock_page(page);
1443 goto page_ok;
1446 readpage:
1448 * A previous I/O error may have been due to temporary
1449 * failures, eg. multipath errors.
1450 * PG_error will be set again if readpage fails.
1452 ClearPageError(page);
1453 /* Start the actual read. The read will unlock the page. */
1454 error = mapping->a_ops->readpage(filp, page);
1456 if (unlikely(error)) {
1457 if (error == AOP_TRUNCATED_PAGE) {
1458 page_cache_release(page);
1459 goto find_page;
1461 goto readpage_error;
1464 if (!PageUptodate(page)) {
1465 error = lock_page_killable(page);
1466 if (unlikely(error))
1467 goto readpage_error;
1468 if (!PageUptodate(page)) {
1469 if (page->mapping == NULL) {
1471 * invalidate_mapping_pages got it
1473 unlock_page(page);
1474 page_cache_release(page);
1475 goto find_page;
1477 unlock_page(page);
1478 shrink_readahead_size_eio(filp, ra);
1479 error = -EIO;
1480 goto readpage_error;
1482 unlock_page(page);
1485 goto page_ok;
1487 readpage_error:
1488 /* UHHUH! A synchronous read error occurred. Report it */
1489 desc->error = error;
1490 page_cache_release(page);
1491 goto out;
1493 no_cached_page:
1495 * Ok, it wasn't cached, so we need to create a new
1496 * page..
1498 page = page_cache_alloc_cold(mapping);
1499 if (!page) {
1500 desc->error = -ENOMEM;
1501 goto out;
1503 error = add_to_page_cache_lru(page, mapping,
1504 index, GFP_KERNEL);
1505 if (error) {
1506 page_cache_release(page);
1507 if (error == -EEXIST)
1508 goto find_page;
1509 desc->error = error;
1510 goto out;
1512 goto readpage;
1515 out:
1516 ra->prev_pos = prev_index;
1517 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1518 ra->prev_pos |= prev_offset;
1520 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1521 file_accessed(filp);
1524 int file_read_actor(read_descriptor_t *desc, struct page *page,
1525 unsigned long offset, unsigned long size)
1527 char *kaddr;
1528 unsigned long left, count = desc->count;
1530 if (size > count)
1531 size = count;
1534 * Faults on the destination of a read are common, so do it before
1535 * taking the kmap.
1537 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1538 kaddr = kmap_atomic(page);
1539 left = __copy_to_user_inatomic(desc->arg.buf,
1540 kaddr + offset, size);
1541 kunmap_atomic(kaddr);
1542 if (left == 0)
1543 goto success;
1546 /* Do it the slow way */
1547 kaddr = kmap(page);
1548 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1549 kunmap(page);
1551 if (left) {
1552 size -= left;
1553 desc->error = -EFAULT;
1555 success:
1556 desc->count = count - size;
1557 desc->written += size;
1558 desc->arg.buf += size;
1559 return size;
1563 * Performs necessary checks before doing a write
1564 * @iov: io vector request
1565 * @nr_segs: number of segments in the iovec
1566 * @count: number of bytes to write
1567 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1569 * Adjust number of segments and amount of bytes to write (nr_segs should be
1570 * properly initialized first). Returns appropriate error code that caller
1571 * should return or zero in case that write should be allowed.
1573 int generic_segment_checks(const struct iovec *iov,
1574 unsigned long *nr_segs, size_t *count, int access_flags)
1576 unsigned long seg;
1577 size_t cnt = 0;
1578 for (seg = 0; seg < *nr_segs; seg++) {
1579 const struct iovec *iv = &iov[seg];
1582 * If any segment has a negative length, or the cumulative
1583 * length ever wraps negative then return -EINVAL.
1585 cnt += iv->iov_len;
1586 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1587 return -EINVAL;
1588 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1589 continue;
1590 if (seg == 0)
1591 return -EFAULT;
1592 *nr_segs = seg;
1593 cnt -= iv->iov_len; /* This segment is no good */
1594 break;
1596 *count = cnt;
1597 return 0;
1599 EXPORT_SYMBOL(generic_segment_checks);
1602 * generic_file_aio_read - generic filesystem read routine
1603 * @iocb: kernel I/O control block
1604 * @iov: io vector request
1605 * @nr_segs: number of segments in the iovec
1606 * @pos: current file position
1608 * This is the "read()" routine for all filesystems
1609 * that can use the page cache directly.
1611 ssize_t
1612 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1613 unsigned long nr_segs, loff_t pos)
1615 struct file *filp = iocb->ki_filp;
1616 ssize_t retval;
1617 unsigned long seg = 0;
1618 size_t count;
1619 loff_t *ppos = &iocb->ki_pos;
1621 count = 0;
1622 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1623 if (retval)
1624 return retval;
1626 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1627 if (filp->f_flags & O_DIRECT) {
1628 loff_t size;
1629 struct address_space *mapping;
1630 struct inode *inode;
1632 mapping = filp->f_mapping;
1633 inode = mapping->host;
1634 if (!count)
1635 goto out; /* skip atime */
1636 size = i_size_read(inode);
1637 if (pos < size) {
1638 retval = filemap_write_and_wait_range(mapping, pos,
1639 pos + iov_length(iov, nr_segs) - 1);
1640 if (!retval) {
1641 retval = mapping->a_ops->direct_IO(READ, iocb,
1642 iov, pos, nr_segs);
1644 if (retval > 0) {
1645 *ppos = pos + retval;
1646 count -= retval;
1650 * Btrfs can have a short DIO read if we encounter
1651 * compressed extents, so if there was an error, or if
1652 * we've already read everything we wanted to, or if
1653 * there was a short read because we hit EOF, go ahead
1654 * and return. Otherwise fallthrough to buffered io for
1655 * the rest of the read.
1657 if (retval < 0 || !count || *ppos >= size) {
1658 file_accessed(filp);
1659 goto out;
1664 count = retval;
1665 for (seg = 0; seg < nr_segs; seg++) {
1666 read_descriptor_t desc;
1667 loff_t offset = 0;
1670 * If we did a short DIO read we need to skip the section of the
1671 * iov that we've already read data into.
1673 if (count) {
1674 if (count > iov[seg].iov_len) {
1675 count -= iov[seg].iov_len;
1676 continue;
1678 offset = count;
1679 count = 0;
1682 desc.written = 0;
1683 desc.arg.buf = iov[seg].iov_base + offset;
1684 desc.count = iov[seg].iov_len - offset;
1685 if (desc.count == 0)
1686 continue;
1687 desc.error = 0;
1688 do_generic_file_read(filp, ppos, &desc, file_read_actor);
1689 retval += desc.written;
1690 if (desc.error) {
1691 retval = retval ?: desc.error;
1692 break;
1694 if (desc.count > 0)
1695 break;
1697 out:
1698 return retval;
1700 EXPORT_SYMBOL(generic_file_aio_read);
1702 #ifdef CONFIG_MMU
1704 * page_cache_read - adds requested page to the page cache if not already there
1705 * @file: file to read
1706 * @offset: page index
1708 * This adds the requested page to the page cache if it isn't already there,
1709 * and schedules an I/O to read in its contents from disk.
1711 static int page_cache_read(struct file *file, pgoff_t offset)
1713 struct address_space *mapping = file->f_mapping;
1714 struct page *page;
1715 int ret;
1717 do {
1718 page = page_cache_alloc_cold(mapping);
1719 if (!page)
1720 return -ENOMEM;
1722 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1723 if (ret == 0)
1724 ret = mapping->a_ops->readpage(file, page);
1725 else if (ret == -EEXIST)
1726 ret = 0; /* losing race to add is OK */
1728 page_cache_release(page);
1730 } while (ret == AOP_TRUNCATED_PAGE);
1732 return ret;
1735 #define MMAP_LOTSAMISS (100)
1738 * Synchronous readahead happens when we don't even find
1739 * a page in the page cache at all.
1741 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
1742 struct file_ra_state *ra,
1743 struct file *file,
1744 pgoff_t offset)
1746 unsigned long ra_pages;
1747 struct address_space *mapping = file->f_mapping;
1749 /* If we don't want any read-ahead, don't bother */
1750 if (vma->vm_flags & VM_RAND_READ)
1751 return;
1752 if (!ra->ra_pages)
1753 return;
1755 if (vma->vm_flags & VM_SEQ_READ) {
1756 page_cache_sync_readahead(mapping, ra, file, offset,
1757 ra->ra_pages);
1758 return;
1761 /* Avoid banging the cache line if not needed */
1762 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
1763 ra->mmap_miss++;
1766 * Do we miss much more than hit in this file? If so,
1767 * stop bothering with read-ahead. It will only hurt.
1769 if (ra->mmap_miss > MMAP_LOTSAMISS)
1770 return;
1773 * mmap read-around
1775 ra_pages = max_sane_readahead(ra->ra_pages);
1776 ra->start = max_t(long, 0, offset - ra_pages / 2);
1777 ra->size = ra_pages;
1778 ra->async_size = ra_pages / 4;
1779 ra_submit(ra, mapping, file);
1783 * Asynchronous readahead happens when we find the page and PG_readahead,
1784 * so we want to possibly extend the readahead further..
1786 static void do_async_mmap_readahead(struct vm_area_struct *vma,
1787 struct file_ra_state *ra,
1788 struct file *file,
1789 struct page *page,
1790 pgoff_t offset)
1792 struct address_space *mapping = file->f_mapping;
1794 /* If we don't want any read-ahead, don't bother */
1795 if (vma->vm_flags & VM_RAND_READ)
1796 return;
1797 if (ra->mmap_miss > 0)
1798 ra->mmap_miss--;
1799 if (PageReadahead(page))
1800 page_cache_async_readahead(mapping, ra, file,
1801 page, offset, ra->ra_pages);
1805 * filemap_fault - read in file data for page fault handling
1806 * @vma: vma in which the fault was taken
1807 * @vmf: struct vm_fault containing details of the fault
1809 * filemap_fault() is invoked via the vma operations vector for a
1810 * mapped memory region to read in file data during a page fault.
1812 * The goto's are kind of ugly, but this streamlines the normal case of having
1813 * it in the page cache, and handles the special cases reasonably without
1814 * having a lot of duplicated code.
1816 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1818 int error;
1819 struct file *file = vma->vm_file;
1820 struct address_space *mapping = file->f_mapping;
1821 struct file_ra_state *ra = &file->f_ra;
1822 struct inode *inode = mapping->host;
1823 pgoff_t offset = vmf->pgoff;
1824 struct page *page;
1825 pgoff_t size;
1826 int ret = 0;
1828 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1829 if (offset >= size)
1830 return VM_FAULT_SIGBUS;
1833 * Do we have something in the page cache already?
1835 page = find_get_page(mapping, offset);
1836 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
1838 * We found the page, so try async readahead before
1839 * waiting for the lock.
1841 do_async_mmap_readahead(vma, ra, file, page, offset);
1842 } else if (!page) {
1843 /* No page in the page cache at all */
1844 do_sync_mmap_readahead(vma, ra, file, offset);
1845 count_vm_event(PGMAJFAULT);
1846 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
1847 ret = VM_FAULT_MAJOR;
1848 retry_find:
1849 page = find_get_page(mapping, offset);
1850 if (!page)
1851 goto no_cached_page;
1854 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
1855 page_cache_release(page);
1856 return ret | VM_FAULT_RETRY;
1859 /* Did it get truncated? */
1860 if (unlikely(page->mapping != mapping)) {
1861 unlock_page(page);
1862 put_page(page);
1863 goto retry_find;
1865 VM_BUG_ON(page->index != offset);
1868 * We have a locked page in the page cache, now we need to check
1869 * that it's up-to-date. If not, it is going to be due to an error.
1871 if (unlikely(!PageUptodate(page)))
1872 goto page_not_uptodate;
1875 * Found the page and have a reference on it.
1876 * We must recheck i_size under page lock.
1878 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1879 if (unlikely(offset >= size)) {
1880 unlock_page(page);
1881 page_cache_release(page);
1882 return VM_FAULT_SIGBUS;
1885 vmf->page = page;
1886 return ret | VM_FAULT_LOCKED;
1888 no_cached_page:
1890 * We're only likely to ever get here if MADV_RANDOM is in
1891 * effect.
1893 error = page_cache_read(file, offset);
1896 * The page we want has now been added to the page cache.
1897 * In the unlikely event that someone removed it in the
1898 * meantime, we'll just come back here and read it again.
1900 if (error >= 0)
1901 goto retry_find;
1904 * An error return from page_cache_read can result if the
1905 * system is low on memory, or a problem occurs while trying
1906 * to schedule I/O.
1908 if (error == -ENOMEM)
1909 return VM_FAULT_OOM;
1910 return VM_FAULT_SIGBUS;
1912 page_not_uptodate:
1914 * Umm, take care of errors if the page isn't up-to-date.
1915 * Try to re-read it _once_. We do this synchronously,
1916 * because there really aren't any performance issues here
1917 * and we need to check for errors.
1919 ClearPageError(page);
1920 error = mapping->a_ops->readpage(file, page);
1921 if (!error) {
1922 wait_on_page_locked(page);
1923 if (!PageUptodate(page))
1924 error = -EIO;
1926 page_cache_release(page);
1928 if (!error || error == AOP_TRUNCATED_PAGE)
1929 goto retry_find;
1931 /* Things didn't work out. Return zero to tell the mm layer so. */
1932 shrink_readahead_size_eio(file, ra);
1933 return VM_FAULT_SIGBUS;
1935 EXPORT_SYMBOL(filemap_fault);
1937 int filemap_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
1939 struct page *page = vmf->page;
1940 struct inode *inode = file_inode(vma->vm_file);
1941 int ret = VM_FAULT_LOCKED;
1943 sb_start_pagefault(inode->i_sb);
1944 file_update_time(vma->vm_file);
1945 lock_page(page);
1946 if (page->mapping != inode->i_mapping) {
1947 unlock_page(page);
1948 ret = VM_FAULT_NOPAGE;
1949 goto out;
1952 * We mark the page dirty already here so that when freeze is in
1953 * progress, we are guaranteed that writeback during freezing will
1954 * see the dirty page and writeprotect it again.
1956 set_page_dirty(page);
1957 wait_for_stable_page(page);
1958 out:
1959 sb_end_pagefault(inode->i_sb);
1960 return ret;
1962 EXPORT_SYMBOL(filemap_page_mkwrite);
1964 const struct vm_operations_struct generic_file_vm_ops = {
1965 .fault = filemap_fault,
1966 .page_mkwrite = filemap_page_mkwrite,
1967 .remap_pages = generic_file_remap_pages,
1970 /* This is used for a general mmap of a disk file */
1972 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1974 struct address_space *mapping = file->f_mapping;
1976 if (!mapping->a_ops->readpage)
1977 return -ENOEXEC;
1978 file_accessed(file);
1979 vma->vm_ops = &generic_file_vm_ops;
1980 return 0;
1984 * This is for filesystems which do not implement ->writepage.
1986 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1988 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1989 return -EINVAL;
1990 return generic_file_mmap(file, vma);
1992 #else
1993 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1995 return -ENOSYS;
1997 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1999 return -ENOSYS;
2001 #endif /* CONFIG_MMU */
2003 EXPORT_SYMBOL(generic_file_mmap);
2004 EXPORT_SYMBOL(generic_file_readonly_mmap);
2006 static struct page *wait_on_page_read(struct page *page)
2008 if (!IS_ERR(page)) {
2009 wait_on_page_locked(page);
2010 if (!PageUptodate(page)) {
2011 page_cache_release(page);
2012 page = ERR_PTR(-EIO);
2015 return page;
2018 static struct page *__read_cache_page(struct address_space *mapping,
2019 pgoff_t index,
2020 int (*filler)(void *, struct page *),
2021 void *data,
2022 gfp_t gfp)
2024 struct page *page;
2025 int err;
2026 repeat:
2027 page = find_get_page(mapping, index);
2028 if (!page) {
2029 page = __page_cache_alloc(gfp | __GFP_COLD);
2030 if (!page)
2031 return ERR_PTR(-ENOMEM);
2032 err = add_to_page_cache_lru(page, mapping, index, gfp);
2033 if (unlikely(err)) {
2034 page_cache_release(page);
2035 if (err == -EEXIST)
2036 goto repeat;
2037 /* Presumably ENOMEM for radix tree node */
2038 return ERR_PTR(err);
2040 err = filler(data, page);
2041 if (err < 0) {
2042 page_cache_release(page);
2043 page = ERR_PTR(err);
2044 } else {
2045 page = wait_on_page_read(page);
2048 return page;
2051 static struct page *do_read_cache_page(struct address_space *mapping,
2052 pgoff_t index,
2053 int (*filler)(void *, struct page *),
2054 void *data,
2055 gfp_t gfp)
2058 struct page *page;
2059 int err;
2061 retry:
2062 page = __read_cache_page(mapping, index, filler, data, gfp);
2063 if (IS_ERR(page))
2064 return page;
2065 if (PageUptodate(page))
2066 goto out;
2068 lock_page(page);
2069 if (!page->mapping) {
2070 unlock_page(page);
2071 page_cache_release(page);
2072 goto retry;
2074 if (PageUptodate(page)) {
2075 unlock_page(page);
2076 goto out;
2078 err = filler(data, page);
2079 if (err < 0) {
2080 page_cache_release(page);
2081 return ERR_PTR(err);
2082 } else {
2083 page = wait_on_page_read(page);
2084 if (IS_ERR(page))
2085 return page;
2087 out:
2088 mark_page_accessed(page);
2089 return page;
2093 * read_cache_page - read into page cache, fill it if needed
2094 * @mapping: the page's address_space
2095 * @index: the page index
2096 * @filler: function to perform the read
2097 * @data: first arg to filler(data, page) function, often left as NULL
2099 * Read into the page cache. If a page already exists, and PageUptodate() is
2100 * not set, try to fill the page and wait for it to become unlocked.
2102 * If the page does not get brought uptodate, return -EIO.
2104 struct page *read_cache_page(struct address_space *mapping,
2105 pgoff_t index,
2106 int (*filler)(void *, struct page *),
2107 void *data)
2109 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2111 EXPORT_SYMBOL(read_cache_page);
2114 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2115 * @mapping: the page's address_space
2116 * @index: the page index
2117 * @gfp: the page allocator flags to use if allocating
2119 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2120 * any new page allocations done using the specified allocation flags.
2122 * If the page does not get brought uptodate, return -EIO.
2124 struct page *read_cache_page_gfp(struct address_space *mapping,
2125 pgoff_t index,
2126 gfp_t gfp)
2128 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2130 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2132 EXPORT_SYMBOL(read_cache_page_gfp);
2134 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
2135 const struct iovec *iov, size_t base, size_t bytes)
2137 size_t copied = 0, left = 0;
2139 while (bytes) {
2140 char __user *buf = iov->iov_base + base;
2141 int copy = min(bytes, iov->iov_len - base);
2143 base = 0;
2144 left = __copy_from_user_inatomic(vaddr, buf, copy);
2145 copied += copy;
2146 bytes -= copy;
2147 vaddr += copy;
2148 iov++;
2150 if (unlikely(left))
2151 break;
2153 return copied - left;
2157 * Copy as much as we can into the page and return the number of bytes which
2158 * were successfully copied. If a fault is encountered then return the number of
2159 * bytes which were copied.
2161 size_t iov_iter_copy_from_user_atomic(struct page *page,
2162 struct iov_iter *i, unsigned long offset, size_t bytes)
2164 char *kaddr;
2165 size_t copied;
2167 kaddr = kmap_atomic(page);
2168 if (likely(i->nr_segs == 1)) {
2169 int left;
2170 char __user *buf = i->iov->iov_base + i->iov_offset;
2171 left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
2172 copied = bytes - left;
2173 } else {
2174 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2175 i->iov, i->iov_offset, bytes);
2177 kunmap_atomic(kaddr);
2179 return copied;
2181 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
2184 * This has the same sideeffects and return value as
2185 * iov_iter_copy_from_user_atomic().
2186 * The difference is that it attempts to resolve faults.
2187 * Page must not be locked.
2189 size_t iov_iter_copy_from_user(struct page *page,
2190 struct iov_iter *i, unsigned long offset, size_t bytes)
2192 char *kaddr;
2193 size_t copied;
2195 kaddr = kmap(page);
2196 if (likely(i->nr_segs == 1)) {
2197 int left;
2198 char __user *buf = i->iov->iov_base + i->iov_offset;
2199 left = __copy_from_user(kaddr + offset, buf, bytes);
2200 copied = bytes - left;
2201 } else {
2202 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2203 i->iov, i->iov_offset, bytes);
2205 kunmap(page);
2206 return copied;
2208 EXPORT_SYMBOL(iov_iter_copy_from_user);
2210 void iov_iter_advance(struct iov_iter *i, size_t bytes)
2212 BUG_ON(i->count < bytes);
2214 if (likely(i->nr_segs == 1)) {
2215 i->iov_offset += bytes;
2216 i->count -= bytes;
2217 } else {
2218 const struct iovec *iov = i->iov;
2219 size_t base = i->iov_offset;
2220 unsigned long nr_segs = i->nr_segs;
2223 * The !iov->iov_len check ensures we skip over unlikely
2224 * zero-length segments (without overruning the iovec).
2226 while (bytes || unlikely(i->count && !iov->iov_len)) {
2227 int copy;
2229 copy = min(bytes, iov->iov_len - base);
2230 BUG_ON(!i->count || i->count < copy);
2231 i->count -= copy;
2232 bytes -= copy;
2233 base += copy;
2234 if (iov->iov_len == base) {
2235 iov++;
2236 nr_segs--;
2237 base = 0;
2240 i->iov = iov;
2241 i->iov_offset = base;
2242 i->nr_segs = nr_segs;
2245 EXPORT_SYMBOL(iov_iter_advance);
2248 * Fault in the first iovec of the given iov_iter, to a maximum length
2249 * of bytes. Returns 0 on success, or non-zero if the memory could not be
2250 * accessed (ie. because it is an invalid address).
2252 * writev-intensive code may want this to prefault several iovecs -- that
2253 * would be possible (callers must not rely on the fact that _only_ the
2254 * first iovec will be faulted with the current implementation).
2256 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
2258 char __user *buf = i->iov->iov_base + i->iov_offset;
2259 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
2260 return fault_in_pages_readable(buf, bytes);
2262 EXPORT_SYMBOL(iov_iter_fault_in_readable);
2265 * Return the count of just the current iov_iter segment.
2267 size_t iov_iter_single_seg_count(const struct iov_iter *i)
2269 const struct iovec *iov = i->iov;
2270 if (i->nr_segs == 1)
2271 return i->count;
2272 else
2273 return min(i->count, iov->iov_len - i->iov_offset);
2275 EXPORT_SYMBOL(iov_iter_single_seg_count);
2278 * Performs necessary checks before doing a write
2280 * Can adjust writing position or amount of bytes to write.
2281 * Returns appropriate error code that caller should return or
2282 * zero in case that write should be allowed.
2284 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
2286 struct inode *inode = file->f_mapping->host;
2287 unsigned long limit = rlimit(RLIMIT_FSIZE);
2289 if (unlikely(*pos < 0))
2290 return -EINVAL;
2292 if (!isblk) {
2293 /* FIXME: this is for backwards compatibility with 2.4 */
2294 if (file->f_flags & O_APPEND)
2295 *pos = i_size_read(inode);
2297 if (limit != RLIM_INFINITY) {
2298 if (*pos >= limit) {
2299 send_sig(SIGXFSZ, current, 0);
2300 return -EFBIG;
2302 if (*count > limit - (typeof(limit))*pos) {
2303 *count = limit - (typeof(limit))*pos;
2309 * LFS rule
2311 if (unlikely(*pos + *count > MAX_NON_LFS &&
2312 !(file->f_flags & O_LARGEFILE))) {
2313 if (*pos >= MAX_NON_LFS) {
2314 return -EFBIG;
2316 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
2317 *count = MAX_NON_LFS - (unsigned long)*pos;
2322 * Are we about to exceed the fs block limit ?
2324 * If we have written data it becomes a short write. If we have
2325 * exceeded without writing data we send a signal and return EFBIG.
2326 * Linus frestrict idea will clean these up nicely..
2328 if (likely(!isblk)) {
2329 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
2330 if (*count || *pos > inode->i_sb->s_maxbytes) {
2331 return -EFBIG;
2333 /* zero-length writes at ->s_maxbytes are OK */
2336 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
2337 *count = inode->i_sb->s_maxbytes - *pos;
2338 } else {
2339 #ifdef CONFIG_BLOCK
2340 loff_t isize;
2341 if (bdev_read_only(I_BDEV(inode)))
2342 return -EPERM;
2343 isize = i_size_read(inode);
2344 if (*pos >= isize) {
2345 if (*count || *pos > isize)
2346 return -ENOSPC;
2349 if (*pos + *count > isize)
2350 *count = isize - *pos;
2351 #else
2352 return -EPERM;
2353 #endif
2355 return 0;
2357 EXPORT_SYMBOL(generic_write_checks);
2359 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2360 loff_t pos, unsigned len, unsigned flags,
2361 struct page **pagep, void **fsdata)
2363 const struct address_space_operations *aops = mapping->a_ops;
2365 return aops->write_begin(file, mapping, pos, len, flags,
2366 pagep, fsdata);
2368 EXPORT_SYMBOL(pagecache_write_begin);
2370 int pagecache_write_end(struct file *file, struct address_space *mapping,
2371 loff_t pos, unsigned len, unsigned copied,
2372 struct page *page, void *fsdata)
2374 const struct address_space_operations *aops = mapping->a_ops;
2376 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2378 EXPORT_SYMBOL(pagecache_write_end);
2380 ssize_t
2381 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
2382 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
2383 size_t count, size_t ocount)
2385 struct file *file = iocb->ki_filp;
2386 struct address_space *mapping = file->f_mapping;
2387 struct inode *inode = mapping->host;
2388 ssize_t written;
2389 size_t write_len;
2390 pgoff_t end;
2392 if (count != ocount)
2393 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
2395 write_len = iov_length(iov, *nr_segs);
2396 end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
2398 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2399 if (written)
2400 goto out;
2403 * After a write we want buffered reads to be sure to go to disk to get
2404 * the new data. We invalidate clean cached page from the region we're
2405 * about to write. We do this *before* the write so that we can return
2406 * without clobbering -EIOCBQUEUED from ->direct_IO().
2408 if (mapping->nrpages) {
2409 written = invalidate_inode_pages2_range(mapping,
2410 pos >> PAGE_CACHE_SHIFT, end);
2412 * If a page can not be invalidated, return 0 to fall back
2413 * to buffered write.
2415 if (written) {
2416 if (written == -EBUSY)
2417 return 0;
2418 goto out;
2422 written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
2425 * Finally, try again to invalidate clean pages which might have been
2426 * cached by non-direct readahead, or faulted in by get_user_pages()
2427 * if the source of the write was an mmap'ed region of the file
2428 * we're writing. Either one is a pretty crazy thing to do,
2429 * so we don't support it 100%. If this invalidation
2430 * fails, tough, the write still worked...
2432 if (mapping->nrpages) {
2433 invalidate_inode_pages2_range(mapping,
2434 pos >> PAGE_CACHE_SHIFT, end);
2437 if (written > 0) {
2438 pos += written;
2439 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2440 i_size_write(inode, pos);
2441 mark_inode_dirty(inode);
2443 *ppos = pos;
2445 out:
2446 return written;
2448 EXPORT_SYMBOL(generic_file_direct_write);
2451 * Find or create a page at the given pagecache position. Return the locked
2452 * page. This function is specifically for buffered writes.
2454 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2455 pgoff_t index, unsigned flags)
2457 struct page *page;
2458 int fgp_flags = FGP_LOCK|FGP_ACCESSED|FGP_WRITE|FGP_CREAT;
2460 if (flags & AOP_FLAG_NOFS)
2461 fgp_flags |= FGP_NOFS;
2463 page = pagecache_get_page(mapping, index, fgp_flags,
2464 mapping_gfp_mask(mapping));
2465 if (page)
2466 wait_for_stable_page(page);
2468 return page;
2470 EXPORT_SYMBOL(grab_cache_page_write_begin);
2472 static ssize_t generic_perform_write(struct file *file,
2473 struct iov_iter *i, loff_t pos)
2475 struct address_space *mapping = file->f_mapping;
2476 const struct address_space_operations *a_ops = mapping->a_ops;
2477 long status = 0;
2478 ssize_t written = 0;
2479 unsigned int flags = 0;
2482 * Copies from kernel address space cannot fail (NFSD is a big user).
2484 if (segment_eq(get_fs(), KERNEL_DS))
2485 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2487 do {
2488 struct page *page;
2489 unsigned long offset; /* Offset into pagecache page */
2490 unsigned long bytes; /* Bytes to write to page */
2491 size_t copied; /* Bytes copied from user */
2492 void *fsdata;
2494 offset = (pos & (PAGE_CACHE_SIZE - 1));
2495 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2496 iov_iter_count(i));
2498 again:
2500 * Bring in the user page that we will copy from _first_.
2501 * Otherwise there's a nasty deadlock on copying from the
2502 * same page as we're writing to, without it being marked
2503 * up-to-date.
2505 * Not only is this an optimisation, but it is also required
2506 * to check that the address is actually valid, when atomic
2507 * usercopies are used, below.
2509 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2510 status = -EFAULT;
2511 break;
2514 if (fatal_signal_pending(current)) {
2515 status = -EINTR;
2516 break;
2519 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2520 &page, &fsdata);
2521 if (unlikely(status < 0))
2522 break;
2524 if (mapping_writably_mapped(mapping))
2525 flush_dcache_page(page);
2527 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2528 flush_dcache_page(page);
2530 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2531 page, fsdata);
2532 if (unlikely(status < 0))
2533 break;
2534 copied = status;
2536 cond_resched();
2538 iov_iter_advance(i, copied);
2539 if (unlikely(copied == 0)) {
2541 * If we were unable to copy any data at all, we must
2542 * fall back to a single segment length write.
2544 * If we didn't fallback here, we could livelock
2545 * because not all segments in the iov can be copied at
2546 * once without a pagefault.
2548 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2549 iov_iter_single_seg_count(i));
2550 goto again;
2552 pos += copied;
2553 written += copied;
2555 balance_dirty_pages_ratelimited(mapping);
2556 } while (iov_iter_count(i));
2558 return written ? written : status;
2561 ssize_t
2562 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2563 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2564 size_t count, ssize_t written)
2566 struct file *file = iocb->ki_filp;
2567 ssize_t status;
2568 struct iov_iter i;
2570 iov_iter_init(&i, iov, nr_segs, count, written);
2571 status = generic_perform_write(file, &i, pos);
2573 if (likely(status >= 0)) {
2574 written += status;
2575 *ppos = pos + status;
2578 return written ? written : status;
2580 EXPORT_SYMBOL(generic_file_buffered_write);
2583 * __generic_file_aio_write - write data to a file
2584 * @iocb: IO state structure (file, offset, etc.)
2585 * @iov: vector with data to write
2586 * @nr_segs: number of segments in the vector
2587 * @ppos: position where to write
2589 * This function does all the work needed for actually writing data to a
2590 * file. It does all basic checks, removes SUID from the file, updates
2591 * modification times and calls proper subroutines depending on whether we
2592 * do direct IO or a standard buffered write.
2594 * It expects i_mutex to be grabbed unless we work on a block device or similar
2595 * object which does not need locking at all.
2597 * This function does *not* take care of syncing data in case of O_SYNC write.
2598 * A caller has to handle it. This is mainly due to the fact that we want to
2599 * avoid syncing under i_mutex.
2601 ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2602 unsigned long nr_segs, loff_t *ppos)
2604 struct file *file = iocb->ki_filp;
2605 struct address_space * mapping = file->f_mapping;
2606 size_t ocount; /* original count */
2607 size_t count; /* after file limit checks */
2608 struct inode *inode = mapping->host;
2609 loff_t pos;
2610 ssize_t written;
2611 ssize_t err;
2613 ocount = 0;
2614 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2615 if (err)
2616 return err;
2618 count = ocount;
2619 pos = *ppos;
2621 /* We can write back this queue in page reclaim */
2622 current->backing_dev_info = mapping->backing_dev_info;
2623 written = 0;
2625 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2626 if (err)
2627 goto out;
2629 if (count == 0)
2630 goto out;
2632 err = file_remove_suid(file);
2633 if (err)
2634 goto out;
2636 err = file_update_time(file);
2637 if (err)
2638 goto out;
2640 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2641 if (unlikely(file->f_flags & O_DIRECT)) {
2642 loff_t endbyte;
2643 ssize_t written_buffered;
2645 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2646 ppos, count, ocount);
2647 if (written < 0 || written == count)
2648 goto out;
2650 * direct-io write to a hole: fall through to buffered I/O
2651 * for completing the rest of the request.
2653 pos += written;
2654 count -= written;
2655 written_buffered = generic_file_buffered_write(iocb, iov,
2656 nr_segs, pos, ppos, count,
2657 written);
2659 * If generic_file_buffered_write() retuned a synchronous error
2660 * then we want to return the number of bytes which were
2661 * direct-written, or the error code if that was zero. Note
2662 * that this differs from normal direct-io semantics, which
2663 * will return -EFOO even if some bytes were written.
2665 if (written_buffered < 0) {
2666 err = written_buffered;
2667 goto out;
2671 * We need to ensure that the page cache pages are written to
2672 * disk and invalidated to preserve the expected O_DIRECT
2673 * semantics.
2675 endbyte = pos + written_buffered - written - 1;
2676 err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
2677 if (err == 0) {
2678 written = written_buffered;
2679 invalidate_mapping_pages(mapping,
2680 pos >> PAGE_CACHE_SHIFT,
2681 endbyte >> PAGE_CACHE_SHIFT);
2682 } else {
2684 * We don't know how much we wrote, so just return
2685 * the number of bytes which were direct-written
2688 } else {
2689 written = generic_file_buffered_write(iocb, iov, nr_segs,
2690 pos, ppos, count, written);
2692 out:
2693 current->backing_dev_info = NULL;
2694 return written ? written : err;
2696 EXPORT_SYMBOL(__generic_file_aio_write);
2699 * generic_file_aio_write - write data to a file
2700 * @iocb: IO state structure
2701 * @iov: vector with data to write
2702 * @nr_segs: number of segments in the vector
2703 * @pos: position in file where to write
2705 * This is a wrapper around __generic_file_aio_write() to be used by most
2706 * filesystems. It takes care of syncing the file in case of O_SYNC file
2707 * and acquires i_mutex as needed.
2709 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2710 unsigned long nr_segs, loff_t pos)
2712 struct file *file = iocb->ki_filp;
2713 struct inode *inode = file->f_mapping->host;
2714 ssize_t ret;
2716 BUG_ON(iocb->ki_pos != pos);
2718 mutex_lock(&inode->i_mutex);
2719 ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
2720 mutex_unlock(&inode->i_mutex);
2722 if (ret > 0) {
2723 ssize_t err;
2725 err = generic_write_sync(file, iocb->ki_pos - ret, ret);
2726 if (err < 0)
2727 ret = err;
2729 return ret;
2731 EXPORT_SYMBOL(generic_file_aio_write);
2734 * try_to_release_page() - release old fs-specific metadata on a page
2736 * @page: the page which the kernel is trying to free
2737 * @gfp_mask: memory allocation flags (and I/O mode)
2739 * The address_space is to try to release any data against the page
2740 * (presumably at page->private). If the release was successful, return `1'.
2741 * Otherwise return zero.
2743 * This may also be called if PG_fscache is set on a page, indicating that the
2744 * page is known to the local caching routines.
2746 * The @gfp_mask argument specifies whether I/O may be performed to release
2747 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
2750 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2752 struct address_space * const mapping = page->mapping;
2754 BUG_ON(!PageLocked(page));
2755 if (PageWriteback(page))
2756 return 0;
2758 if (mapping && mapping->a_ops->releasepage)
2759 return mapping->a_ops->releasepage(page, gfp_mask);
2760 return try_to_free_buffers(page);
2763 EXPORT_SYMBOL(try_to_release_page);