4 * Copyright (C) 1994-1999 Linus Torvalds
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>
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>
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>
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 */
49 * Shared mappings implemented 30.11.1994. It's not fully working yet,
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>
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
69 * ->i_mmap_mutex (truncate->unmap_mapping_range)
73 * ->page_table_lock or pte_lock (various, mainly in memory.c)
74 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
77 * ->lock_page (access_process_vm)
79 * ->i_mutex (generic_file_buffered_write)
80 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
83 * sb_lock (fs/fs-writeback.c)
84 * ->mapping->tree_lock (__sync_single_inode)
87 * ->anon_vma.lock (vma_adjust)
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)
107 * ->tasklist_lock (memory_failure, collect_procs_ao)
110 static void page_cache_tree_delete(struct address_space
*mapping
,
111 struct page
*page
, void *shadow
)
113 struct radix_tree_node
*node
;
119 VM_BUG_ON(!PageLocked(page
));
121 __radix_tree_lookup(&mapping
->page_tree
, page
->index
, &node
, &slot
);
124 mapping
->nrshadows
++;
126 * Make sure the nrshadows update is committed before
127 * the nrpages update so that final truncate racing
128 * with reclaim does not see both counters 0 at the
129 * same time and miss a shadow entry.
136 /* Clear direct pointer tags in root node */
137 mapping
->page_tree
.gfp_mask
&= __GFP_BITS_MASK
;
138 radix_tree_replace_slot(slot
, shadow
);
142 /* Clear tree tags for the removed page */
144 offset
= index
& RADIX_TREE_MAP_MASK
;
145 for (tag
= 0; tag
< RADIX_TREE_MAX_TAGS
; tag
++) {
146 if (test_bit(offset
, node
->tags
[tag
]))
147 radix_tree_tag_clear(&mapping
->page_tree
, index
, tag
);
150 /* Delete page, swap shadow entry */
151 radix_tree_replace_slot(slot
, shadow
);
152 workingset_node_pages_dec(node
);
154 workingset_node_shadows_inc(node
);
156 if (__radix_tree_delete_node(&mapping
->page_tree
, node
))
160 * Track node that only contains shadow entries.
162 * Avoid acquiring the list_lru lock if already tracked. The
163 * list_empty() test is safe as node->private_list is
164 * protected by mapping->tree_lock.
166 if (!workingset_node_pages(node
) &&
167 list_empty(&node
->private_list
)) {
168 node
->private_data
= mapping
;
169 list_lru_add(&workingset_shadow_nodes
, &node
->private_list
);
174 * Delete a page from the page cache and free it. Caller has to make
175 * sure the page is locked and that nobody else uses it - or that usage
176 * is safe. The caller must hold the mapping's tree_lock.
178 void __delete_from_page_cache(struct page
*page
, void *shadow
)
180 struct address_space
*mapping
= page
->mapping
;
182 trace_mm_filemap_delete_from_page_cache(page
);
184 * if we're uptodate, flush out into the cleancache, otherwise
185 * invalidate any existing cleancache entries. We can't leave
186 * stale data around in the cleancache once our page is gone
188 if (PageUptodate(page
) && PageMappedToDisk(page
))
189 cleancache_put_page(page
);
191 cleancache_invalidate_page(mapping
, page
);
193 page_cache_tree_delete(mapping
, page
, shadow
);
195 page
->mapping
= NULL
;
196 /* Leave page->index set: truncation lookup relies upon it */
198 __dec_zone_page_state(page
, NR_FILE_PAGES
);
199 if (PageSwapBacked(page
))
200 __dec_zone_page_state(page
, NR_SHMEM
);
201 BUG_ON(page_mapped(page
));
204 * Some filesystems seem to re-dirty the page even after
205 * the VM has canceled the dirty bit (eg ext3 journaling).
207 * Fix it up by doing a final dirty accounting check after
208 * having removed the page entirely.
210 if (PageDirty(page
) && mapping_cap_account_dirty(mapping
)) {
211 dec_zone_page_state(page
, NR_FILE_DIRTY
);
212 dec_bdi_stat(mapping
->backing_dev_info
, BDI_RECLAIMABLE
);
217 * delete_from_page_cache - delete page from page cache
218 * @page: the page which the kernel is trying to remove from page cache
220 * This must be called only on pages that have been verified to be in the page
221 * cache and locked. It will never put the page into the free list, the caller
222 * has a reference on the page.
224 void delete_from_page_cache(struct page
*page
)
226 struct address_space
*mapping
= page
->mapping
;
227 void (*freepage
)(struct page
*);
229 BUG_ON(!PageLocked(page
));
231 freepage
= mapping
->a_ops
->freepage
;
232 spin_lock_irq(&mapping
->tree_lock
);
233 __delete_from_page_cache(page
, NULL
);
234 spin_unlock_irq(&mapping
->tree_lock
);
235 mem_cgroup_uncharge_cache_page(page
);
239 page_cache_release(page
);
241 EXPORT_SYMBOL(delete_from_page_cache
);
243 static int sleep_on_page(void *word
)
249 static int sleep_on_page_killable(void *word
)
252 return fatal_signal_pending(current
) ? -EINTR
: 0;
255 static int filemap_check_errors(struct address_space
*mapping
)
258 /* Check for outstanding write errors */
259 if (test_and_clear_bit(AS_ENOSPC
, &mapping
->flags
))
261 if (test_and_clear_bit(AS_EIO
, &mapping
->flags
))
267 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
268 * @mapping: address space structure to write
269 * @start: offset in bytes where the range starts
270 * @end: offset in bytes where the range ends (inclusive)
271 * @sync_mode: enable synchronous operation
273 * Start writeback against all of a mapping's dirty pages that lie
274 * within the byte offsets <start, end> inclusive.
276 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
277 * opposed to a regular memory cleansing writeback. The difference between
278 * these two operations is that if a dirty page/buffer is encountered, it must
279 * be waited upon, and not just skipped over.
281 int __filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
282 loff_t end
, int sync_mode
)
285 struct writeback_control wbc
= {
286 .sync_mode
= sync_mode
,
287 .nr_to_write
= LONG_MAX
,
288 .range_start
= start
,
292 if (!mapping_cap_writeback_dirty(mapping
))
295 ret
= do_writepages(mapping
, &wbc
);
299 static inline int __filemap_fdatawrite(struct address_space
*mapping
,
302 return __filemap_fdatawrite_range(mapping
, 0, LLONG_MAX
, sync_mode
);
305 int filemap_fdatawrite(struct address_space
*mapping
)
307 return __filemap_fdatawrite(mapping
, WB_SYNC_ALL
);
309 EXPORT_SYMBOL(filemap_fdatawrite
);
311 int filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
314 return __filemap_fdatawrite_range(mapping
, start
, end
, WB_SYNC_ALL
);
316 EXPORT_SYMBOL(filemap_fdatawrite_range
);
319 * filemap_flush - mostly a non-blocking flush
320 * @mapping: target address_space
322 * This is a mostly non-blocking flush. Not suitable for data-integrity
323 * purposes - I/O may not be started against all dirty pages.
325 int filemap_flush(struct address_space
*mapping
)
327 return __filemap_fdatawrite(mapping
, WB_SYNC_NONE
);
329 EXPORT_SYMBOL(filemap_flush
);
332 * filemap_fdatawait_range - wait for writeback to complete
333 * @mapping: address space structure to wait for
334 * @start_byte: offset in bytes where the range starts
335 * @end_byte: offset in bytes where the range ends (inclusive)
337 * Walk the list of under-writeback pages of the given address space
338 * in the given range and wait for all of them.
340 int filemap_fdatawait_range(struct address_space
*mapping
, loff_t start_byte
,
343 pgoff_t index
= start_byte
>> PAGE_CACHE_SHIFT
;
344 pgoff_t end
= end_byte
>> PAGE_CACHE_SHIFT
;
349 if (end_byte
< start_byte
)
352 pagevec_init(&pvec
, 0);
353 while ((index
<= end
) &&
354 (nr_pages
= pagevec_lookup_tag(&pvec
, mapping
, &index
,
355 PAGECACHE_TAG_WRITEBACK
,
356 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
-1) + 1)) != 0) {
359 for (i
= 0; i
< nr_pages
; i
++) {
360 struct page
*page
= pvec
.pages
[i
];
362 /* until radix tree lookup accepts end_index */
363 if (page
->index
> end
)
366 wait_on_page_writeback(page
);
367 if (TestClearPageError(page
))
370 pagevec_release(&pvec
);
374 ret2
= filemap_check_errors(mapping
);
380 EXPORT_SYMBOL(filemap_fdatawait_range
);
383 * filemap_fdatawait - wait for all under-writeback pages to complete
384 * @mapping: address space structure to wait for
386 * Walk the list of under-writeback pages of the given address space
387 * and wait for all of them.
389 int filemap_fdatawait(struct address_space
*mapping
)
391 loff_t i_size
= i_size_read(mapping
->host
);
396 return filemap_fdatawait_range(mapping
, 0, i_size
- 1);
398 EXPORT_SYMBOL(filemap_fdatawait
);
400 int filemap_write_and_wait(struct address_space
*mapping
)
404 if (mapping
->nrpages
) {
405 err
= filemap_fdatawrite(mapping
);
407 * Even if the above returned error, the pages may be
408 * written partially (e.g. -ENOSPC), so we wait for it.
409 * But the -EIO is special case, it may indicate the worst
410 * thing (e.g. bug) happened, so we avoid waiting for it.
413 int err2
= filemap_fdatawait(mapping
);
418 err
= filemap_check_errors(mapping
);
422 EXPORT_SYMBOL(filemap_write_and_wait
);
425 * filemap_write_and_wait_range - write out & wait on a file range
426 * @mapping: the address_space for the pages
427 * @lstart: offset in bytes where the range starts
428 * @lend: offset in bytes where the range ends (inclusive)
430 * Write out and wait upon file offsets lstart->lend, inclusive.
432 * Note that `lend' is inclusive (describes the last byte to be written) so
433 * that this function can be used to write to the very end-of-file (end = -1).
435 int filemap_write_and_wait_range(struct address_space
*mapping
,
436 loff_t lstart
, loff_t lend
)
440 if (mapping
->nrpages
) {
441 err
= __filemap_fdatawrite_range(mapping
, lstart
, lend
,
443 /* See comment of filemap_write_and_wait() */
445 int err2
= filemap_fdatawait_range(mapping
,
451 err
= filemap_check_errors(mapping
);
455 EXPORT_SYMBOL(filemap_write_and_wait_range
);
458 * replace_page_cache_page - replace a pagecache page with a new one
459 * @old: page to be replaced
460 * @new: page to replace with
461 * @gfp_mask: allocation mode
463 * This function replaces a page in the pagecache with a new one. On
464 * success it acquires the pagecache reference for the new page and
465 * drops it for the old page. Both the old and new pages must be
466 * locked. This function does not add the new page to the LRU, the
467 * caller must do that.
469 * The remove + add is atomic. The only way this function can fail is
470 * memory allocation failure.
472 int replace_page_cache_page(struct page
*old
, struct page
*new, gfp_t gfp_mask
)
476 VM_BUG_ON_PAGE(!PageLocked(old
), old
);
477 VM_BUG_ON_PAGE(!PageLocked(new), new);
478 VM_BUG_ON_PAGE(new->mapping
, new);
480 error
= radix_tree_preload(gfp_mask
& ~__GFP_HIGHMEM
);
482 struct address_space
*mapping
= old
->mapping
;
483 void (*freepage
)(struct page
*);
485 pgoff_t offset
= old
->index
;
486 freepage
= mapping
->a_ops
->freepage
;
489 new->mapping
= mapping
;
492 spin_lock_irq(&mapping
->tree_lock
);
493 __delete_from_page_cache(old
, NULL
);
494 error
= radix_tree_insert(&mapping
->page_tree
, offset
, new);
497 __inc_zone_page_state(new, NR_FILE_PAGES
);
498 if (PageSwapBacked(new))
499 __inc_zone_page_state(new, NR_SHMEM
);
500 spin_unlock_irq(&mapping
->tree_lock
);
501 /* mem_cgroup codes must not be called under tree_lock */
502 mem_cgroup_replace_page_cache(old
, new);
503 radix_tree_preload_end();
506 page_cache_release(old
);
511 EXPORT_SYMBOL_GPL(replace_page_cache_page
);
513 static int page_cache_tree_insert(struct address_space
*mapping
,
514 struct page
*page
, void **shadowp
)
516 struct radix_tree_node
*node
;
520 error
= __radix_tree_create(&mapping
->page_tree
, page
->index
,
527 p
= radix_tree_deref_slot_protected(slot
, &mapping
->tree_lock
);
528 if (!radix_tree_exceptional_entry(p
))
532 mapping
->nrshadows
--;
534 workingset_node_shadows_dec(node
);
536 radix_tree_replace_slot(slot
, page
);
539 workingset_node_pages_inc(node
);
541 * Don't track node that contains actual pages.
543 * Avoid acquiring the list_lru lock if already
544 * untracked. The list_empty() test is safe as
545 * node->private_list is protected by
546 * mapping->tree_lock.
548 if (!list_empty(&node
->private_list
))
549 list_lru_del(&workingset_shadow_nodes
,
550 &node
->private_list
);
555 static int __add_to_page_cache_locked(struct page
*page
,
556 struct address_space
*mapping
,
557 pgoff_t offset
, gfp_t gfp_mask
,
562 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
563 VM_BUG_ON_PAGE(PageSwapBacked(page
), page
);
565 error
= mem_cgroup_cache_charge(page
, current
->mm
,
566 gfp_mask
& GFP_RECLAIM_MASK
);
570 error
= radix_tree_maybe_preload(gfp_mask
& ~__GFP_HIGHMEM
);
572 mem_cgroup_uncharge_cache_page(page
);
576 page_cache_get(page
);
577 page
->mapping
= mapping
;
578 page
->index
= offset
;
580 spin_lock_irq(&mapping
->tree_lock
);
581 error
= page_cache_tree_insert(mapping
, page
, shadowp
);
582 radix_tree_preload_end();
585 __inc_zone_page_state(page
, NR_FILE_PAGES
);
586 spin_unlock_irq(&mapping
->tree_lock
);
587 trace_mm_filemap_add_to_page_cache(page
);
590 page
->mapping
= NULL
;
591 /* Leave page->index set: truncation relies upon it */
592 spin_unlock_irq(&mapping
->tree_lock
);
593 mem_cgroup_uncharge_cache_page(page
);
594 page_cache_release(page
);
599 * add_to_page_cache_locked - add a locked page to the pagecache
601 * @mapping: the page's address_space
602 * @offset: page index
603 * @gfp_mask: page allocation mode
605 * This function is used to add a page to the pagecache. It must be locked.
606 * This function does not add the page to the LRU. The caller must do that.
608 int add_to_page_cache_locked(struct page
*page
, struct address_space
*mapping
,
609 pgoff_t offset
, gfp_t gfp_mask
)
611 return __add_to_page_cache_locked(page
, mapping
, offset
,
614 EXPORT_SYMBOL(add_to_page_cache_locked
);
616 int add_to_page_cache_lru(struct page
*page
, struct address_space
*mapping
,
617 pgoff_t offset
, gfp_t gfp_mask
)
622 __set_page_locked(page
);
623 ret
= __add_to_page_cache_locked(page
, mapping
, offset
,
626 __clear_page_locked(page
);
629 * The page might have been evicted from cache only
630 * recently, in which case it should be activated like
631 * any other repeatedly accessed page.
633 if (shadow
&& workingset_refault(shadow
)) {
635 workingset_activation(page
);
637 ClearPageActive(page
);
642 EXPORT_SYMBOL_GPL(add_to_page_cache_lru
);
645 struct page
*__page_cache_alloc(gfp_t gfp
)
650 if (cpuset_do_page_mem_spread()) {
651 unsigned int cpuset_mems_cookie
;
653 cpuset_mems_cookie
= read_mems_allowed_begin();
654 n
= cpuset_mem_spread_node();
655 page
= alloc_pages_exact_node(n
, gfp
, 0);
656 } while (!page
&& read_mems_allowed_retry(cpuset_mems_cookie
));
660 return alloc_pages(gfp
, 0);
662 EXPORT_SYMBOL(__page_cache_alloc
);
666 * In order to wait for pages to become available there must be
667 * waitqueues associated with pages. By using a hash table of
668 * waitqueues where the bucket discipline is to maintain all
669 * waiters on the same queue and wake all when any of the pages
670 * become available, and for the woken contexts to check to be
671 * sure the appropriate page became available, this saves space
672 * at a cost of "thundering herd" phenomena during rare hash
675 static wait_queue_head_t
*page_waitqueue(struct page
*page
)
677 const struct zone
*zone
= page_zone(page
);
679 return &zone
->wait_table
[hash_ptr(page
, zone
->wait_table_bits
)];
682 static inline void wake_up_page(struct page
*page
, int bit
)
684 __wake_up_bit(page_waitqueue(page
), &page
->flags
, bit
);
687 void wait_on_page_bit(struct page
*page
, int bit_nr
)
689 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
691 if (test_bit(bit_nr
, &page
->flags
))
692 __wait_on_bit(page_waitqueue(page
), &wait
, sleep_on_page
,
693 TASK_UNINTERRUPTIBLE
);
695 EXPORT_SYMBOL(wait_on_page_bit
);
697 int wait_on_page_bit_killable(struct page
*page
, int bit_nr
)
699 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
701 if (!test_bit(bit_nr
, &page
->flags
))
704 return __wait_on_bit(page_waitqueue(page
), &wait
,
705 sleep_on_page_killable
, TASK_KILLABLE
);
709 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
710 * @page: Page defining the wait queue of interest
711 * @waiter: Waiter to add to the queue
713 * Add an arbitrary @waiter to the wait queue for the nominated @page.
715 void add_page_wait_queue(struct page
*page
, wait_queue_t
*waiter
)
717 wait_queue_head_t
*q
= page_waitqueue(page
);
720 spin_lock_irqsave(&q
->lock
, flags
);
721 __add_wait_queue(q
, waiter
);
722 spin_unlock_irqrestore(&q
->lock
, flags
);
724 EXPORT_SYMBOL_GPL(add_page_wait_queue
);
727 * unlock_page - unlock a locked page
730 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
731 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
732 * mechananism between PageLocked pages and PageWriteback pages is shared.
733 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
735 * The mb is necessary to enforce ordering between the clear_bit and the read
736 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
738 void unlock_page(struct page
*page
)
740 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
741 clear_bit_unlock(PG_locked
, &page
->flags
);
742 smp_mb__after_clear_bit();
743 wake_up_page(page
, PG_locked
);
745 EXPORT_SYMBOL(unlock_page
);
748 * end_page_writeback - end writeback against a page
751 void end_page_writeback(struct page
*page
)
753 if (TestClearPageReclaim(page
))
754 rotate_reclaimable_page(page
);
756 if (!test_clear_page_writeback(page
))
759 smp_mb__after_clear_bit();
760 wake_up_page(page
, PG_writeback
);
762 EXPORT_SYMBOL(end_page_writeback
);
765 * __lock_page - get a lock on the page, assuming we need to sleep to get it
766 * @page: the page to lock
768 void __lock_page(struct page
*page
)
770 DEFINE_WAIT_BIT(wait
, &page
->flags
, PG_locked
);
772 __wait_on_bit_lock(page_waitqueue(page
), &wait
, sleep_on_page
,
773 TASK_UNINTERRUPTIBLE
);
775 EXPORT_SYMBOL(__lock_page
);
777 int __lock_page_killable(struct page
*page
)
779 DEFINE_WAIT_BIT(wait
, &page
->flags
, PG_locked
);
781 return __wait_on_bit_lock(page_waitqueue(page
), &wait
,
782 sleep_on_page_killable
, TASK_KILLABLE
);
784 EXPORT_SYMBOL_GPL(__lock_page_killable
);
786 int __lock_page_or_retry(struct page
*page
, struct mm_struct
*mm
,
789 if (flags
& FAULT_FLAG_ALLOW_RETRY
) {
791 * CAUTION! In this case, mmap_sem is not released
792 * even though return 0.
794 if (flags
& FAULT_FLAG_RETRY_NOWAIT
)
797 up_read(&mm
->mmap_sem
);
798 if (flags
& FAULT_FLAG_KILLABLE
)
799 wait_on_page_locked_killable(page
);
801 wait_on_page_locked(page
);
804 if (flags
& FAULT_FLAG_KILLABLE
) {
807 ret
= __lock_page_killable(page
);
809 up_read(&mm
->mmap_sem
);
819 * page_cache_next_hole - find the next hole (not-present entry)
822 * @max_scan: maximum range to search
824 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
825 * lowest indexed hole.
827 * Returns: the index of the hole if found, otherwise returns an index
828 * outside of the set specified (in which case 'return - index >=
829 * max_scan' will be true). In rare cases of index wrap-around, 0 will
832 * page_cache_next_hole may be called under rcu_read_lock. However,
833 * like radix_tree_gang_lookup, this will not atomically search a
834 * snapshot of the tree at a single point in time. For example, if a
835 * hole is created at index 5, then subsequently a hole is created at
836 * index 10, page_cache_next_hole covering both indexes may return 10
837 * if called under rcu_read_lock.
839 pgoff_t
page_cache_next_hole(struct address_space
*mapping
,
840 pgoff_t index
, unsigned long max_scan
)
844 for (i
= 0; i
< max_scan
; i
++) {
847 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
848 if (!page
|| radix_tree_exceptional_entry(page
))
857 EXPORT_SYMBOL(page_cache_next_hole
);
860 * page_cache_prev_hole - find the prev hole (not-present entry)
863 * @max_scan: maximum range to search
865 * Search backwards in the range [max(index-max_scan+1, 0), index] for
868 * Returns: the index of the hole if found, otherwise returns an index
869 * outside of the set specified (in which case 'index - return >=
870 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
873 * page_cache_prev_hole may be called under rcu_read_lock. However,
874 * like radix_tree_gang_lookup, this will not atomically search a
875 * snapshot of the tree at a single point in time. For example, if a
876 * hole is created at index 10, then subsequently a hole is created at
877 * index 5, page_cache_prev_hole covering both indexes may return 5 if
878 * called under rcu_read_lock.
880 pgoff_t
page_cache_prev_hole(struct address_space
*mapping
,
881 pgoff_t index
, unsigned long max_scan
)
885 for (i
= 0; i
< max_scan
; i
++) {
888 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
889 if (!page
|| radix_tree_exceptional_entry(page
))
892 if (index
== ULONG_MAX
)
898 EXPORT_SYMBOL(page_cache_prev_hole
);
901 * find_get_entry - find and get a page cache entry
902 * @mapping: the address_space to search
903 * @offset: the page cache index
905 * Looks up the page cache slot at @mapping & @offset. If there is a
906 * page cache page, it is returned with an increased refcount.
908 * If the slot holds a shadow entry of a previously evicted page, it
911 * Otherwise, %NULL is returned.
913 struct page
*find_get_entry(struct address_space
*mapping
, pgoff_t offset
)
921 pagep
= radix_tree_lookup_slot(&mapping
->page_tree
, offset
);
923 page
= radix_tree_deref_slot(pagep
);
926 if (radix_tree_exception(page
)) {
927 if (radix_tree_deref_retry(page
))
930 * Otherwise, shmem/tmpfs must be storing a swap entry
931 * here as an exceptional entry: so return it without
932 * attempting to raise page count.
936 if (!page_cache_get_speculative(page
))
940 * Has the page moved?
941 * This is part of the lockless pagecache protocol. See
942 * include/linux/pagemap.h for details.
944 if (unlikely(page
!= *pagep
)) {
945 page_cache_release(page
);
954 EXPORT_SYMBOL(find_get_entry
);
957 * find_get_page - find and get a page reference
958 * @mapping: the address_space to search
959 * @offset: the page index
961 * Looks up the page cache slot at @mapping & @offset. If there is a
962 * page cache page, it is returned with an increased refcount.
964 * Otherwise, %NULL is returned.
966 struct page
*find_get_page(struct address_space
*mapping
, pgoff_t offset
)
968 struct page
*page
= find_get_entry(mapping
, offset
);
970 if (radix_tree_exceptional_entry(page
))
974 EXPORT_SYMBOL(find_get_page
);
977 * find_lock_entry - locate, pin and lock a page cache entry
978 * @mapping: the address_space to search
979 * @offset: the page cache index
981 * Looks up the page cache slot at @mapping & @offset. If there is a
982 * page cache page, it is returned locked and with an increased
985 * If the slot holds a shadow entry of a previously evicted page, it
988 * Otherwise, %NULL is returned.
990 * find_lock_entry() may sleep.
992 struct page
*find_lock_entry(struct address_space
*mapping
, pgoff_t offset
)
997 page
= find_get_entry(mapping
, offset
);
998 if (page
&& !radix_tree_exception(page
)) {
1000 /* Has the page been truncated? */
1001 if (unlikely(page
->mapping
!= mapping
)) {
1003 page_cache_release(page
);
1006 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
1010 EXPORT_SYMBOL(find_lock_entry
);
1013 * find_lock_page - locate, pin and lock a pagecache page
1014 * @mapping: the address_space to search
1015 * @offset: the page index
1017 * Looks up the page cache slot at @mapping & @offset. If there is a
1018 * page cache page, it is returned locked and with an increased
1021 * Otherwise, %NULL is returned.
1023 * find_lock_page() may sleep.
1025 struct page
*find_lock_page(struct address_space
*mapping
, pgoff_t offset
)
1027 struct page
*page
= find_lock_entry(mapping
, offset
);
1029 if (radix_tree_exceptional_entry(page
))
1033 EXPORT_SYMBOL(find_lock_page
);
1036 * find_or_create_page - locate or add a pagecache page
1037 * @mapping: the page's address_space
1038 * @index: the page's index into the mapping
1039 * @gfp_mask: page allocation mode
1041 * Looks up the page cache slot at @mapping & @offset. If there is a
1042 * page cache page, it is returned locked and with an increased
1045 * If the page is not present, a new page is allocated using @gfp_mask
1046 * and added to the page cache and the VM's LRU list. The page is
1047 * returned locked and with an increased refcount.
1049 * On memory exhaustion, %NULL is returned.
1051 * find_or_create_page() may sleep, even if @gfp_flags specifies an
1052 * atomic allocation!
1054 struct page
*find_or_create_page(struct address_space
*mapping
,
1055 pgoff_t index
, gfp_t gfp_mask
)
1060 page
= find_lock_page(mapping
, index
);
1062 page
= __page_cache_alloc(gfp_mask
);
1066 * We want a regular kernel memory (not highmem or DMA etc)
1067 * allocation for the radix tree nodes, but we need to honour
1068 * the context-specific requirements the caller has asked for.
1069 * GFP_RECLAIM_MASK collects those requirements.
1071 err
= add_to_page_cache_lru(page
, mapping
, index
,
1072 (gfp_mask
& GFP_RECLAIM_MASK
));
1073 if (unlikely(err
)) {
1074 page_cache_release(page
);
1082 EXPORT_SYMBOL(find_or_create_page
);
1085 * find_get_entries - gang pagecache lookup
1086 * @mapping: The address_space to search
1087 * @start: The starting page cache index
1088 * @nr_entries: The maximum number of entries
1089 * @entries: Where the resulting entries are placed
1090 * @indices: The cache indices corresponding to the entries in @entries
1092 * find_get_entries() will search for and return a group of up to
1093 * @nr_entries entries in the mapping. The entries are placed at
1094 * @entries. find_get_entries() takes a reference against any actual
1097 * The search returns a group of mapping-contiguous page cache entries
1098 * with ascending indexes. There may be holes in the indices due to
1099 * not-present pages.
1101 * Any shadow entries of evicted pages are included in the returned
1104 * find_get_entries() returns the number of pages and shadow entries
1107 unsigned find_get_entries(struct address_space
*mapping
,
1108 pgoff_t start
, unsigned int nr_entries
,
1109 struct page
**entries
, pgoff_t
*indices
)
1112 unsigned int ret
= 0;
1113 struct radix_tree_iter iter
;
1120 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1123 page
= radix_tree_deref_slot(slot
);
1124 if (unlikely(!page
))
1126 if (radix_tree_exception(page
)) {
1127 if (radix_tree_deref_retry(page
))
1130 * Otherwise, we must be storing a swap entry
1131 * here as an exceptional entry: so return it
1132 * without attempting to raise page count.
1136 if (!page_cache_get_speculative(page
))
1139 /* Has the page moved? */
1140 if (unlikely(page
!= *slot
)) {
1141 page_cache_release(page
);
1145 indices
[ret
] = iter
.index
;
1146 entries
[ret
] = page
;
1147 if (++ret
== nr_entries
)
1155 * find_get_pages - gang pagecache lookup
1156 * @mapping: The address_space to search
1157 * @start: The starting page index
1158 * @nr_pages: The maximum number of pages
1159 * @pages: Where the resulting pages are placed
1161 * find_get_pages() will search for and return a group of up to
1162 * @nr_pages pages in the mapping. The pages are placed at @pages.
1163 * find_get_pages() takes a reference against the returned pages.
1165 * The search returns a group of mapping-contiguous pages with ascending
1166 * indexes. There may be holes in the indices due to not-present pages.
1168 * find_get_pages() returns the number of pages which were found.
1170 unsigned find_get_pages(struct address_space
*mapping
, pgoff_t start
,
1171 unsigned int nr_pages
, struct page
**pages
)
1173 struct radix_tree_iter iter
;
1177 if (unlikely(!nr_pages
))
1182 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1185 page
= radix_tree_deref_slot(slot
);
1186 if (unlikely(!page
))
1189 if (radix_tree_exception(page
)) {
1190 if (radix_tree_deref_retry(page
)) {
1192 * Transient condition which can only trigger
1193 * when entry at index 0 moves out of or back
1194 * to root: none yet gotten, safe to restart.
1196 WARN_ON(iter
.index
);
1200 * Otherwise, shmem/tmpfs must be storing a swap entry
1201 * here as an exceptional entry: so skip over it -
1202 * we only reach this from invalidate_mapping_pages().
1207 if (!page_cache_get_speculative(page
))
1210 /* Has the page moved? */
1211 if (unlikely(page
!= *slot
)) {
1212 page_cache_release(page
);
1217 if (++ret
== nr_pages
)
1226 * find_get_pages_contig - gang contiguous pagecache lookup
1227 * @mapping: The address_space to search
1228 * @index: The starting page index
1229 * @nr_pages: The maximum number of pages
1230 * @pages: Where the resulting pages are placed
1232 * find_get_pages_contig() works exactly like find_get_pages(), except
1233 * that the returned number of pages are guaranteed to be contiguous.
1235 * find_get_pages_contig() returns the number of pages which were found.
1237 unsigned find_get_pages_contig(struct address_space
*mapping
, pgoff_t index
,
1238 unsigned int nr_pages
, struct page
**pages
)
1240 struct radix_tree_iter iter
;
1242 unsigned int ret
= 0;
1244 if (unlikely(!nr_pages
))
1249 radix_tree_for_each_contig(slot
, &mapping
->page_tree
, &iter
, index
) {
1252 page
= radix_tree_deref_slot(slot
);
1253 /* The hole, there no reason to continue */
1254 if (unlikely(!page
))
1257 if (radix_tree_exception(page
)) {
1258 if (radix_tree_deref_retry(page
)) {
1260 * Transient condition which can only trigger
1261 * when entry at index 0 moves out of or back
1262 * to root: none yet gotten, safe to restart.
1267 * Otherwise, shmem/tmpfs must be storing a swap entry
1268 * here as an exceptional entry: so stop looking for
1274 if (!page_cache_get_speculative(page
))
1277 /* Has the page moved? */
1278 if (unlikely(page
!= *slot
)) {
1279 page_cache_release(page
);
1284 * must check mapping and index after taking the ref.
1285 * otherwise we can get both false positives and false
1286 * negatives, which is just confusing to the caller.
1288 if (page
->mapping
== NULL
|| page
->index
!= iter
.index
) {
1289 page_cache_release(page
);
1294 if (++ret
== nr_pages
)
1300 EXPORT_SYMBOL(find_get_pages_contig
);
1303 * find_get_pages_tag - find and return pages that match @tag
1304 * @mapping: the address_space to search
1305 * @index: the starting page index
1306 * @tag: the tag index
1307 * @nr_pages: the maximum number of pages
1308 * @pages: where the resulting pages are placed
1310 * Like find_get_pages, except we only return pages which are tagged with
1311 * @tag. We update @index to index the next page for the traversal.
1313 unsigned find_get_pages_tag(struct address_space
*mapping
, pgoff_t
*index
,
1314 int tag
, unsigned int nr_pages
, struct page
**pages
)
1316 struct radix_tree_iter iter
;
1320 if (unlikely(!nr_pages
))
1325 radix_tree_for_each_tagged(slot
, &mapping
->page_tree
,
1326 &iter
, *index
, tag
) {
1329 page
= radix_tree_deref_slot(slot
);
1330 if (unlikely(!page
))
1333 if (radix_tree_exception(page
)) {
1334 if (radix_tree_deref_retry(page
)) {
1336 * Transient condition which can only trigger
1337 * when entry at index 0 moves out of or back
1338 * to root: none yet gotten, safe to restart.
1343 * This function is never used on a shmem/tmpfs
1344 * mapping, so a swap entry won't be found here.
1349 if (!page_cache_get_speculative(page
))
1352 /* Has the page moved? */
1353 if (unlikely(page
!= *slot
)) {
1354 page_cache_release(page
);
1359 if (++ret
== nr_pages
)
1366 *index
= pages
[ret
- 1]->index
+ 1;
1370 EXPORT_SYMBOL(find_get_pages_tag
);
1373 * grab_cache_page_nowait - returns locked page at given index in given cache
1374 * @mapping: target address_space
1375 * @index: the page index
1377 * Same as grab_cache_page(), but do not wait if the page is unavailable.
1378 * This is intended for speculative data generators, where the data can
1379 * be regenerated if the page couldn't be grabbed. This routine should
1380 * be safe to call while holding the lock for another page.
1382 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
1383 * and deadlock against the caller's locked page.
1386 grab_cache_page_nowait(struct address_space
*mapping
, pgoff_t index
)
1388 struct page
*page
= find_get_page(mapping
, index
);
1391 if (trylock_page(page
))
1393 page_cache_release(page
);
1396 page
= __page_cache_alloc(mapping_gfp_mask(mapping
) & ~__GFP_FS
);
1397 if (page
&& add_to_page_cache_lru(page
, mapping
, index
, GFP_NOFS
)) {
1398 page_cache_release(page
);
1403 EXPORT_SYMBOL(grab_cache_page_nowait
);
1406 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1407 * a _large_ part of the i/o request. Imagine the worst scenario:
1409 * ---R__________________________________________B__________
1410 * ^ reading here ^ bad block(assume 4k)
1412 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1413 * => failing the whole request => read(R) => read(R+1) =>
1414 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1415 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1416 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1418 * It is going insane. Fix it by quickly scaling down the readahead size.
1420 static void shrink_readahead_size_eio(struct file
*filp
,
1421 struct file_ra_state
*ra
)
1427 * do_generic_file_read - generic file read routine
1428 * @filp: the file to read
1429 * @ppos: current file position
1430 * @desc: read_descriptor
1432 * This is a generic file read routine, and uses the
1433 * mapping->a_ops->readpage() function for the actual low-level stuff.
1435 * This is really ugly. But the goto's actually try to clarify some
1436 * of the logic when it comes to error handling etc.
1438 static void do_generic_file_read(struct file
*filp
, loff_t
*ppos
,
1439 read_descriptor_t
*desc
)
1441 struct address_space
*mapping
= filp
->f_mapping
;
1442 struct inode
*inode
= mapping
->host
;
1443 struct file_ra_state
*ra
= &filp
->f_ra
;
1447 unsigned long offset
; /* offset into pagecache page */
1448 unsigned int prev_offset
;
1451 index
= *ppos
>> PAGE_CACHE_SHIFT
;
1452 prev_index
= ra
->prev_pos
>> PAGE_CACHE_SHIFT
;
1453 prev_offset
= ra
->prev_pos
& (PAGE_CACHE_SIZE
-1);
1454 last_index
= (*ppos
+ desc
->count
+ PAGE_CACHE_SIZE
-1) >> PAGE_CACHE_SHIFT
;
1455 offset
= *ppos
& ~PAGE_CACHE_MASK
;
1461 unsigned long nr
, ret
;
1465 page
= find_get_page(mapping
, index
);
1467 page_cache_sync_readahead(mapping
,
1469 index
, last_index
- index
);
1470 page
= find_get_page(mapping
, index
);
1471 if (unlikely(page
== NULL
))
1472 goto no_cached_page
;
1474 if (PageReadahead(page
)) {
1475 page_cache_async_readahead(mapping
,
1477 index
, last_index
- index
);
1479 if (!PageUptodate(page
)) {
1480 if (inode
->i_blkbits
== PAGE_CACHE_SHIFT
||
1481 !mapping
->a_ops
->is_partially_uptodate
)
1482 goto page_not_up_to_date
;
1483 if (!trylock_page(page
))
1484 goto page_not_up_to_date
;
1485 /* Did it get truncated before we got the lock? */
1487 goto page_not_up_to_date_locked
;
1488 if (!mapping
->a_ops
->is_partially_uptodate(page
,
1490 goto page_not_up_to_date_locked
;
1495 * i_size must be checked after we know the page is Uptodate.
1497 * Checking i_size after the check allows us to calculate
1498 * the correct value for "nr", which means the zero-filled
1499 * part of the page is not copied back to userspace (unless
1500 * another truncate extends the file - this is desired though).
1503 isize
= i_size_read(inode
);
1504 end_index
= (isize
- 1) >> PAGE_CACHE_SHIFT
;
1505 if (unlikely(!isize
|| index
> end_index
)) {
1506 page_cache_release(page
);
1510 /* nr is the maximum number of bytes to copy from this page */
1511 nr
= PAGE_CACHE_SIZE
;
1512 if (index
== end_index
) {
1513 nr
= ((isize
- 1) & ~PAGE_CACHE_MASK
) + 1;
1515 page_cache_release(page
);
1521 /* If users can be writing to this page using arbitrary
1522 * virtual addresses, take care about potential aliasing
1523 * before reading the page on the kernel side.
1525 if (mapping_writably_mapped(mapping
))
1526 flush_dcache_page(page
);
1529 * When a sequential read accesses a page several times,
1530 * only mark it as accessed the first time.
1532 if (prev_index
!= index
|| offset
!= prev_offset
)
1533 mark_page_accessed(page
);
1537 * Ok, we have the page, and it's up-to-date, so
1538 * now we can copy it to user space...
1540 * The file_read_actor routine returns how many bytes were
1542 * NOTE! This may not be the same as how much of a user buffer
1543 * we filled up (we may be padding etc), so we can only update
1544 * "pos" here (the actor routine has to update the user buffer
1545 * pointers and the remaining count).
1547 ret
= file_read_actor(desc
, page
, offset
, nr
);
1549 index
+= offset
>> PAGE_CACHE_SHIFT
;
1550 offset
&= ~PAGE_CACHE_MASK
;
1551 prev_offset
= offset
;
1553 page_cache_release(page
);
1554 if (ret
== nr
&& desc
->count
)
1558 page_not_up_to_date
:
1559 /* Get exclusive access to the page ... */
1560 error
= lock_page_killable(page
);
1561 if (unlikely(error
))
1562 goto readpage_error
;
1564 page_not_up_to_date_locked
:
1565 /* Did it get truncated before we got the lock? */
1566 if (!page
->mapping
) {
1568 page_cache_release(page
);
1572 /* Did somebody else fill it already? */
1573 if (PageUptodate(page
)) {
1580 * A previous I/O error may have been due to temporary
1581 * failures, eg. multipath errors.
1582 * PG_error will be set again if readpage fails.
1584 ClearPageError(page
);
1585 /* Start the actual read. The read will unlock the page. */
1586 error
= mapping
->a_ops
->readpage(filp
, page
);
1588 if (unlikely(error
)) {
1589 if (error
== AOP_TRUNCATED_PAGE
) {
1590 page_cache_release(page
);
1593 goto readpage_error
;
1596 if (!PageUptodate(page
)) {
1597 error
= lock_page_killable(page
);
1598 if (unlikely(error
))
1599 goto readpage_error
;
1600 if (!PageUptodate(page
)) {
1601 if (page
->mapping
== NULL
) {
1603 * invalidate_mapping_pages got it
1606 page_cache_release(page
);
1610 shrink_readahead_size_eio(filp
, ra
);
1612 goto readpage_error
;
1620 /* UHHUH! A synchronous read error occurred. Report it */
1621 desc
->error
= error
;
1622 page_cache_release(page
);
1627 * Ok, it wasn't cached, so we need to create a new
1630 page
= page_cache_alloc_cold(mapping
);
1632 desc
->error
= -ENOMEM
;
1635 error
= add_to_page_cache_lru(page
, mapping
,
1638 page_cache_release(page
);
1639 if (error
== -EEXIST
)
1641 desc
->error
= error
;
1648 ra
->prev_pos
= prev_index
;
1649 ra
->prev_pos
<<= PAGE_CACHE_SHIFT
;
1650 ra
->prev_pos
|= prev_offset
;
1652 *ppos
= ((loff_t
)index
<< PAGE_CACHE_SHIFT
) + offset
;
1653 file_accessed(filp
);
1656 int file_read_actor(read_descriptor_t
*desc
, struct page
*page
,
1657 unsigned long offset
, unsigned long size
)
1660 unsigned long left
, count
= desc
->count
;
1666 * Faults on the destination of a read are common, so do it before
1669 if (!fault_in_pages_writeable(desc
->arg
.buf
, size
)) {
1670 kaddr
= kmap_atomic(page
);
1671 left
= __copy_to_user_inatomic(desc
->arg
.buf
,
1672 kaddr
+ offset
, size
);
1673 kunmap_atomic(kaddr
);
1678 /* Do it the slow way */
1680 left
= __copy_to_user(desc
->arg
.buf
, kaddr
+ offset
, size
);
1685 desc
->error
= -EFAULT
;
1688 desc
->count
= count
- size
;
1689 desc
->written
+= size
;
1690 desc
->arg
.buf
+= size
;
1695 * Performs necessary checks before doing a write
1696 * @iov: io vector request
1697 * @nr_segs: number of segments in the iovec
1698 * @count: number of bytes to write
1699 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1701 * Adjust number of segments and amount of bytes to write (nr_segs should be
1702 * properly initialized first). Returns appropriate error code that caller
1703 * should return or zero in case that write should be allowed.
1705 int generic_segment_checks(const struct iovec
*iov
,
1706 unsigned long *nr_segs
, size_t *count
, int access_flags
)
1710 for (seg
= 0; seg
< *nr_segs
; seg
++) {
1711 const struct iovec
*iv
= &iov
[seg
];
1714 * If any segment has a negative length, or the cumulative
1715 * length ever wraps negative then return -EINVAL.
1718 if (unlikely((ssize_t
)(cnt
|iv
->iov_len
) < 0))
1720 if (access_ok(access_flags
, iv
->iov_base
, iv
->iov_len
))
1725 cnt
-= iv
->iov_len
; /* This segment is no good */
1731 EXPORT_SYMBOL(generic_segment_checks
);
1734 * generic_file_aio_read - generic filesystem read routine
1735 * @iocb: kernel I/O control block
1736 * @iov: io vector request
1737 * @nr_segs: number of segments in the iovec
1738 * @pos: current file position
1740 * This is the "read()" routine for all filesystems
1741 * that can use the page cache directly.
1744 generic_file_aio_read(struct kiocb
*iocb
, const struct iovec
*iov
,
1745 unsigned long nr_segs
, loff_t pos
)
1747 struct file
*filp
= iocb
->ki_filp
;
1749 unsigned long seg
= 0;
1751 loff_t
*ppos
= &iocb
->ki_pos
;
1754 retval
= generic_segment_checks(iov
, &nr_segs
, &count
, VERIFY_WRITE
);
1758 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1759 if (filp
->f_flags
& O_DIRECT
) {
1761 struct address_space
*mapping
;
1762 struct inode
*inode
;
1764 mapping
= filp
->f_mapping
;
1765 inode
= mapping
->host
;
1767 goto out
; /* skip atime */
1768 size
= i_size_read(inode
);
1769 retval
= filemap_write_and_wait_range(mapping
, pos
,
1770 pos
+ iov_length(iov
, nr_segs
) - 1);
1772 retval
= mapping
->a_ops
->direct_IO(READ
, iocb
,
1776 *ppos
= pos
+ retval
;
1781 * Btrfs can have a short DIO read if we encounter
1782 * compressed extents, so if there was an error, or if
1783 * we've already read everything we wanted to, or if
1784 * there was a short read because we hit EOF, go ahead
1785 * and return. Otherwise fallthrough to buffered io for
1786 * the rest of the read.
1788 if (retval
< 0 || !count
|| *ppos
>= size
) {
1789 file_accessed(filp
);
1795 for (seg
= 0; seg
< nr_segs
; seg
++) {
1796 read_descriptor_t desc
;
1800 * If we did a short DIO read we need to skip the section of the
1801 * iov that we've already read data into.
1804 if (count
> iov
[seg
].iov_len
) {
1805 count
-= iov
[seg
].iov_len
;
1813 desc
.arg
.buf
= iov
[seg
].iov_base
+ offset
;
1814 desc
.count
= iov
[seg
].iov_len
- offset
;
1815 if (desc
.count
== 0)
1818 do_generic_file_read(filp
, ppos
, &desc
);
1819 retval
+= desc
.written
;
1821 retval
= retval
?: desc
.error
;
1830 EXPORT_SYMBOL(generic_file_aio_read
);
1834 * page_cache_read - adds requested page to the page cache if not already there
1835 * @file: file to read
1836 * @offset: page index
1838 * This adds the requested page to the page cache if it isn't already there,
1839 * and schedules an I/O to read in its contents from disk.
1841 static int page_cache_read(struct file
*file
, pgoff_t offset
)
1843 struct address_space
*mapping
= file
->f_mapping
;
1848 page
= page_cache_alloc_cold(mapping
);
1852 ret
= add_to_page_cache_lru(page
, mapping
, offset
, GFP_KERNEL
);
1854 ret
= mapping
->a_ops
->readpage(file
, page
);
1855 else if (ret
== -EEXIST
)
1856 ret
= 0; /* losing race to add is OK */
1858 page_cache_release(page
);
1860 } while (ret
== AOP_TRUNCATED_PAGE
);
1865 #define MMAP_LOTSAMISS (100)
1868 * Synchronous readahead happens when we don't even find
1869 * a page in the page cache at all.
1871 static void do_sync_mmap_readahead(struct vm_area_struct
*vma
,
1872 struct file_ra_state
*ra
,
1876 unsigned long ra_pages
;
1877 struct address_space
*mapping
= file
->f_mapping
;
1879 /* If we don't want any read-ahead, don't bother */
1880 if (vma
->vm_flags
& VM_RAND_READ
)
1885 if (vma
->vm_flags
& VM_SEQ_READ
) {
1886 page_cache_sync_readahead(mapping
, ra
, file
, offset
,
1891 /* Avoid banging the cache line if not needed */
1892 if (ra
->mmap_miss
< MMAP_LOTSAMISS
* 10)
1896 * Do we miss much more than hit in this file? If so,
1897 * stop bothering with read-ahead. It will only hurt.
1899 if (ra
->mmap_miss
> MMAP_LOTSAMISS
)
1905 ra_pages
= max_sane_readahead(ra
->ra_pages
);
1906 ra
->start
= max_t(long, 0, offset
- ra_pages
/ 2);
1907 ra
->size
= ra_pages
;
1908 ra
->async_size
= ra_pages
/ 4;
1909 ra_submit(ra
, mapping
, file
);
1913 * Asynchronous readahead happens when we find the page and PG_readahead,
1914 * so we want to possibly extend the readahead further..
1916 static void do_async_mmap_readahead(struct vm_area_struct
*vma
,
1917 struct file_ra_state
*ra
,
1922 struct address_space
*mapping
= file
->f_mapping
;
1924 /* If we don't want any read-ahead, don't bother */
1925 if (vma
->vm_flags
& VM_RAND_READ
)
1927 if (ra
->mmap_miss
> 0)
1929 if (PageReadahead(page
))
1930 page_cache_async_readahead(mapping
, ra
, file
,
1931 page
, offset
, ra
->ra_pages
);
1935 * filemap_fault - read in file data for page fault handling
1936 * @vma: vma in which the fault was taken
1937 * @vmf: struct vm_fault containing details of the fault
1939 * filemap_fault() is invoked via the vma operations vector for a
1940 * mapped memory region to read in file data during a page fault.
1942 * The goto's are kind of ugly, but this streamlines the normal case of having
1943 * it in the page cache, and handles the special cases reasonably without
1944 * having a lot of duplicated code.
1946 int filemap_fault(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
1949 struct file
*file
= vma
->vm_file
;
1950 struct address_space
*mapping
= file
->f_mapping
;
1951 struct file_ra_state
*ra
= &file
->f_ra
;
1952 struct inode
*inode
= mapping
->host
;
1953 pgoff_t offset
= vmf
->pgoff
;
1958 size
= (i_size_read(inode
) + PAGE_CACHE_SIZE
- 1) >> PAGE_CACHE_SHIFT
;
1960 return VM_FAULT_SIGBUS
;
1963 * Do we have something in the page cache already?
1965 page
= find_get_page(mapping
, offset
);
1966 if (likely(page
) && !(vmf
->flags
& FAULT_FLAG_TRIED
)) {
1968 * We found the page, so try async readahead before
1969 * waiting for the lock.
1971 do_async_mmap_readahead(vma
, ra
, file
, page
, offset
);
1973 /* No page in the page cache at all */
1974 do_sync_mmap_readahead(vma
, ra
, file
, offset
);
1975 count_vm_event(PGMAJFAULT
);
1976 mem_cgroup_count_vm_event(vma
->vm_mm
, PGMAJFAULT
);
1977 ret
= VM_FAULT_MAJOR
;
1979 page
= find_get_page(mapping
, offset
);
1981 goto no_cached_page
;
1984 if (!lock_page_or_retry(page
, vma
->vm_mm
, vmf
->flags
)) {
1985 page_cache_release(page
);
1986 return ret
| VM_FAULT_RETRY
;
1989 /* Did it get truncated? */
1990 if (unlikely(page
->mapping
!= mapping
)) {
1995 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
1998 * We have a locked page in the page cache, now we need to check
1999 * that it's up-to-date. If not, it is going to be due to an error.
2001 if (unlikely(!PageUptodate(page
)))
2002 goto page_not_uptodate
;
2005 * Found the page and have a reference on it.
2006 * We must recheck i_size under page lock.
2008 size
= (i_size_read(inode
) + PAGE_CACHE_SIZE
- 1) >> PAGE_CACHE_SHIFT
;
2009 if (unlikely(offset
>= size
)) {
2011 page_cache_release(page
);
2012 return VM_FAULT_SIGBUS
;
2016 return ret
| VM_FAULT_LOCKED
;
2020 * We're only likely to ever get here if MADV_RANDOM is in
2023 error
= page_cache_read(file
, offset
);
2026 * The page we want has now been added to the page cache.
2027 * In the unlikely event that someone removed it in the
2028 * meantime, we'll just come back here and read it again.
2034 * An error return from page_cache_read can result if the
2035 * system is low on memory, or a problem occurs while trying
2038 if (error
== -ENOMEM
)
2039 return VM_FAULT_OOM
;
2040 return VM_FAULT_SIGBUS
;
2044 * Umm, take care of errors if the page isn't up-to-date.
2045 * Try to re-read it _once_. We do this synchronously,
2046 * because there really aren't any performance issues here
2047 * and we need to check for errors.
2049 ClearPageError(page
);
2050 error
= mapping
->a_ops
->readpage(file
, page
);
2052 wait_on_page_locked(page
);
2053 if (!PageUptodate(page
))
2056 page_cache_release(page
);
2058 if (!error
|| error
== AOP_TRUNCATED_PAGE
)
2061 /* Things didn't work out. Return zero to tell the mm layer so. */
2062 shrink_readahead_size_eio(file
, ra
);
2063 return VM_FAULT_SIGBUS
;
2065 EXPORT_SYMBOL(filemap_fault
);
2067 int filemap_page_mkwrite(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
2069 struct page
*page
= vmf
->page
;
2070 struct inode
*inode
= file_inode(vma
->vm_file
);
2071 int ret
= VM_FAULT_LOCKED
;
2073 sb_start_pagefault(inode
->i_sb
);
2074 file_update_time(vma
->vm_file
);
2076 if (page
->mapping
!= inode
->i_mapping
) {
2078 ret
= VM_FAULT_NOPAGE
;
2082 * We mark the page dirty already here so that when freeze is in
2083 * progress, we are guaranteed that writeback during freezing will
2084 * see the dirty page and writeprotect it again.
2086 set_page_dirty(page
);
2087 wait_for_stable_page(page
);
2089 sb_end_pagefault(inode
->i_sb
);
2092 EXPORT_SYMBOL(filemap_page_mkwrite
);
2094 const struct vm_operations_struct generic_file_vm_ops
= {
2095 .fault
= filemap_fault
,
2096 .page_mkwrite
= filemap_page_mkwrite
,
2097 .remap_pages
= generic_file_remap_pages
,
2100 /* This is used for a general mmap of a disk file */
2102 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2104 struct address_space
*mapping
= file
->f_mapping
;
2106 if (!mapping
->a_ops
->readpage
)
2108 file_accessed(file
);
2109 vma
->vm_ops
= &generic_file_vm_ops
;
2114 * This is for filesystems which do not implement ->writepage.
2116 int generic_file_readonly_mmap(struct file
*file
, struct vm_area_struct
*vma
)
2118 if ((vma
->vm_flags
& VM_SHARED
) && (vma
->vm_flags
& VM_MAYWRITE
))
2120 return generic_file_mmap(file
, vma
);
2123 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2127 int generic_file_readonly_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2131 #endif /* CONFIG_MMU */
2133 EXPORT_SYMBOL(generic_file_mmap
);
2134 EXPORT_SYMBOL(generic_file_readonly_mmap
);
2136 static struct page
*wait_on_page_read(struct page
*page
)
2138 if (!IS_ERR(page
)) {
2139 wait_on_page_locked(page
);
2140 if (!PageUptodate(page
)) {
2141 page_cache_release(page
);
2142 page
= ERR_PTR(-EIO
);
2148 static struct page
*__read_cache_page(struct address_space
*mapping
,
2150 int (*filler
)(void *, struct page
*),
2157 page
= find_get_page(mapping
, index
);
2159 page
= __page_cache_alloc(gfp
| __GFP_COLD
);
2161 return ERR_PTR(-ENOMEM
);
2162 err
= add_to_page_cache_lru(page
, mapping
, index
, gfp
);
2163 if (unlikely(err
)) {
2164 page_cache_release(page
);
2167 /* Presumably ENOMEM for radix tree node */
2168 return ERR_PTR(err
);
2170 err
= filler(data
, page
);
2172 page_cache_release(page
);
2173 page
= ERR_PTR(err
);
2175 page
= wait_on_page_read(page
);
2181 static struct page
*do_read_cache_page(struct address_space
*mapping
,
2183 int (*filler
)(void *, struct page
*),
2192 page
= __read_cache_page(mapping
, index
, filler
, data
, gfp
);
2195 if (PageUptodate(page
))
2199 if (!page
->mapping
) {
2201 page_cache_release(page
);
2204 if (PageUptodate(page
)) {
2208 err
= filler(data
, page
);
2210 page_cache_release(page
);
2211 return ERR_PTR(err
);
2213 page
= wait_on_page_read(page
);
2218 mark_page_accessed(page
);
2223 * read_cache_page - read into page cache, fill it if needed
2224 * @mapping: the page's address_space
2225 * @index: the page index
2226 * @filler: function to perform the read
2227 * @data: first arg to filler(data, page) function, often left as NULL
2229 * Read into the page cache. If a page already exists, and PageUptodate() is
2230 * not set, try to fill the page and wait for it to become unlocked.
2232 * If the page does not get brought uptodate, return -EIO.
2234 struct page
*read_cache_page(struct address_space
*mapping
,
2236 int (*filler
)(void *, struct page
*),
2239 return do_read_cache_page(mapping
, index
, filler
, data
, mapping_gfp_mask(mapping
));
2241 EXPORT_SYMBOL(read_cache_page
);
2244 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2245 * @mapping: the page's address_space
2246 * @index: the page index
2247 * @gfp: the page allocator flags to use if allocating
2249 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2250 * any new page allocations done using the specified allocation flags.
2252 * If the page does not get brought uptodate, return -EIO.
2254 struct page
*read_cache_page_gfp(struct address_space
*mapping
,
2258 filler_t
*filler
= (filler_t
*)mapping
->a_ops
->readpage
;
2260 return do_read_cache_page(mapping
, index
, filler
, NULL
, gfp
);
2262 EXPORT_SYMBOL(read_cache_page_gfp
);
2264 static size_t __iovec_copy_from_user_inatomic(char *vaddr
,
2265 const struct iovec
*iov
, size_t base
, size_t bytes
)
2267 size_t copied
= 0, left
= 0;
2270 char __user
*buf
= iov
->iov_base
+ base
;
2271 int copy
= min(bytes
, iov
->iov_len
- base
);
2274 left
= __copy_from_user_inatomic(vaddr
, buf
, copy
);
2283 return copied
- left
;
2287 * Copy as much as we can into the page and return the number of bytes which
2288 * were successfully copied. If a fault is encountered then return the number of
2289 * bytes which were copied.
2291 size_t iov_iter_copy_from_user_atomic(struct page
*page
,
2292 struct iov_iter
*i
, unsigned long offset
, size_t bytes
)
2297 BUG_ON(!in_atomic());
2298 kaddr
= kmap_atomic(page
);
2299 if (likely(i
->nr_segs
== 1)) {
2301 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
2302 left
= __copy_from_user_inatomic(kaddr
+ offset
, buf
, bytes
);
2303 copied
= bytes
- left
;
2305 copied
= __iovec_copy_from_user_inatomic(kaddr
+ offset
,
2306 i
->iov
, i
->iov_offset
, bytes
);
2308 kunmap_atomic(kaddr
);
2312 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic
);
2315 * This has the same sideeffects and return value as
2316 * iov_iter_copy_from_user_atomic().
2317 * The difference is that it attempts to resolve faults.
2318 * Page must not be locked.
2320 size_t iov_iter_copy_from_user(struct page
*page
,
2321 struct iov_iter
*i
, unsigned long offset
, size_t bytes
)
2327 if (likely(i
->nr_segs
== 1)) {
2329 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
2330 left
= __copy_from_user(kaddr
+ offset
, buf
, bytes
);
2331 copied
= bytes
- left
;
2333 copied
= __iovec_copy_from_user_inatomic(kaddr
+ offset
,
2334 i
->iov
, i
->iov_offset
, bytes
);
2339 EXPORT_SYMBOL(iov_iter_copy_from_user
);
2341 void iov_iter_advance(struct iov_iter
*i
, size_t bytes
)
2343 BUG_ON(i
->count
< bytes
);
2345 if (likely(i
->nr_segs
== 1)) {
2346 i
->iov_offset
+= bytes
;
2349 const struct iovec
*iov
= i
->iov
;
2350 size_t base
= i
->iov_offset
;
2351 unsigned long nr_segs
= i
->nr_segs
;
2354 * The !iov->iov_len check ensures we skip over unlikely
2355 * zero-length segments (without overruning the iovec).
2357 while (bytes
|| unlikely(i
->count
&& !iov
->iov_len
)) {
2360 copy
= min(bytes
, iov
->iov_len
- base
);
2361 BUG_ON(!i
->count
|| i
->count
< copy
);
2365 if (iov
->iov_len
== base
) {
2372 i
->iov_offset
= base
;
2373 i
->nr_segs
= nr_segs
;
2376 EXPORT_SYMBOL(iov_iter_advance
);
2379 * Fault in the first iovec of the given iov_iter, to a maximum length
2380 * of bytes. Returns 0 on success, or non-zero if the memory could not be
2381 * accessed (ie. because it is an invalid address).
2383 * writev-intensive code may want this to prefault several iovecs -- that
2384 * would be possible (callers must not rely on the fact that _only_ the
2385 * first iovec will be faulted with the current implementation).
2387 int iov_iter_fault_in_readable(struct iov_iter
*i
, size_t bytes
)
2389 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
2390 bytes
= min(bytes
, i
->iov
->iov_len
- i
->iov_offset
);
2391 return fault_in_pages_readable(buf
, bytes
);
2393 EXPORT_SYMBOL(iov_iter_fault_in_readable
);
2396 * Return the count of just the current iov_iter segment.
2398 size_t iov_iter_single_seg_count(const struct iov_iter
*i
)
2400 const struct iovec
*iov
= i
->iov
;
2401 if (i
->nr_segs
== 1)
2404 return min(i
->count
, iov
->iov_len
- i
->iov_offset
);
2406 EXPORT_SYMBOL(iov_iter_single_seg_count
);
2409 * Performs necessary checks before doing a write
2411 * Can adjust writing position or amount of bytes to write.
2412 * Returns appropriate error code that caller should return or
2413 * zero in case that write should be allowed.
2415 inline int generic_write_checks(struct file
*file
, loff_t
*pos
, size_t *count
, int isblk
)
2417 struct inode
*inode
= file
->f_mapping
->host
;
2418 unsigned long limit
= rlimit(RLIMIT_FSIZE
);
2420 if (unlikely(*pos
< 0))
2424 /* FIXME: this is for backwards compatibility with 2.4 */
2425 if (file
->f_flags
& O_APPEND
)
2426 *pos
= i_size_read(inode
);
2428 if (limit
!= RLIM_INFINITY
) {
2429 if (*pos
>= limit
) {
2430 send_sig(SIGXFSZ
, current
, 0);
2433 if (*count
> limit
- (typeof(limit
))*pos
) {
2434 *count
= limit
- (typeof(limit
))*pos
;
2442 if (unlikely(*pos
+ *count
> MAX_NON_LFS
&&
2443 !(file
->f_flags
& O_LARGEFILE
))) {
2444 if (*pos
>= MAX_NON_LFS
) {
2447 if (*count
> MAX_NON_LFS
- (unsigned long)*pos
) {
2448 *count
= MAX_NON_LFS
- (unsigned long)*pos
;
2453 * Are we about to exceed the fs block limit ?
2455 * If we have written data it becomes a short write. If we have
2456 * exceeded without writing data we send a signal and return EFBIG.
2457 * Linus frestrict idea will clean these up nicely..
2459 if (likely(!isblk
)) {
2460 if (unlikely(*pos
>= inode
->i_sb
->s_maxbytes
)) {
2461 if (*count
|| *pos
> inode
->i_sb
->s_maxbytes
) {
2464 /* zero-length writes at ->s_maxbytes are OK */
2467 if (unlikely(*pos
+ *count
> inode
->i_sb
->s_maxbytes
))
2468 *count
= inode
->i_sb
->s_maxbytes
- *pos
;
2472 if (bdev_read_only(I_BDEV(inode
)))
2474 isize
= i_size_read(inode
);
2475 if (*pos
>= isize
) {
2476 if (*count
|| *pos
> isize
)
2480 if (*pos
+ *count
> isize
)
2481 *count
= isize
- *pos
;
2488 EXPORT_SYMBOL(generic_write_checks
);
2490 int pagecache_write_begin(struct file
*file
, struct address_space
*mapping
,
2491 loff_t pos
, unsigned len
, unsigned flags
,
2492 struct page
**pagep
, void **fsdata
)
2494 const struct address_space_operations
*aops
= mapping
->a_ops
;
2496 return aops
->write_begin(file
, mapping
, pos
, len
, flags
,
2499 EXPORT_SYMBOL(pagecache_write_begin
);
2501 int pagecache_write_end(struct file
*file
, struct address_space
*mapping
,
2502 loff_t pos
, unsigned len
, unsigned copied
,
2503 struct page
*page
, void *fsdata
)
2505 const struct address_space_operations
*aops
= mapping
->a_ops
;
2507 mark_page_accessed(page
);
2508 return aops
->write_end(file
, mapping
, pos
, len
, copied
, page
, fsdata
);
2510 EXPORT_SYMBOL(pagecache_write_end
);
2513 generic_file_direct_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2514 unsigned long *nr_segs
, loff_t pos
, loff_t
*ppos
,
2515 size_t count
, size_t ocount
)
2517 struct file
*file
= iocb
->ki_filp
;
2518 struct address_space
*mapping
= file
->f_mapping
;
2519 struct inode
*inode
= mapping
->host
;
2524 if (count
!= ocount
)
2525 *nr_segs
= iov_shorten((struct iovec
*)iov
, *nr_segs
, count
);
2527 write_len
= iov_length(iov
, *nr_segs
);
2528 end
= (pos
+ write_len
- 1) >> PAGE_CACHE_SHIFT
;
2530 written
= filemap_write_and_wait_range(mapping
, pos
, pos
+ write_len
- 1);
2535 * After a write we want buffered reads to be sure to go to disk to get
2536 * the new data. We invalidate clean cached page from the region we're
2537 * about to write. We do this *before* the write so that we can return
2538 * without clobbering -EIOCBQUEUED from ->direct_IO().
2540 if (mapping
->nrpages
) {
2541 written
= invalidate_inode_pages2_range(mapping
,
2542 pos
>> PAGE_CACHE_SHIFT
, end
);
2544 * If a page can not be invalidated, return 0 to fall back
2545 * to buffered write.
2548 if (written
== -EBUSY
)
2554 written
= mapping
->a_ops
->direct_IO(WRITE
, iocb
, iov
, pos
, *nr_segs
);
2557 * Finally, try again to invalidate clean pages which might have been
2558 * cached by non-direct readahead, or faulted in by get_user_pages()
2559 * if the source of the write was an mmap'ed region of the file
2560 * we're writing. Either one is a pretty crazy thing to do,
2561 * so we don't support it 100%. If this invalidation
2562 * fails, tough, the write still worked...
2564 if (mapping
->nrpages
) {
2565 invalidate_inode_pages2_range(mapping
,
2566 pos
>> PAGE_CACHE_SHIFT
, end
);
2571 if (pos
> i_size_read(inode
) && !S_ISBLK(inode
->i_mode
)) {
2572 i_size_write(inode
, pos
);
2573 mark_inode_dirty(inode
);
2580 EXPORT_SYMBOL(generic_file_direct_write
);
2583 * Find or create a page at the given pagecache position. Return the locked
2584 * page. This function is specifically for buffered writes.
2586 struct page
*grab_cache_page_write_begin(struct address_space
*mapping
,
2587 pgoff_t index
, unsigned flags
)
2592 gfp_t gfp_notmask
= 0;
2594 gfp_mask
= mapping_gfp_mask(mapping
);
2595 if (mapping_cap_account_dirty(mapping
))
2596 gfp_mask
|= __GFP_WRITE
;
2597 if (flags
& AOP_FLAG_NOFS
)
2598 gfp_notmask
= __GFP_FS
;
2600 page
= find_lock_page(mapping
, index
);
2604 page
= __page_cache_alloc(gfp_mask
& ~gfp_notmask
);
2607 status
= add_to_page_cache_lru(page
, mapping
, index
,
2608 GFP_KERNEL
& ~gfp_notmask
);
2609 if (unlikely(status
)) {
2610 page_cache_release(page
);
2611 if (status
== -EEXIST
)
2616 wait_for_stable_page(page
);
2619 EXPORT_SYMBOL(grab_cache_page_write_begin
);
2621 static ssize_t
generic_perform_write(struct file
*file
,
2622 struct iov_iter
*i
, loff_t pos
)
2624 struct address_space
*mapping
= file
->f_mapping
;
2625 const struct address_space_operations
*a_ops
= mapping
->a_ops
;
2627 ssize_t written
= 0;
2628 unsigned int flags
= 0;
2631 * Copies from kernel address space cannot fail (NFSD is a big user).
2633 if (segment_eq(get_fs(), KERNEL_DS
))
2634 flags
|= AOP_FLAG_UNINTERRUPTIBLE
;
2638 unsigned long offset
; /* Offset into pagecache page */
2639 unsigned long bytes
; /* Bytes to write to page */
2640 size_t copied
; /* Bytes copied from user */
2643 offset
= (pos
& (PAGE_CACHE_SIZE
- 1));
2644 bytes
= min_t(unsigned long, PAGE_CACHE_SIZE
- offset
,
2649 * Bring in the user page that we will copy from _first_.
2650 * Otherwise there's a nasty deadlock on copying from the
2651 * same page as we're writing to, without it being marked
2654 * Not only is this an optimisation, but it is also required
2655 * to check that the address is actually valid, when atomic
2656 * usercopies are used, below.
2658 if (unlikely(iov_iter_fault_in_readable(i
, bytes
))) {
2663 status
= a_ops
->write_begin(file
, mapping
, pos
, bytes
, flags
,
2665 if (unlikely(status
))
2668 if (mapping_writably_mapped(mapping
))
2669 flush_dcache_page(page
);
2671 pagefault_disable();
2672 copied
= iov_iter_copy_from_user_atomic(page
, i
, offset
, bytes
);
2674 flush_dcache_page(page
);
2676 mark_page_accessed(page
);
2677 status
= a_ops
->write_end(file
, mapping
, pos
, bytes
, copied
,
2679 if (unlikely(status
< 0))
2685 iov_iter_advance(i
, copied
);
2686 if (unlikely(copied
== 0)) {
2688 * If we were unable to copy any data at all, we must
2689 * fall back to a single segment length write.
2691 * If we didn't fallback here, we could livelock
2692 * because not all segments in the iov can be copied at
2693 * once without a pagefault.
2695 bytes
= min_t(unsigned long, PAGE_CACHE_SIZE
- offset
,
2696 iov_iter_single_seg_count(i
));
2702 balance_dirty_pages_ratelimited(mapping
);
2703 if (fatal_signal_pending(current
)) {
2707 } while (iov_iter_count(i
));
2709 return written
? written
: status
;
2713 generic_file_buffered_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2714 unsigned long nr_segs
, loff_t pos
, loff_t
*ppos
,
2715 size_t count
, ssize_t written
)
2717 struct file
*file
= iocb
->ki_filp
;
2721 iov_iter_init(&i
, iov
, nr_segs
, count
, written
);
2722 status
= generic_perform_write(file
, &i
, pos
);
2724 if (likely(status
>= 0)) {
2726 *ppos
= pos
+ status
;
2729 return written
? written
: status
;
2731 EXPORT_SYMBOL(generic_file_buffered_write
);
2734 * __generic_file_aio_write - write data to a file
2735 * @iocb: IO state structure (file, offset, etc.)
2736 * @iov: vector with data to write
2737 * @nr_segs: number of segments in the vector
2738 * @ppos: position where to write
2740 * This function does all the work needed for actually writing data to a
2741 * file. It does all basic checks, removes SUID from the file, updates
2742 * modification times and calls proper subroutines depending on whether we
2743 * do direct IO or a standard buffered write.
2745 * It expects i_mutex to be grabbed unless we work on a block device or similar
2746 * object which does not need locking at all.
2748 * This function does *not* take care of syncing data in case of O_SYNC write.
2749 * A caller has to handle it. This is mainly due to the fact that we want to
2750 * avoid syncing under i_mutex.
2752 ssize_t
__generic_file_aio_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2753 unsigned long nr_segs
, loff_t
*ppos
)
2755 struct file
*file
= iocb
->ki_filp
;
2756 struct address_space
* mapping
= file
->f_mapping
;
2757 size_t ocount
; /* original count */
2758 size_t count
; /* after file limit checks */
2759 struct inode
*inode
= mapping
->host
;
2765 err
= generic_segment_checks(iov
, &nr_segs
, &ocount
, VERIFY_READ
);
2772 /* We can write back this queue in page reclaim */
2773 current
->backing_dev_info
= mapping
->backing_dev_info
;
2776 err
= generic_write_checks(file
, &pos
, &count
, S_ISBLK(inode
->i_mode
));
2783 err
= file_remove_suid(file
);
2787 err
= file_update_time(file
);
2791 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2792 if (unlikely(file
->f_flags
& O_DIRECT
)) {
2794 ssize_t written_buffered
;
2796 written
= generic_file_direct_write(iocb
, iov
, &nr_segs
, pos
,
2797 ppos
, count
, ocount
);
2798 if (written
< 0 || written
== count
)
2801 * direct-io write to a hole: fall through to buffered I/O
2802 * for completing the rest of the request.
2806 written_buffered
= generic_file_buffered_write(iocb
, iov
,
2807 nr_segs
, pos
, ppos
, count
,
2810 * If generic_file_buffered_write() retuned a synchronous error
2811 * then we want to return the number of bytes which were
2812 * direct-written, or the error code if that was zero. Note
2813 * that this differs from normal direct-io semantics, which
2814 * will return -EFOO even if some bytes were written.
2816 if (written_buffered
< 0) {
2817 err
= written_buffered
;
2822 * We need to ensure that the page cache pages are written to
2823 * disk and invalidated to preserve the expected O_DIRECT
2826 endbyte
= pos
+ written_buffered
- written
- 1;
2827 err
= filemap_write_and_wait_range(file
->f_mapping
, pos
, endbyte
);
2829 written
= written_buffered
;
2830 invalidate_mapping_pages(mapping
,
2831 pos
>> PAGE_CACHE_SHIFT
,
2832 endbyte
>> PAGE_CACHE_SHIFT
);
2835 * We don't know how much we wrote, so just return
2836 * the number of bytes which were direct-written
2840 written
= generic_file_buffered_write(iocb
, iov
, nr_segs
,
2841 pos
, ppos
, count
, written
);
2844 current
->backing_dev_info
= NULL
;
2845 return written
? written
: err
;
2847 EXPORT_SYMBOL(__generic_file_aio_write
);
2850 * generic_file_aio_write - write data to a file
2851 * @iocb: IO state structure
2852 * @iov: vector with data to write
2853 * @nr_segs: number of segments in the vector
2854 * @pos: position in file where to write
2856 * This is a wrapper around __generic_file_aio_write() to be used by most
2857 * filesystems. It takes care of syncing the file in case of O_SYNC file
2858 * and acquires i_mutex as needed.
2860 ssize_t
generic_file_aio_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2861 unsigned long nr_segs
, loff_t pos
)
2863 struct file
*file
= iocb
->ki_filp
;
2864 struct inode
*inode
= file
->f_mapping
->host
;
2867 BUG_ON(iocb
->ki_pos
!= pos
);
2869 mutex_lock(&inode
->i_mutex
);
2870 ret
= __generic_file_aio_write(iocb
, iov
, nr_segs
, &iocb
->ki_pos
);
2871 mutex_unlock(&inode
->i_mutex
);
2876 err
= generic_write_sync(file
, iocb
->ki_pos
- ret
, ret
);
2882 EXPORT_SYMBOL(generic_file_aio_write
);
2885 * try_to_release_page() - release old fs-specific metadata on a page
2887 * @page: the page which the kernel is trying to free
2888 * @gfp_mask: memory allocation flags (and I/O mode)
2890 * The address_space is to try to release any data against the page
2891 * (presumably at page->private). If the release was successful, return `1'.
2892 * Otherwise return zero.
2894 * This may also be called if PG_fscache is set on a page, indicating that the
2895 * page is known to the local caching routines.
2897 * The @gfp_mask argument specifies whether I/O may be performed to release
2898 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
2901 int try_to_release_page(struct page
*page
, gfp_t gfp_mask
)
2903 struct address_space
* const mapping
= page
->mapping
;
2905 BUG_ON(!PageLocked(page
));
2906 if (PageWriteback(page
))
2909 if (mapping
&& mapping
->a_ops
->releasepage
)
2910 return mapping
->a_ops
->releasepage(page
, gfp_mask
);
2911 return try_to_free_buffers(page
);
2914 EXPORT_SYMBOL(try_to_release_page
);