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/module.h>
13 #include <linux/slab.h>
14 #include <linux/compiler.h>
16 #include <linux/uaccess.h>
17 #include <linux/aio.h>
18 #include <linux/capability.h>
19 #include <linux/kernel_stat.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/syscalls.h>
33 #include <linux/cpuset.h>
34 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
35 #include <linux/memcontrol.h>
36 #include <linux/mm_inline.h> /* for page_is_file_cache() */
40 * FIXME: remove all knowledge of the buffer layer from the core VM
42 #include <linux/buffer_head.h> /* for try_to_free_buffers */
47 * Shared mappings implemented 30.11.1994. It's not fully working yet,
50 * Shared mappings now work. 15.8.1995 Bruno.
52 * finished 'unifying' the page and buffer cache and SMP-threaded the
53 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
55 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
61 * ->i_mmap_lock (truncate_pagecache)
62 * ->private_lock (__free_pte->__set_page_dirty_buffers)
63 * ->swap_lock (exclusive_swap_page, others)
64 * ->mapping->tree_lock
67 * ->i_mmap_lock (truncate->unmap_mapping_range)
71 * ->page_table_lock or pte_lock (various, mainly in memory.c)
72 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
75 * ->lock_page (access_process_vm)
77 * ->i_mutex (generic_file_buffered_write)
78 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
81 * ->i_alloc_sem (various)
84 * ->sb_lock (fs/fs-writeback.c)
85 * ->mapping->tree_lock (__sync_single_inode)
88 * ->anon_vma.lock (vma_adjust)
91 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
93 * ->page_table_lock or pte_lock
94 * ->swap_lock (try_to_unmap_one)
95 * ->private_lock (try_to_unmap_one)
96 * ->tree_lock (try_to_unmap_one)
97 * ->zone.lru_lock (follow_page->mark_page_accessed)
98 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
99 * ->private_lock (page_remove_rmap->set_page_dirty)
100 * ->tree_lock (page_remove_rmap->set_page_dirty)
101 * ->inode_lock (page_remove_rmap->set_page_dirty)
102 * ->inode_lock (zap_pte_range->set_page_dirty)
103 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
106 * ->dcache_lock (proc_pid_lookup)
108 * (code doesn't rely on that order, so you could switch it around)
109 * ->tasklist_lock (memory_failure, collect_procs_ao)
114 * Remove a page from the page cache and free it. Caller has to make
115 * sure the page is locked and that nobody else uses it - or that usage
116 * is safe. The caller must hold the mapping's tree_lock.
118 void __remove_from_page_cache(struct page
*page
)
120 struct address_space
*mapping
= page
->mapping
;
122 radix_tree_delete(&mapping
->page_tree
, page
->index
);
123 page
->mapping
= NULL
;
125 __dec_zone_page_state(page
, NR_FILE_PAGES
);
126 if (PageSwapBacked(page
))
127 __dec_zone_page_state(page
, NR_SHMEM
);
128 BUG_ON(page_mapped(page
));
131 * Some filesystems seem to re-dirty the page even after
132 * the VM has canceled the dirty bit (eg ext3 journaling).
134 * Fix it up by doing a final dirty accounting check after
135 * having removed the page entirely.
137 if (PageDirty(page
) && mapping_cap_account_dirty(mapping
)) {
138 dec_zone_page_state(page
, NR_FILE_DIRTY
);
139 dec_bdi_stat(mapping
->backing_dev_info
, BDI_RECLAIMABLE
);
143 void remove_from_page_cache(struct page
*page
)
145 struct address_space
*mapping
= page
->mapping
;
147 BUG_ON(!PageLocked(page
));
149 spin_lock_irq(&mapping
->tree_lock
);
150 __remove_from_page_cache(page
);
151 spin_unlock_irq(&mapping
->tree_lock
);
152 mem_cgroup_uncharge_cache_page(page
);
155 static int sync_page(void *word
)
157 struct address_space
*mapping
;
160 page
= container_of((unsigned long *)word
, struct page
, flags
);
163 * page_mapping() is being called without PG_locked held.
164 * Some knowledge of the state and use of the page is used to
165 * reduce the requirements down to a memory barrier.
166 * The danger here is of a stale page_mapping() return value
167 * indicating a struct address_space different from the one it's
168 * associated with when it is associated with one.
169 * After smp_mb(), it's either the correct page_mapping() for
170 * the page, or an old page_mapping() and the page's own
171 * page_mapping() has gone NULL.
172 * The ->sync_page() address_space operation must tolerate
173 * page_mapping() going NULL. By an amazing coincidence,
174 * this comes about because none of the users of the page
175 * in the ->sync_page() methods make essential use of the
176 * page_mapping(), merely passing the page down to the backing
177 * device's unplug functions when it's non-NULL, which in turn
178 * ignore it for all cases but swap, where only page_private(page) is
179 * of interest. When page_mapping() does go NULL, the entire
180 * call stack gracefully ignores the page and returns.
184 mapping
= page_mapping(page
);
185 if (mapping
&& mapping
->a_ops
&& mapping
->a_ops
->sync_page
)
186 mapping
->a_ops
->sync_page(page
);
191 static int sync_page_killable(void *word
)
194 return fatal_signal_pending(current
) ? -EINTR
: 0;
198 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
199 * @mapping: address space structure to write
200 * @start: offset in bytes where the range starts
201 * @end: offset in bytes where the range ends (inclusive)
202 * @sync_mode: enable synchronous operation
204 * Start writeback against all of a mapping's dirty pages that lie
205 * within the byte offsets <start, end> inclusive.
207 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
208 * opposed to a regular memory cleansing writeback. The difference between
209 * these two operations is that if a dirty page/buffer is encountered, it must
210 * be waited upon, and not just skipped over.
212 int __filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
213 loff_t end
, int sync_mode
)
216 struct writeback_control wbc
= {
217 .sync_mode
= sync_mode
,
218 .nr_to_write
= LONG_MAX
,
219 .range_start
= start
,
223 if (!mapping_cap_writeback_dirty(mapping
))
226 ret
= do_writepages(mapping
, &wbc
);
230 static inline int __filemap_fdatawrite(struct address_space
*mapping
,
233 return __filemap_fdatawrite_range(mapping
, 0, LLONG_MAX
, sync_mode
);
236 int filemap_fdatawrite(struct address_space
*mapping
)
238 return __filemap_fdatawrite(mapping
, WB_SYNC_ALL
);
240 EXPORT_SYMBOL(filemap_fdatawrite
);
242 int filemap_fdatawrite_range(struct address_space
*mapping
, loff_t start
,
245 return __filemap_fdatawrite_range(mapping
, start
, end
, WB_SYNC_ALL
);
247 EXPORT_SYMBOL(filemap_fdatawrite_range
);
250 * filemap_flush - mostly a non-blocking flush
251 * @mapping: target address_space
253 * This is a mostly non-blocking flush. Not suitable for data-integrity
254 * purposes - I/O may not be started against all dirty pages.
256 int filemap_flush(struct address_space
*mapping
)
258 return __filemap_fdatawrite(mapping
, WB_SYNC_NONE
);
260 EXPORT_SYMBOL(filemap_flush
);
263 * wait_on_page_writeback_range - wait for writeback to complete
264 * @mapping: target address_space
265 * @start: beginning page index
266 * @end: ending page index
268 * Wait for writeback to complete against pages indexed by start->end
271 int wait_on_page_writeback_range(struct address_space
*mapping
,
272 pgoff_t start
, pgoff_t end
)
282 pagevec_init(&pvec
, 0);
284 while ((index
<= end
) &&
285 (nr_pages
= pagevec_lookup_tag(&pvec
, mapping
, &index
,
286 PAGECACHE_TAG_WRITEBACK
,
287 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
-1) + 1)) != 0) {
290 for (i
= 0; i
< nr_pages
; i
++) {
291 struct page
*page
= pvec
.pages
[i
];
293 /* until radix tree lookup accepts end_index */
294 if (page
->index
> end
)
297 wait_on_page_writeback(page
);
301 pagevec_release(&pvec
);
305 /* Check for outstanding write errors */
306 if (test_and_clear_bit(AS_ENOSPC
, &mapping
->flags
))
308 if (test_and_clear_bit(AS_EIO
, &mapping
->flags
))
315 * filemap_fdatawait_range - wait for all under-writeback pages to complete in a given range
316 * @mapping: address space structure to wait for
317 * @start: offset in bytes where the range starts
318 * @end: offset in bytes where the range ends (inclusive)
320 * Walk the list of under-writeback pages of the given address space
321 * in the given range and wait for all of them.
323 * This is just a simple wrapper so that callers don't have to convert offsets
324 * to page indexes themselves
326 int filemap_fdatawait_range(struct address_space
*mapping
, loff_t start
,
329 return wait_on_page_writeback_range(mapping
, start
>> PAGE_CACHE_SHIFT
,
330 end
>> PAGE_CACHE_SHIFT
);
332 EXPORT_SYMBOL(filemap_fdatawait_range
);
335 * filemap_fdatawait - wait for all under-writeback pages to complete
336 * @mapping: address space structure to wait for
338 * Walk the list of under-writeback pages of the given address space
339 * and wait for all of them.
341 int filemap_fdatawait(struct address_space
*mapping
)
343 loff_t i_size
= i_size_read(mapping
->host
);
348 return wait_on_page_writeback_range(mapping
, 0,
349 (i_size
- 1) >> PAGE_CACHE_SHIFT
);
351 EXPORT_SYMBOL(filemap_fdatawait
);
353 int filemap_write_and_wait(struct address_space
*mapping
)
357 if (mapping
->nrpages
) {
358 err
= filemap_fdatawrite(mapping
);
360 * Even if the above returned error, the pages may be
361 * written partially (e.g. -ENOSPC), so we wait for it.
362 * But the -EIO is special case, it may indicate the worst
363 * thing (e.g. bug) happened, so we avoid waiting for it.
366 int err2
= filemap_fdatawait(mapping
);
373 EXPORT_SYMBOL(filemap_write_and_wait
);
376 * filemap_write_and_wait_range - write out & wait on a file range
377 * @mapping: the address_space for the pages
378 * @lstart: offset in bytes where the range starts
379 * @lend: offset in bytes where the range ends (inclusive)
381 * Write out and wait upon file offsets lstart->lend, inclusive.
383 * Note that `lend' is inclusive (describes the last byte to be written) so
384 * that this function can be used to write to the very end-of-file (end = -1).
386 int filemap_write_and_wait_range(struct address_space
*mapping
,
387 loff_t lstart
, loff_t lend
)
391 if (mapping
->nrpages
) {
392 err
= __filemap_fdatawrite_range(mapping
, lstart
, lend
,
394 /* See comment of filemap_write_and_wait() */
396 int err2
= wait_on_page_writeback_range(mapping
,
397 lstart
>> PAGE_CACHE_SHIFT
,
398 lend
>> PAGE_CACHE_SHIFT
);
405 EXPORT_SYMBOL(filemap_write_and_wait_range
);
408 * add_to_page_cache_locked - add a locked page to the pagecache
410 * @mapping: the page's address_space
411 * @offset: page index
412 * @gfp_mask: page allocation mode
414 * This function is used to add a page to the pagecache. It must be locked.
415 * This function does not add the page to the LRU. The caller must do that.
417 int add_to_page_cache_locked(struct page
*page
, struct address_space
*mapping
,
418 pgoff_t offset
, gfp_t gfp_mask
)
422 VM_BUG_ON(!PageLocked(page
));
424 error
= mem_cgroup_cache_charge(page
, current
->mm
,
425 gfp_mask
& GFP_RECLAIM_MASK
);
429 error
= radix_tree_preload(gfp_mask
& ~__GFP_HIGHMEM
);
431 page_cache_get(page
);
432 page
->mapping
= mapping
;
433 page
->index
= offset
;
435 spin_lock_irq(&mapping
->tree_lock
);
436 error
= radix_tree_insert(&mapping
->page_tree
, offset
, page
);
437 if (likely(!error
)) {
439 __inc_zone_page_state(page
, NR_FILE_PAGES
);
440 if (PageSwapBacked(page
))
441 __inc_zone_page_state(page
, NR_SHMEM
);
442 spin_unlock_irq(&mapping
->tree_lock
);
444 page
->mapping
= NULL
;
445 spin_unlock_irq(&mapping
->tree_lock
);
446 mem_cgroup_uncharge_cache_page(page
);
447 page_cache_release(page
);
449 radix_tree_preload_end();
451 mem_cgroup_uncharge_cache_page(page
);
455 EXPORT_SYMBOL(add_to_page_cache_locked
);
457 int add_to_page_cache_lru(struct page
*page
, struct address_space
*mapping
,
458 pgoff_t offset
, gfp_t gfp_mask
)
463 * Splice_read and readahead add shmem/tmpfs pages into the page cache
464 * before shmem_readpage has a chance to mark them as SwapBacked: they
465 * need to go on the active_anon lru below, and mem_cgroup_cache_charge
466 * (called in add_to_page_cache) needs to know where they're going too.
468 if (mapping_cap_swap_backed(mapping
))
469 SetPageSwapBacked(page
);
471 ret
= add_to_page_cache(page
, mapping
, offset
, gfp_mask
);
473 if (page_is_file_cache(page
))
474 lru_cache_add_file(page
);
476 lru_cache_add_active_anon(page
);
480 EXPORT_SYMBOL_GPL(add_to_page_cache_lru
);
483 struct page
*__page_cache_alloc(gfp_t gfp
)
485 if (cpuset_do_page_mem_spread()) {
486 int n
= cpuset_mem_spread_node();
487 return alloc_pages_exact_node(n
, gfp
, 0);
489 return alloc_pages(gfp
, 0);
491 EXPORT_SYMBOL(__page_cache_alloc
);
494 static int __sleep_on_page_lock(void *word
)
501 * In order to wait for pages to become available there must be
502 * waitqueues associated with pages. By using a hash table of
503 * waitqueues where the bucket discipline is to maintain all
504 * waiters on the same queue and wake all when any of the pages
505 * become available, and for the woken contexts to check to be
506 * sure the appropriate page became available, this saves space
507 * at a cost of "thundering herd" phenomena during rare hash
510 static wait_queue_head_t
*page_waitqueue(struct page
*page
)
512 const struct zone
*zone
= page_zone(page
);
514 return &zone
->wait_table
[hash_ptr(page
, zone
->wait_table_bits
)];
517 static inline void wake_up_page(struct page
*page
, int bit
)
519 __wake_up_bit(page_waitqueue(page
), &page
->flags
, bit
);
522 void wait_on_page_bit(struct page
*page
, int bit_nr
)
524 DEFINE_WAIT_BIT(wait
, &page
->flags
, bit_nr
);
526 if (test_bit(bit_nr
, &page
->flags
))
527 __wait_on_bit(page_waitqueue(page
), &wait
, sync_page
,
528 TASK_UNINTERRUPTIBLE
);
530 EXPORT_SYMBOL(wait_on_page_bit
);
533 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
534 * @page: Page defining the wait queue of interest
535 * @waiter: Waiter to add to the queue
537 * Add an arbitrary @waiter to the wait queue for the nominated @page.
539 void add_page_wait_queue(struct page
*page
, wait_queue_t
*waiter
)
541 wait_queue_head_t
*q
= page_waitqueue(page
);
544 spin_lock_irqsave(&q
->lock
, flags
);
545 __add_wait_queue(q
, waiter
);
546 spin_unlock_irqrestore(&q
->lock
, flags
);
548 EXPORT_SYMBOL_GPL(add_page_wait_queue
);
551 * unlock_page - unlock a locked page
554 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
555 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
556 * mechananism between PageLocked pages and PageWriteback pages is shared.
557 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
559 * The mb is necessary to enforce ordering between the clear_bit and the read
560 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
562 void unlock_page(struct page
*page
)
564 VM_BUG_ON(!PageLocked(page
));
565 clear_bit_unlock(PG_locked
, &page
->flags
);
566 smp_mb__after_clear_bit();
567 wake_up_page(page
, PG_locked
);
569 EXPORT_SYMBOL(unlock_page
);
572 * end_page_writeback - end writeback against a page
575 void end_page_writeback(struct page
*page
)
577 if (TestClearPageReclaim(page
))
578 rotate_reclaimable_page(page
);
580 if (!test_clear_page_writeback(page
))
583 smp_mb__after_clear_bit();
584 wake_up_page(page
, PG_writeback
);
586 EXPORT_SYMBOL(end_page_writeback
);
589 * __lock_page - get a lock on the page, assuming we need to sleep to get it
590 * @page: the page to lock
592 * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
593 * random driver's requestfn sets TASK_RUNNING, we could busywait. However
594 * chances are that on the second loop, the block layer's plug list is empty,
595 * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
597 void __lock_page(struct page
*page
)
599 DEFINE_WAIT_BIT(wait
, &page
->flags
, PG_locked
);
601 __wait_on_bit_lock(page_waitqueue(page
), &wait
, sync_page
,
602 TASK_UNINTERRUPTIBLE
);
604 EXPORT_SYMBOL(__lock_page
);
606 int __lock_page_killable(struct page
*page
)
608 DEFINE_WAIT_BIT(wait
, &page
->flags
, PG_locked
);
610 return __wait_on_bit_lock(page_waitqueue(page
), &wait
,
611 sync_page_killable
, TASK_KILLABLE
);
613 EXPORT_SYMBOL_GPL(__lock_page_killable
);
616 * __lock_page_nosync - get a lock on the page, without calling sync_page()
617 * @page: the page to lock
619 * Variant of lock_page that does not require the caller to hold a reference
620 * on the page's mapping.
622 void __lock_page_nosync(struct page
*page
)
624 DEFINE_WAIT_BIT(wait
, &page
->flags
, PG_locked
);
625 __wait_on_bit_lock(page_waitqueue(page
), &wait
, __sleep_on_page_lock
,
626 TASK_UNINTERRUPTIBLE
);
630 * find_get_page - find and get a page reference
631 * @mapping: the address_space to search
632 * @offset: the page index
634 * Is there a pagecache struct page at the given (mapping, offset) tuple?
635 * If yes, increment its refcount and return it; if no, return NULL.
637 struct page
*find_get_page(struct address_space
*mapping
, pgoff_t offset
)
645 pagep
= radix_tree_lookup_slot(&mapping
->page_tree
, offset
);
647 page
= radix_tree_deref_slot(pagep
);
648 if (unlikely(!page
|| page
== RADIX_TREE_RETRY
))
651 if (!page_cache_get_speculative(page
))
655 * Has the page moved?
656 * This is part of the lockless pagecache protocol. See
657 * include/linux/pagemap.h for details.
659 if (unlikely(page
!= *pagep
)) {
660 page_cache_release(page
);
668 EXPORT_SYMBOL(find_get_page
);
671 * find_lock_page - locate, pin and lock a pagecache page
672 * @mapping: the address_space to search
673 * @offset: the page index
675 * Locates the desired pagecache page, locks it, increments its reference
676 * count and returns its address.
678 * Returns zero if the page was not present. find_lock_page() may sleep.
680 struct page
*find_lock_page(struct address_space
*mapping
, pgoff_t offset
)
685 page
= find_get_page(mapping
, offset
);
688 /* Has the page been truncated? */
689 if (unlikely(page
->mapping
!= mapping
)) {
691 page_cache_release(page
);
694 VM_BUG_ON(page
->index
!= offset
);
698 EXPORT_SYMBOL(find_lock_page
);
701 * find_or_create_page - locate or add a pagecache page
702 * @mapping: the page's address_space
703 * @index: the page's index into the mapping
704 * @gfp_mask: page allocation mode
706 * Locates a page in the pagecache. If the page is not present, a new page
707 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
708 * LRU list. The returned page is locked and has its reference count
711 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
714 * find_or_create_page() returns the desired page's address, or zero on
717 struct page
*find_or_create_page(struct address_space
*mapping
,
718 pgoff_t index
, gfp_t gfp_mask
)
723 page
= find_lock_page(mapping
, index
);
725 page
= __page_cache_alloc(gfp_mask
);
729 * We want a regular kernel memory (not highmem or DMA etc)
730 * allocation for the radix tree nodes, but we need to honour
731 * the context-specific requirements the caller has asked for.
732 * GFP_RECLAIM_MASK collects those requirements.
734 err
= add_to_page_cache_lru(page
, mapping
, index
,
735 (gfp_mask
& GFP_RECLAIM_MASK
));
737 page_cache_release(page
);
745 EXPORT_SYMBOL(find_or_create_page
);
748 * find_get_pages - gang pagecache lookup
749 * @mapping: The address_space to search
750 * @start: The starting page index
751 * @nr_pages: The maximum number of pages
752 * @pages: Where the resulting pages are placed
754 * find_get_pages() will search for and return a group of up to
755 * @nr_pages pages in the mapping. The pages are placed at @pages.
756 * find_get_pages() takes a reference against the returned pages.
758 * The search returns a group of mapping-contiguous pages with ascending
759 * indexes. There may be holes in the indices due to not-present pages.
761 * find_get_pages() returns the number of pages which were found.
763 unsigned find_get_pages(struct address_space
*mapping
, pgoff_t start
,
764 unsigned int nr_pages
, struct page
**pages
)
768 unsigned int nr_found
;
772 nr_found
= radix_tree_gang_lookup_slot(&mapping
->page_tree
,
773 (void ***)pages
, start
, nr_pages
);
775 for (i
= 0; i
< nr_found
; i
++) {
778 page
= radix_tree_deref_slot((void **)pages
[i
]);
782 * this can only trigger if nr_found == 1, making livelock
785 if (unlikely(page
== RADIX_TREE_RETRY
))
788 if (!page_cache_get_speculative(page
))
791 /* Has the page moved? */
792 if (unlikely(page
!= *((void **)pages
[i
]))) {
793 page_cache_release(page
);
803 EXPORT_SYMBOL(find_get_pages
);
806 * find_get_pages_contig - gang contiguous pagecache lookup
807 * @mapping: The address_space to search
808 * @index: The starting page index
809 * @nr_pages: The maximum number of pages
810 * @pages: Where the resulting pages are placed
812 * find_get_pages_contig() works exactly like find_get_pages(), except
813 * that the returned number of pages are guaranteed to be contiguous.
815 * find_get_pages_contig() returns the number of pages which were found.
817 unsigned find_get_pages_contig(struct address_space
*mapping
, pgoff_t index
,
818 unsigned int nr_pages
, struct page
**pages
)
822 unsigned int nr_found
;
826 nr_found
= radix_tree_gang_lookup_slot(&mapping
->page_tree
,
827 (void ***)pages
, index
, nr_pages
);
829 for (i
= 0; i
< nr_found
; i
++) {
832 page
= radix_tree_deref_slot((void **)pages
[i
]);
836 * this can only trigger if nr_found == 1, making livelock
839 if (unlikely(page
== RADIX_TREE_RETRY
))
842 if (page
->mapping
== NULL
|| page
->index
!= index
)
845 if (!page_cache_get_speculative(page
))
848 /* Has the page moved? */
849 if (unlikely(page
!= *((void **)pages
[i
]))) {
850 page_cache_release(page
);
861 EXPORT_SYMBOL(find_get_pages_contig
);
864 * find_get_pages_tag - find and return pages that match @tag
865 * @mapping: the address_space to search
866 * @index: the starting page index
867 * @tag: the tag index
868 * @nr_pages: the maximum number of pages
869 * @pages: where the resulting pages are placed
871 * Like find_get_pages, except we only return pages which are tagged with
872 * @tag. We update @index to index the next page for the traversal.
874 unsigned find_get_pages_tag(struct address_space
*mapping
, pgoff_t
*index
,
875 int tag
, unsigned int nr_pages
, struct page
**pages
)
879 unsigned int nr_found
;
883 nr_found
= radix_tree_gang_lookup_tag_slot(&mapping
->page_tree
,
884 (void ***)pages
, *index
, nr_pages
, tag
);
886 for (i
= 0; i
< nr_found
; i
++) {
889 page
= radix_tree_deref_slot((void **)pages
[i
]);
893 * this can only trigger if nr_found == 1, making livelock
896 if (unlikely(page
== RADIX_TREE_RETRY
))
899 if (!page_cache_get_speculative(page
))
902 /* Has the page moved? */
903 if (unlikely(page
!= *((void **)pages
[i
]))) {
904 page_cache_release(page
);
914 *index
= pages
[ret
- 1]->index
+ 1;
918 EXPORT_SYMBOL(find_get_pages_tag
);
921 * grab_cache_page_nowait - returns locked page at given index in given cache
922 * @mapping: target address_space
923 * @index: the page index
925 * Same as grab_cache_page(), but do not wait if the page is unavailable.
926 * This is intended for speculative data generators, where the data can
927 * be regenerated if the page couldn't be grabbed. This routine should
928 * be safe to call while holding the lock for another page.
930 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
931 * and deadlock against the caller's locked page.
934 grab_cache_page_nowait(struct address_space
*mapping
, pgoff_t index
)
936 struct page
*page
= find_get_page(mapping
, index
);
939 if (trylock_page(page
))
941 page_cache_release(page
);
944 page
= __page_cache_alloc(mapping_gfp_mask(mapping
) & ~__GFP_FS
);
945 if (page
&& add_to_page_cache_lru(page
, mapping
, index
, GFP_NOFS
)) {
946 page_cache_release(page
);
951 EXPORT_SYMBOL(grab_cache_page_nowait
);
954 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
955 * a _large_ part of the i/o request. Imagine the worst scenario:
957 * ---R__________________________________________B__________
958 * ^ reading here ^ bad block(assume 4k)
960 * read(R) => miss => readahead(R...B) => media error => frustrating retries
961 * => failing the whole request => read(R) => read(R+1) =>
962 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
963 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
964 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
966 * It is going insane. Fix it by quickly scaling down the readahead size.
968 static void shrink_readahead_size_eio(struct file
*filp
,
969 struct file_ra_state
*ra
)
975 * do_generic_file_read - generic file read routine
976 * @filp: the file to read
977 * @ppos: current file position
978 * @desc: read_descriptor
979 * @actor: read method
981 * This is a generic file read routine, and uses the
982 * mapping->a_ops->readpage() function for the actual low-level stuff.
984 * This is really ugly. But the goto's actually try to clarify some
985 * of the logic when it comes to error handling etc.
987 static void do_generic_file_read(struct file
*filp
, loff_t
*ppos
,
988 read_descriptor_t
*desc
, read_actor_t actor
)
990 struct address_space
*mapping
= filp
->f_mapping
;
991 struct inode
*inode
= mapping
->host
;
992 struct file_ra_state
*ra
= &filp
->f_ra
;
996 unsigned long offset
; /* offset into pagecache page */
997 unsigned int prev_offset
;
1000 index
= *ppos
>> PAGE_CACHE_SHIFT
;
1001 prev_index
= ra
->prev_pos
>> PAGE_CACHE_SHIFT
;
1002 prev_offset
= ra
->prev_pos
& (PAGE_CACHE_SIZE
-1);
1003 last_index
= (*ppos
+ desc
->count
+ PAGE_CACHE_SIZE
-1) >> PAGE_CACHE_SHIFT
;
1004 offset
= *ppos
& ~PAGE_CACHE_MASK
;
1010 unsigned long nr
, ret
;
1014 page
= find_get_page(mapping
, index
);
1016 page_cache_sync_readahead(mapping
,
1018 index
, last_index
- index
);
1019 page
= find_get_page(mapping
, index
);
1020 if (unlikely(page
== NULL
))
1021 goto no_cached_page
;
1023 if (PageReadahead(page
)) {
1024 page_cache_async_readahead(mapping
,
1026 index
, last_index
- index
);
1028 if (!PageUptodate(page
)) {
1029 if (inode
->i_blkbits
== PAGE_CACHE_SHIFT
||
1030 !mapping
->a_ops
->is_partially_uptodate
)
1031 goto page_not_up_to_date
;
1032 if (!trylock_page(page
))
1033 goto page_not_up_to_date
;
1034 if (!mapping
->a_ops
->is_partially_uptodate(page
,
1036 goto page_not_up_to_date_locked
;
1041 * i_size must be checked after we know the page is Uptodate.
1043 * Checking i_size after the check allows us to calculate
1044 * the correct value for "nr", which means the zero-filled
1045 * part of the page is not copied back to userspace (unless
1046 * another truncate extends the file - this is desired though).
1049 isize
= i_size_read(inode
);
1050 end_index
= (isize
- 1) >> PAGE_CACHE_SHIFT
;
1051 if (unlikely(!isize
|| index
> end_index
)) {
1052 page_cache_release(page
);
1056 /* nr is the maximum number of bytes to copy from this page */
1057 nr
= PAGE_CACHE_SIZE
;
1058 if (index
== end_index
) {
1059 nr
= ((isize
- 1) & ~PAGE_CACHE_MASK
) + 1;
1061 page_cache_release(page
);
1067 /* If users can be writing to this page using arbitrary
1068 * virtual addresses, take care about potential aliasing
1069 * before reading the page on the kernel side.
1071 if (mapping_writably_mapped(mapping
))
1072 flush_dcache_page(page
);
1075 * When a sequential read accesses a page several times,
1076 * only mark it as accessed the first time.
1078 if (prev_index
!= index
|| offset
!= prev_offset
)
1079 mark_page_accessed(page
);
1083 * Ok, we have the page, and it's up-to-date, so
1084 * now we can copy it to user space...
1086 * The actor routine returns how many bytes were actually used..
1087 * NOTE! This may not be the same as how much of a user buffer
1088 * we filled up (we may be padding etc), so we can only update
1089 * "pos" here (the actor routine has to update the user buffer
1090 * pointers and the remaining count).
1092 ret
= actor(desc
, page
, offset
, nr
);
1094 index
+= offset
>> PAGE_CACHE_SHIFT
;
1095 offset
&= ~PAGE_CACHE_MASK
;
1096 prev_offset
= offset
;
1098 page_cache_release(page
);
1099 if (ret
== nr
&& desc
->count
)
1103 page_not_up_to_date
:
1104 /* Get exclusive access to the page ... */
1105 error
= lock_page_killable(page
);
1106 if (unlikely(error
))
1107 goto readpage_error
;
1109 page_not_up_to_date_locked
:
1110 /* Did it get truncated before we got the lock? */
1111 if (!page
->mapping
) {
1113 page_cache_release(page
);
1117 /* Did somebody else fill it already? */
1118 if (PageUptodate(page
)) {
1124 /* Start the actual read. The read will unlock the page. */
1125 error
= mapping
->a_ops
->readpage(filp
, page
);
1127 if (unlikely(error
)) {
1128 if (error
== AOP_TRUNCATED_PAGE
) {
1129 page_cache_release(page
);
1132 goto readpage_error
;
1135 if (!PageUptodate(page
)) {
1136 error
= lock_page_killable(page
);
1137 if (unlikely(error
))
1138 goto readpage_error
;
1139 if (!PageUptodate(page
)) {
1140 if (page
->mapping
== NULL
) {
1142 * invalidate_inode_pages got it
1145 page_cache_release(page
);
1149 shrink_readahead_size_eio(filp
, ra
);
1151 goto readpage_error
;
1159 /* UHHUH! A synchronous read error occurred. Report it */
1160 desc
->error
= error
;
1161 page_cache_release(page
);
1166 * Ok, it wasn't cached, so we need to create a new
1169 page
= page_cache_alloc_cold(mapping
);
1171 desc
->error
= -ENOMEM
;
1174 error
= add_to_page_cache_lru(page
, mapping
,
1177 page_cache_release(page
);
1178 if (error
== -EEXIST
)
1180 desc
->error
= error
;
1187 ra
->prev_pos
= prev_index
;
1188 ra
->prev_pos
<<= PAGE_CACHE_SHIFT
;
1189 ra
->prev_pos
|= prev_offset
;
1191 *ppos
= ((loff_t
)index
<< PAGE_CACHE_SHIFT
) + offset
;
1192 file_accessed(filp
);
1195 int file_read_actor(read_descriptor_t
*desc
, struct page
*page
,
1196 unsigned long offset
, unsigned long size
)
1199 unsigned long left
, count
= desc
->count
;
1205 * Faults on the destination of a read are common, so do it before
1208 if (!fault_in_pages_writeable(desc
->arg
.buf
, size
)) {
1209 kaddr
= kmap_atomic(page
, KM_USER0
);
1210 left
= __copy_to_user_inatomic(desc
->arg
.buf
,
1211 kaddr
+ offset
, size
);
1212 kunmap_atomic(kaddr
, KM_USER0
);
1217 /* Do it the slow way */
1219 left
= __copy_to_user(desc
->arg
.buf
, kaddr
+ offset
, size
);
1224 desc
->error
= -EFAULT
;
1227 desc
->count
= count
- size
;
1228 desc
->written
+= size
;
1229 desc
->arg
.buf
+= size
;
1234 * Performs necessary checks before doing a write
1235 * @iov: io vector request
1236 * @nr_segs: number of segments in the iovec
1237 * @count: number of bytes to write
1238 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1240 * Adjust number of segments and amount of bytes to write (nr_segs should be
1241 * properly initialized first). Returns appropriate error code that caller
1242 * should return or zero in case that write should be allowed.
1244 int generic_segment_checks(const struct iovec
*iov
,
1245 unsigned long *nr_segs
, size_t *count
, int access_flags
)
1249 for (seg
= 0; seg
< *nr_segs
; seg
++) {
1250 const struct iovec
*iv
= &iov
[seg
];
1253 * If any segment has a negative length, or the cumulative
1254 * length ever wraps negative then return -EINVAL.
1257 if (unlikely((ssize_t
)(cnt
|iv
->iov_len
) < 0))
1259 if (access_ok(access_flags
, iv
->iov_base
, iv
->iov_len
))
1264 cnt
-= iv
->iov_len
; /* This segment is no good */
1270 EXPORT_SYMBOL(generic_segment_checks
);
1273 * generic_file_aio_read - generic filesystem read routine
1274 * @iocb: kernel I/O control block
1275 * @iov: io vector request
1276 * @nr_segs: number of segments in the iovec
1277 * @pos: current file position
1279 * This is the "read()" routine for all filesystems
1280 * that can use the page cache directly.
1283 generic_file_aio_read(struct kiocb
*iocb
, const struct iovec
*iov
,
1284 unsigned long nr_segs
, loff_t pos
)
1286 struct file
*filp
= iocb
->ki_filp
;
1290 loff_t
*ppos
= &iocb
->ki_pos
;
1293 retval
= generic_segment_checks(iov
, &nr_segs
, &count
, VERIFY_WRITE
);
1297 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1298 if (filp
->f_flags
& O_DIRECT
) {
1300 struct address_space
*mapping
;
1301 struct inode
*inode
;
1303 mapping
= filp
->f_mapping
;
1304 inode
= mapping
->host
;
1306 goto out
; /* skip atime */
1307 size
= i_size_read(inode
);
1309 retval
= filemap_write_and_wait_range(mapping
, pos
,
1310 pos
+ iov_length(iov
, nr_segs
) - 1);
1312 retval
= mapping
->a_ops
->direct_IO(READ
, iocb
,
1316 *ppos
= pos
+ retval
;
1318 file_accessed(filp
);
1324 for (seg
= 0; seg
< nr_segs
; seg
++) {
1325 read_descriptor_t desc
;
1328 desc
.arg
.buf
= iov
[seg
].iov_base
;
1329 desc
.count
= iov
[seg
].iov_len
;
1330 if (desc
.count
== 0)
1333 do_generic_file_read(filp
, ppos
, &desc
, file_read_actor
);
1334 retval
+= desc
.written
;
1336 retval
= retval
?: desc
.error
;
1345 EXPORT_SYMBOL(generic_file_aio_read
);
1348 do_readahead(struct address_space
*mapping
, struct file
*filp
,
1349 pgoff_t index
, unsigned long nr
)
1351 if (!mapping
|| !mapping
->a_ops
|| !mapping
->a_ops
->readpage
)
1354 force_page_cache_readahead(mapping
, filp
, index
, nr
);
1358 SYSCALL_DEFINE(readahead
)(int fd
, loff_t offset
, size_t count
)
1366 if (file
->f_mode
& FMODE_READ
) {
1367 struct address_space
*mapping
= file
->f_mapping
;
1368 pgoff_t start
= offset
>> PAGE_CACHE_SHIFT
;
1369 pgoff_t end
= (offset
+ count
- 1) >> PAGE_CACHE_SHIFT
;
1370 unsigned long len
= end
- start
+ 1;
1371 ret
= do_readahead(mapping
, file
, start
, len
);
1377 #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
1378 asmlinkage
long SyS_readahead(long fd
, loff_t offset
, long count
)
1380 return SYSC_readahead((int) fd
, offset
, (size_t) count
);
1382 SYSCALL_ALIAS(sys_readahead
, SyS_readahead
);
1387 * page_cache_read - adds requested page to the page cache if not already there
1388 * @file: file to read
1389 * @offset: page index
1391 * This adds the requested page to the page cache if it isn't already there,
1392 * and schedules an I/O to read in its contents from disk.
1394 static int page_cache_read(struct file
*file
, pgoff_t offset
)
1396 struct address_space
*mapping
= file
->f_mapping
;
1401 page
= page_cache_alloc_cold(mapping
);
1405 ret
= add_to_page_cache_lru(page
, mapping
, offset
, GFP_KERNEL
);
1407 ret
= mapping
->a_ops
->readpage(file
, page
);
1408 else if (ret
== -EEXIST
)
1409 ret
= 0; /* losing race to add is OK */
1411 page_cache_release(page
);
1413 } while (ret
== AOP_TRUNCATED_PAGE
);
1418 #define MMAP_LOTSAMISS (100)
1421 * Synchronous readahead happens when we don't even find
1422 * a page in the page cache at all.
1424 static void do_sync_mmap_readahead(struct vm_area_struct
*vma
,
1425 struct file_ra_state
*ra
,
1429 unsigned long ra_pages
;
1430 struct address_space
*mapping
= file
->f_mapping
;
1432 /* If we don't want any read-ahead, don't bother */
1433 if (VM_RandomReadHint(vma
))
1436 if (VM_SequentialReadHint(vma
) ||
1437 offset
- 1 == (ra
->prev_pos
>> PAGE_CACHE_SHIFT
)) {
1438 page_cache_sync_readahead(mapping
, ra
, file
, offset
,
1443 if (ra
->mmap_miss
< INT_MAX
)
1447 * Do we miss much more than hit in this file? If so,
1448 * stop bothering with read-ahead. It will only hurt.
1450 if (ra
->mmap_miss
> MMAP_LOTSAMISS
)
1456 ra_pages
= max_sane_readahead(ra
->ra_pages
);
1458 ra
->start
= max_t(long, 0, offset
- ra_pages
/2);
1459 ra
->size
= ra_pages
;
1461 ra_submit(ra
, mapping
, file
);
1466 * Asynchronous readahead happens when we find the page and PG_readahead,
1467 * so we want to possibly extend the readahead further..
1469 static void do_async_mmap_readahead(struct vm_area_struct
*vma
,
1470 struct file_ra_state
*ra
,
1475 struct address_space
*mapping
= file
->f_mapping
;
1477 /* If we don't want any read-ahead, don't bother */
1478 if (VM_RandomReadHint(vma
))
1480 if (ra
->mmap_miss
> 0)
1482 if (PageReadahead(page
))
1483 page_cache_async_readahead(mapping
, ra
, file
,
1484 page
, offset
, ra
->ra_pages
);
1488 * filemap_fault - read in file data for page fault handling
1489 * @vma: vma in which the fault was taken
1490 * @vmf: struct vm_fault containing details of the fault
1492 * filemap_fault() is invoked via the vma operations vector for a
1493 * mapped memory region to read in file data during a page fault.
1495 * The goto's are kind of ugly, but this streamlines the normal case of having
1496 * it in the page cache, and handles the special cases reasonably without
1497 * having a lot of duplicated code.
1499 int filemap_fault(struct vm_area_struct
*vma
, struct vm_fault
*vmf
)
1502 struct file
*file
= vma
->vm_file
;
1503 struct address_space
*mapping
= file
->f_mapping
;
1504 struct file_ra_state
*ra
= &file
->f_ra
;
1505 struct inode
*inode
= mapping
->host
;
1506 pgoff_t offset
= vmf
->pgoff
;
1511 size
= (i_size_read(inode
) + PAGE_CACHE_SIZE
- 1) >> PAGE_CACHE_SHIFT
;
1513 return VM_FAULT_SIGBUS
;
1516 * Do we have something in the page cache already?
1518 page
= find_get_page(mapping
, offset
);
1521 * We found the page, so try async readahead before
1522 * waiting for the lock.
1524 do_async_mmap_readahead(vma
, ra
, file
, page
, offset
);
1527 /* Did it get truncated? */
1528 if (unlikely(page
->mapping
!= mapping
)) {
1531 goto no_cached_page
;
1534 /* No page in the page cache at all */
1535 do_sync_mmap_readahead(vma
, ra
, file
, offset
);
1536 count_vm_event(PGMAJFAULT
);
1537 ret
= VM_FAULT_MAJOR
;
1539 page
= find_lock_page(mapping
, offset
);
1541 goto no_cached_page
;
1545 * We have a locked page in the page cache, now we need to check
1546 * that it's up-to-date. If not, it is going to be due to an error.
1548 if (unlikely(!PageUptodate(page
)))
1549 goto page_not_uptodate
;
1552 * Found the page and have a reference on it.
1553 * We must recheck i_size under page lock.
1555 size
= (i_size_read(inode
) + PAGE_CACHE_SIZE
- 1) >> PAGE_CACHE_SHIFT
;
1556 if (unlikely(offset
>= size
)) {
1558 page_cache_release(page
);
1559 return VM_FAULT_SIGBUS
;
1562 ra
->prev_pos
= (loff_t
)offset
<< PAGE_CACHE_SHIFT
;
1564 return ret
| VM_FAULT_LOCKED
;
1568 * We're only likely to ever get here if MADV_RANDOM is in
1571 error
= page_cache_read(file
, offset
);
1574 * The page we want has now been added to the page cache.
1575 * In the unlikely event that someone removed it in the
1576 * meantime, we'll just come back here and read it again.
1582 * An error return from page_cache_read can result if the
1583 * system is low on memory, or a problem occurs while trying
1586 if (error
== -ENOMEM
)
1587 return VM_FAULT_OOM
;
1588 return VM_FAULT_SIGBUS
;
1592 * Umm, take care of errors if the page isn't up-to-date.
1593 * Try to re-read it _once_. We do this synchronously,
1594 * because there really aren't any performance issues here
1595 * and we need to check for errors.
1597 ClearPageError(page
);
1598 error
= mapping
->a_ops
->readpage(file
, page
);
1600 wait_on_page_locked(page
);
1601 if (!PageUptodate(page
))
1604 page_cache_release(page
);
1606 if (!error
|| error
== AOP_TRUNCATED_PAGE
)
1609 /* Things didn't work out. Return zero to tell the mm layer so. */
1610 shrink_readahead_size_eio(file
, ra
);
1611 return VM_FAULT_SIGBUS
;
1613 EXPORT_SYMBOL(filemap_fault
);
1615 const struct vm_operations_struct generic_file_vm_ops
= {
1616 .fault
= filemap_fault
,
1619 /* This is used for a general mmap of a disk file */
1621 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
1623 struct address_space
*mapping
= file
->f_mapping
;
1625 if (!mapping
->a_ops
->readpage
)
1627 file_accessed(file
);
1628 vma
->vm_ops
= &generic_file_vm_ops
;
1629 vma
->vm_flags
|= VM_CAN_NONLINEAR
;
1634 * This is for filesystems which do not implement ->writepage.
1636 int generic_file_readonly_mmap(struct file
*file
, struct vm_area_struct
*vma
)
1638 if ((vma
->vm_flags
& VM_SHARED
) && (vma
->vm_flags
& VM_MAYWRITE
))
1640 return generic_file_mmap(file
, vma
);
1643 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
1647 int generic_file_readonly_mmap(struct file
* file
, struct vm_area_struct
* vma
)
1651 #endif /* CONFIG_MMU */
1653 EXPORT_SYMBOL(generic_file_mmap
);
1654 EXPORT_SYMBOL(generic_file_readonly_mmap
);
1656 static struct page
*__read_cache_page(struct address_space
*mapping
,
1658 int (*filler
)(void *,struct page
*),
1664 page
= find_get_page(mapping
, index
);
1666 page
= page_cache_alloc_cold(mapping
);
1668 return ERR_PTR(-ENOMEM
);
1669 err
= add_to_page_cache_lru(page
, mapping
, index
, GFP_KERNEL
);
1670 if (unlikely(err
)) {
1671 page_cache_release(page
);
1674 /* Presumably ENOMEM for radix tree node */
1675 return ERR_PTR(err
);
1677 err
= filler(data
, page
);
1679 page_cache_release(page
);
1680 page
= ERR_PTR(err
);
1687 * read_cache_page_async - read into page cache, fill it if needed
1688 * @mapping: the page's address_space
1689 * @index: the page index
1690 * @filler: function to perform the read
1691 * @data: destination for read data
1693 * Same as read_cache_page, but don't wait for page to become unlocked
1694 * after submitting it to the filler.
1696 * Read into the page cache. If a page already exists, and PageUptodate() is
1697 * not set, try to fill the page but don't wait for it to become unlocked.
1699 * If the page does not get brought uptodate, return -EIO.
1701 struct page
*read_cache_page_async(struct address_space
*mapping
,
1703 int (*filler
)(void *,struct page
*),
1710 page
= __read_cache_page(mapping
, index
, filler
, data
);
1713 if (PageUptodate(page
))
1717 if (!page
->mapping
) {
1719 page_cache_release(page
);
1722 if (PageUptodate(page
)) {
1726 err
= filler(data
, page
);
1728 page_cache_release(page
);
1729 return ERR_PTR(err
);
1732 mark_page_accessed(page
);
1735 EXPORT_SYMBOL(read_cache_page_async
);
1738 * read_cache_page - read into page cache, fill it if needed
1739 * @mapping: the page's address_space
1740 * @index: the page index
1741 * @filler: function to perform the read
1742 * @data: destination for read data
1744 * Read into the page cache. If a page already exists, and PageUptodate() is
1745 * not set, try to fill the page then wait for it to become unlocked.
1747 * If the page does not get brought uptodate, return -EIO.
1749 struct page
*read_cache_page(struct address_space
*mapping
,
1751 int (*filler
)(void *,struct page
*),
1756 page
= read_cache_page_async(mapping
, index
, filler
, data
);
1759 wait_on_page_locked(page
);
1760 if (!PageUptodate(page
)) {
1761 page_cache_release(page
);
1762 page
= ERR_PTR(-EIO
);
1767 EXPORT_SYMBOL(read_cache_page
);
1770 * The logic we want is
1772 * if suid or (sgid and xgrp)
1775 int should_remove_suid(struct dentry
*dentry
)
1777 mode_t mode
= dentry
->d_inode
->i_mode
;
1780 /* suid always must be killed */
1781 if (unlikely(mode
& S_ISUID
))
1782 kill
= ATTR_KILL_SUID
;
1785 * sgid without any exec bits is just a mandatory locking mark; leave
1786 * it alone. If some exec bits are set, it's a real sgid; kill it.
1788 if (unlikely((mode
& S_ISGID
) && (mode
& S_IXGRP
)))
1789 kill
|= ATTR_KILL_SGID
;
1791 if (unlikely(kill
&& !capable(CAP_FSETID
) && S_ISREG(mode
)))
1796 EXPORT_SYMBOL(should_remove_suid
);
1798 static int __remove_suid(struct dentry
*dentry
, int kill
)
1800 struct iattr newattrs
;
1802 newattrs
.ia_valid
= ATTR_FORCE
| kill
;
1803 return notify_change(dentry
, &newattrs
);
1806 int file_remove_suid(struct file
*file
)
1808 struct dentry
*dentry
= file
->f_path
.dentry
;
1809 int killsuid
= should_remove_suid(dentry
);
1810 int killpriv
= security_inode_need_killpriv(dentry
);
1816 error
= security_inode_killpriv(dentry
);
1817 if (!error
&& killsuid
)
1818 error
= __remove_suid(dentry
, killsuid
);
1822 EXPORT_SYMBOL(file_remove_suid
);
1824 static size_t __iovec_copy_from_user_inatomic(char *vaddr
,
1825 const struct iovec
*iov
, size_t base
, size_t bytes
)
1827 size_t copied
= 0, left
= 0;
1830 char __user
*buf
= iov
->iov_base
+ base
;
1831 int copy
= min(bytes
, iov
->iov_len
- base
);
1834 left
= __copy_from_user_inatomic(vaddr
, buf
, copy
);
1843 return copied
- left
;
1847 * Copy as much as we can into the page and return the number of bytes which
1848 * were sucessfully copied. If a fault is encountered then return the number of
1849 * bytes which were copied.
1851 size_t iov_iter_copy_from_user_atomic(struct page
*page
,
1852 struct iov_iter
*i
, unsigned long offset
, size_t bytes
)
1857 BUG_ON(!in_atomic());
1858 kaddr
= kmap_atomic(page
, KM_USER0
);
1859 if (likely(i
->nr_segs
== 1)) {
1861 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
1862 left
= __copy_from_user_inatomic(kaddr
+ offset
, buf
, bytes
);
1863 copied
= bytes
- left
;
1865 copied
= __iovec_copy_from_user_inatomic(kaddr
+ offset
,
1866 i
->iov
, i
->iov_offset
, bytes
);
1868 kunmap_atomic(kaddr
, KM_USER0
);
1872 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic
);
1875 * This has the same sideeffects and return value as
1876 * iov_iter_copy_from_user_atomic().
1877 * The difference is that it attempts to resolve faults.
1878 * Page must not be locked.
1880 size_t iov_iter_copy_from_user(struct page
*page
,
1881 struct iov_iter
*i
, unsigned long offset
, size_t bytes
)
1887 if (likely(i
->nr_segs
== 1)) {
1889 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
1890 left
= __copy_from_user(kaddr
+ offset
, buf
, bytes
);
1891 copied
= bytes
- left
;
1893 copied
= __iovec_copy_from_user_inatomic(kaddr
+ offset
,
1894 i
->iov
, i
->iov_offset
, bytes
);
1899 EXPORT_SYMBOL(iov_iter_copy_from_user
);
1901 void iov_iter_advance(struct iov_iter
*i
, size_t bytes
)
1903 BUG_ON(i
->count
< bytes
);
1905 if (likely(i
->nr_segs
== 1)) {
1906 i
->iov_offset
+= bytes
;
1909 const struct iovec
*iov
= i
->iov
;
1910 size_t base
= i
->iov_offset
;
1913 * The !iov->iov_len check ensures we skip over unlikely
1914 * zero-length segments (without overruning the iovec).
1916 while (bytes
|| unlikely(i
->count
&& !iov
->iov_len
)) {
1919 copy
= min(bytes
, iov
->iov_len
- base
);
1920 BUG_ON(!i
->count
|| i
->count
< copy
);
1924 if (iov
->iov_len
== base
) {
1930 i
->iov_offset
= base
;
1933 EXPORT_SYMBOL(iov_iter_advance
);
1936 * Fault in the first iovec of the given iov_iter, to a maximum length
1937 * of bytes. Returns 0 on success, or non-zero if the memory could not be
1938 * accessed (ie. because it is an invalid address).
1940 * writev-intensive code may want this to prefault several iovecs -- that
1941 * would be possible (callers must not rely on the fact that _only_ the
1942 * first iovec will be faulted with the current implementation).
1944 int iov_iter_fault_in_readable(struct iov_iter
*i
, size_t bytes
)
1946 char __user
*buf
= i
->iov
->iov_base
+ i
->iov_offset
;
1947 bytes
= min(bytes
, i
->iov
->iov_len
- i
->iov_offset
);
1948 return fault_in_pages_readable(buf
, bytes
);
1950 EXPORT_SYMBOL(iov_iter_fault_in_readable
);
1953 * Return the count of just the current iov_iter segment.
1955 size_t iov_iter_single_seg_count(struct iov_iter
*i
)
1957 const struct iovec
*iov
= i
->iov
;
1958 if (i
->nr_segs
== 1)
1961 return min(i
->count
, iov
->iov_len
- i
->iov_offset
);
1963 EXPORT_SYMBOL(iov_iter_single_seg_count
);
1966 * Performs necessary checks before doing a write
1968 * Can adjust writing position or amount of bytes to write.
1969 * Returns appropriate error code that caller should return or
1970 * zero in case that write should be allowed.
1972 inline int generic_write_checks(struct file
*file
, loff_t
*pos
, size_t *count
, int isblk
)
1974 struct inode
*inode
= file
->f_mapping
->host
;
1975 unsigned long limit
= current
->signal
->rlim
[RLIMIT_FSIZE
].rlim_cur
;
1977 if (unlikely(*pos
< 0))
1981 /* FIXME: this is for backwards compatibility with 2.4 */
1982 if (file
->f_flags
& O_APPEND
)
1983 *pos
= i_size_read(inode
);
1985 if (limit
!= RLIM_INFINITY
) {
1986 if (*pos
>= limit
) {
1987 send_sig(SIGXFSZ
, current
, 0);
1990 if (*count
> limit
- (typeof(limit
))*pos
) {
1991 *count
= limit
- (typeof(limit
))*pos
;
1999 if (unlikely(*pos
+ *count
> MAX_NON_LFS
&&
2000 !(file
->f_flags
& O_LARGEFILE
))) {
2001 if (*pos
>= MAX_NON_LFS
) {
2004 if (*count
> MAX_NON_LFS
- (unsigned long)*pos
) {
2005 *count
= MAX_NON_LFS
- (unsigned long)*pos
;
2010 * Are we about to exceed the fs block limit ?
2012 * If we have written data it becomes a short write. If we have
2013 * exceeded without writing data we send a signal and return EFBIG.
2014 * Linus frestrict idea will clean these up nicely..
2016 if (likely(!isblk
)) {
2017 if (unlikely(*pos
>= inode
->i_sb
->s_maxbytes
)) {
2018 if (*count
|| *pos
> inode
->i_sb
->s_maxbytes
) {
2021 /* zero-length writes at ->s_maxbytes are OK */
2024 if (unlikely(*pos
+ *count
> inode
->i_sb
->s_maxbytes
))
2025 *count
= inode
->i_sb
->s_maxbytes
- *pos
;
2029 if (bdev_read_only(I_BDEV(inode
)))
2031 isize
= i_size_read(inode
);
2032 if (*pos
>= isize
) {
2033 if (*count
|| *pos
> isize
)
2037 if (*pos
+ *count
> isize
)
2038 *count
= isize
- *pos
;
2045 EXPORT_SYMBOL(generic_write_checks
);
2047 int pagecache_write_begin(struct file
*file
, struct address_space
*mapping
,
2048 loff_t pos
, unsigned len
, unsigned flags
,
2049 struct page
**pagep
, void **fsdata
)
2051 const struct address_space_operations
*aops
= mapping
->a_ops
;
2053 return aops
->write_begin(file
, mapping
, pos
, len
, flags
,
2056 EXPORT_SYMBOL(pagecache_write_begin
);
2058 int pagecache_write_end(struct file
*file
, struct address_space
*mapping
,
2059 loff_t pos
, unsigned len
, unsigned copied
,
2060 struct page
*page
, void *fsdata
)
2062 const struct address_space_operations
*aops
= mapping
->a_ops
;
2064 mark_page_accessed(page
);
2065 return aops
->write_end(file
, mapping
, pos
, len
, copied
, page
, fsdata
);
2067 EXPORT_SYMBOL(pagecache_write_end
);
2070 generic_file_direct_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2071 unsigned long *nr_segs
, loff_t pos
, loff_t
*ppos
,
2072 size_t count
, size_t ocount
)
2074 struct file
*file
= iocb
->ki_filp
;
2075 struct address_space
*mapping
= file
->f_mapping
;
2076 struct inode
*inode
= mapping
->host
;
2081 if (count
!= ocount
)
2082 *nr_segs
= iov_shorten((struct iovec
*)iov
, *nr_segs
, count
);
2084 write_len
= iov_length(iov
, *nr_segs
);
2085 end
= (pos
+ write_len
- 1) >> PAGE_CACHE_SHIFT
;
2087 written
= filemap_write_and_wait_range(mapping
, pos
, pos
+ write_len
- 1);
2092 * After a write we want buffered reads to be sure to go to disk to get
2093 * the new data. We invalidate clean cached page from the region we're
2094 * about to write. We do this *before* the write so that we can return
2095 * without clobbering -EIOCBQUEUED from ->direct_IO().
2097 if (mapping
->nrpages
) {
2098 written
= invalidate_inode_pages2_range(mapping
,
2099 pos
>> PAGE_CACHE_SHIFT
, end
);
2101 * If a page can not be invalidated, return 0 to fall back
2102 * to buffered write.
2105 if (written
== -EBUSY
)
2111 written
= mapping
->a_ops
->direct_IO(WRITE
, iocb
, iov
, pos
, *nr_segs
);
2114 * Finally, try again to invalidate clean pages which might have been
2115 * cached by non-direct readahead, or faulted in by get_user_pages()
2116 * if the source of the write was an mmap'ed region of the file
2117 * we're writing. Either one is a pretty crazy thing to do,
2118 * so we don't support it 100%. If this invalidation
2119 * fails, tough, the write still worked...
2121 if (mapping
->nrpages
) {
2122 invalidate_inode_pages2_range(mapping
,
2123 pos
>> PAGE_CACHE_SHIFT
, end
);
2127 loff_t end
= pos
+ written
;
2128 if (end
> i_size_read(inode
) && !S_ISBLK(inode
->i_mode
)) {
2129 i_size_write(inode
, end
);
2130 mark_inode_dirty(inode
);
2137 EXPORT_SYMBOL(generic_file_direct_write
);
2140 * Find or create a page at the given pagecache position. Return the locked
2141 * page. This function is specifically for buffered writes.
2143 struct page
*grab_cache_page_write_begin(struct address_space
*mapping
,
2144 pgoff_t index
, unsigned flags
)
2148 gfp_t gfp_notmask
= 0;
2149 if (flags
& AOP_FLAG_NOFS
)
2150 gfp_notmask
= __GFP_FS
;
2152 page
= find_lock_page(mapping
, index
);
2156 page
= __page_cache_alloc(mapping_gfp_mask(mapping
) & ~gfp_notmask
);
2159 status
= add_to_page_cache_lru(page
, mapping
, index
,
2160 GFP_KERNEL
& ~gfp_notmask
);
2161 if (unlikely(status
)) {
2162 page_cache_release(page
);
2163 if (status
== -EEXIST
)
2169 EXPORT_SYMBOL(grab_cache_page_write_begin
);
2171 static ssize_t
generic_perform_write(struct file
*file
,
2172 struct iov_iter
*i
, loff_t pos
)
2174 struct address_space
*mapping
= file
->f_mapping
;
2175 const struct address_space_operations
*a_ops
= mapping
->a_ops
;
2177 ssize_t written
= 0;
2178 unsigned int flags
= 0;
2181 * Copies from kernel address space cannot fail (NFSD is a big user).
2183 if (segment_eq(get_fs(), KERNEL_DS
))
2184 flags
|= AOP_FLAG_UNINTERRUPTIBLE
;
2188 pgoff_t index
; /* Pagecache index for current page */
2189 unsigned long offset
; /* Offset into pagecache page */
2190 unsigned long bytes
; /* Bytes to write to page */
2191 size_t copied
; /* Bytes copied from user */
2194 offset
= (pos
& (PAGE_CACHE_SIZE
- 1));
2195 index
= pos
>> PAGE_CACHE_SHIFT
;
2196 bytes
= min_t(unsigned long, PAGE_CACHE_SIZE
- offset
,
2202 * Bring in the user page that we will copy from _first_.
2203 * Otherwise there's a nasty deadlock on copying from the
2204 * same page as we're writing to, without it being marked
2207 * Not only is this an optimisation, but it is also required
2208 * to check that the address is actually valid, when atomic
2209 * usercopies are used, below.
2211 if (unlikely(iov_iter_fault_in_readable(i
, bytes
))) {
2216 status
= a_ops
->write_begin(file
, mapping
, pos
, bytes
, flags
,
2218 if (unlikely(status
))
2221 pagefault_disable();
2222 copied
= iov_iter_copy_from_user_atomic(page
, i
, offset
, bytes
);
2224 flush_dcache_page(page
);
2226 mark_page_accessed(page
);
2227 status
= a_ops
->write_end(file
, mapping
, pos
, bytes
, copied
,
2229 if (unlikely(status
< 0))
2235 iov_iter_advance(i
, copied
);
2236 if (unlikely(copied
== 0)) {
2238 * If we were unable to copy any data at all, we must
2239 * fall back to a single segment length write.
2241 * If we didn't fallback here, we could livelock
2242 * because not all segments in the iov can be copied at
2243 * once without a pagefault.
2245 bytes
= min_t(unsigned long, PAGE_CACHE_SIZE
- offset
,
2246 iov_iter_single_seg_count(i
));
2252 balance_dirty_pages_ratelimited(mapping
);
2254 } while (iov_iter_count(i
));
2256 return written
? written
: status
;
2260 generic_file_buffered_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2261 unsigned long nr_segs
, loff_t pos
, loff_t
*ppos
,
2262 size_t count
, ssize_t written
)
2264 struct file
*file
= iocb
->ki_filp
;
2265 struct address_space
*mapping
= file
->f_mapping
;
2269 iov_iter_init(&i
, iov
, nr_segs
, count
, written
);
2270 status
= generic_perform_write(file
, &i
, pos
);
2272 if (likely(status
>= 0)) {
2274 *ppos
= pos
+ status
;
2278 * If we get here for O_DIRECT writes then we must have fallen through
2279 * to buffered writes (block instantiation inside i_size). So we sync
2280 * the file data here, to try to honour O_DIRECT expectations.
2282 if (unlikely(file
->f_flags
& O_DIRECT
) && written
)
2283 status
= filemap_write_and_wait_range(mapping
,
2284 pos
, pos
+ written
- 1);
2286 return written
? written
: status
;
2288 EXPORT_SYMBOL(generic_file_buffered_write
);
2291 * __generic_file_aio_write - write data to a file
2292 * @iocb: IO state structure (file, offset, etc.)
2293 * @iov: vector with data to write
2294 * @nr_segs: number of segments in the vector
2295 * @ppos: position where to write
2297 * This function does all the work needed for actually writing data to a
2298 * file. It does all basic checks, removes SUID from the file, updates
2299 * modification times and calls proper subroutines depending on whether we
2300 * do direct IO or a standard buffered write.
2302 * It expects i_mutex to be grabbed unless we work on a block device or similar
2303 * object which does not need locking at all.
2305 * This function does *not* take care of syncing data in case of O_SYNC write.
2306 * A caller has to handle it. This is mainly due to the fact that we want to
2307 * avoid syncing under i_mutex.
2309 ssize_t
__generic_file_aio_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2310 unsigned long nr_segs
, loff_t
*ppos
)
2312 struct file
*file
= iocb
->ki_filp
;
2313 struct address_space
* mapping
= file
->f_mapping
;
2314 size_t ocount
; /* original count */
2315 size_t count
; /* after file limit checks */
2316 struct inode
*inode
= mapping
->host
;
2322 err
= generic_segment_checks(iov
, &nr_segs
, &ocount
, VERIFY_READ
);
2329 vfs_check_frozen(inode
->i_sb
, SB_FREEZE_WRITE
);
2331 /* We can write back this queue in page reclaim */
2332 current
->backing_dev_info
= mapping
->backing_dev_info
;
2335 err
= generic_write_checks(file
, &pos
, &count
, S_ISBLK(inode
->i_mode
));
2342 err
= file_remove_suid(file
);
2346 file_update_time(file
);
2348 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2349 if (unlikely(file
->f_flags
& O_DIRECT
)) {
2351 ssize_t written_buffered
;
2353 written
= generic_file_direct_write(iocb
, iov
, &nr_segs
, pos
,
2354 ppos
, count
, ocount
);
2355 if (written
< 0 || written
== count
)
2358 * direct-io write to a hole: fall through to buffered I/O
2359 * for completing the rest of the request.
2363 written_buffered
= generic_file_buffered_write(iocb
, iov
,
2364 nr_segs
, pos
, ppos
, count
,
2367 * If generic_file_buffered_write() retuned a synchronous error
2368 * then we want to return the number of bytes which were
2369 * direct-written, or the error code if that was zero. Note
2370 * that this differs from normal direct-io semantics, which
2371 * will return -EFOO even if some bytes were written.
2373 if (written_buffered
< 0) {
2374 err
= written_buffered
;
2379 * We need to ensure that the page cache pages are written to
2380 * disk and invalidated to preserve the expected O_DIRECT
2383 endbyte
= pos
+ written_buffered
- written
- 1;
2384 err
= do_sync_mapping_range(file
->f_mapping
, pos
, endbyte
,
2385 SYNC_FILE_RANGE_WAIT_BEFORE
|
2386 SYNC_FILE_RANGE_WRITE
|
2387 SYNC_FILE_RANGE_WAIT_AFTER
);
2389 written
= written_buffered
;
2390 invalidate_mapping_pages(mapping
,
2391 pos
>> PAGE_CACHE_SHIFT
,
2392 endbyte
>> PAGE_CACHE_SHIFT
);
2395 * We don't know how much we wrote, so just return
2396 * the number of bytes which were direct-written
2400 written
= generic_file_buffered_write(iocb
, iov
, nr_segs
,
2401 pos
, ppos
, count
, written
);
2404 current
->backing_dev_info
= NULL
;
2405 return written
? written
: err
;
2407 EXPORT_SYMBOL(__generic_file_aio_write
);
2410 * generic_file_aio_write - write data to a file
2411 * @iocb: IO state structure
2412 * @iov: vector with data to write
2413 * @nr_segs: number of segments in the vector
2414 * @pos: position in file where to write
2416 * This is a wrapper around __generic_file_aio_write() to be used by most
2417 * filesystems. It takes care of syncing the file in case of O_SYNC file
2418 * and acquires i_mutex as needed.
2420 ssize_t
generic_file_aio_write(struct kiocb
*iocb
, const struct iovec
*iov
,
2421 unsigned long nr_segs
, loff_t pos
)
2423 struct file
*file
= iocb
->ki_filp
;
2424 struct inode
*inode
= file
->f_mapping
->host
;
2427 BUG_ON(iocb
->ki_pos
!= pos
);
2429 mutex_lock(&inode
->i_mutex
);
2430 ret
= __generic_file_aio_write(iocb
, iov
, nr_segs
, &iocb
->ki_pos
);
2431 mutex_unlock(&inode
->i_mutex
);
2433 if (ret
> 0 || ret
== -EIOCBQUEUED
) {
2436 err
= generic_write_sync(file
, pos
, ret
);
2437 if (err
< 0 && ret
> 0)
2442 EXPORT_SYMBOL(generic_file_aio_write
);
2445 * try_to_release_page() - release old fs-specific metadata on a page
2447 * @page: the page which the kernel is trying to free
2448 * @gfp_mask: memory allocation flags (and I/O mode)
2450 * The address_space is to try to release any data against the page
2451 * (presumably at page->private). If the release was successful, return `1'.
2452 * Otherwise return zero.
2454 * This may also be called if PG_fscache is set on a page, indicating that the
2455 * page is known to the local caching routines.
2457 * The @gfp_mask argument specifies whether I/O may be performed to release
2458 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
2461 int try_to_release_page(struct page
*page
, gfp_t gfp_mask
)
2463 struct address_space
* const mapping
= page
->mapping
;
2465 BUG_ON(!PageLocked(page
));
2466 if (PageWriteback(page
))
2469 if (mapping
&& mapping
->a_ops
->releasepage
)
2470 return mapping
->a_ops
->releasepage(page
, gfp_mask
);
2471 return try_to_free_buffers(page
);
2474 EXPORT_SYMBOL(try_to_release_page
);