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/backing-dev.h>
32 #include <linux/security.h>
33 #include <linux/syscalls.h>
34 #include <linux/cpuset.h>
35 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
39 * FIXME: remove all knowledge of the buffer layer from the core VM
41 #include <linux/buffer_head.h> /* for generic_osync_inode */
46 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
47 loff_t offset, unsigned long nr_segs);
50 * Shared mappings implemented 30.11.1994. It's not fully working yet,
53 * Shared mappings now work. 15.8.1995 Bruno.
55 * finished 'unifying' the page and buffer cache and SMP-threaded the
56 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
58 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
64 * ->i_mmap_lock (vmtruncate)
65 * ->private_lock (__free_pte->__set_page_dirty_buffers)
66 * ->swap_lock (exclusive_swap_page, others)
67 * ->mapping->tree_lock
71 * ->i_mmap_lock (truncate->unmap_mapping_range)
75 * ->page_table_lock or pte_lock (various, mainly in memory.c)
76 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
79 * ->lock_page (access_process_vm)
81 * ->i_mutex (generic_file_buffered_write)
82 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
85 * ->i_alloc_sem (various)
88 * ->sb_lock (fs/fs-writeback.c)
89 * ->mapping->tree_lock (__sync_single_inode)
92 * ->anon_vma.lock (vma_adjust)
95 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
97 * ->page_table_lock or pte_lock
98 * ->swap_lock (try_to_unmap_one)
99 * ->private_lock (try_to_unmap_one)
100 * ->tree_lock (try_to_unmap_one)
101 * ->zone.lru_lock (follow_page->mark_page_accessed)
102 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
103 * ->private_lock (page_remove_rmap->set_page_dirty)
104 * ->tree_lock (page_remove_rmap->set_page_dirty)
105 * ->inode_lock (page_remove_rmap->set_page_dirty)
106 * ->inode_lock (zap_pte_range->set_page_dirty)
107 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
110 * ->dcache_lock (proc_pid_lookup)
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 a write_lock on 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 BUG_ON(page_mapped(page));
129 void remove_from_page_cache(struct page *page)
131 struct address_space *mapping = page->mapping;
133 BUG_ON(!PageLocked(page));
135 write_lock_irq(&mapping->tree_lock);
136 __remove_from_page_cache(page);
137 write_unlock_irq(&mapping->tree_lock);
140 static int sync_page(void *word)
142 struct address_space *mapping;
145 page = container_of((unsigned long *)word, struct page, flags);
148 * page_mapping() is being called without PG_locked held.
149 * Some knowledge of the state and use of the page is used to
150 * reduce the requirements down to a memory barrier.
151 * The danger here is of a stale page_mapping() return value
152 * indicating a struct address_space different from the one it's
153 * associated with when it is associated with one.
154 * After smp_mb(), it's either the correct page_mapping() for
155 * the page, or an old page_mapping() and the page's own
156 * page_mapping() has gone NULL.
157 * The ->sync_page() address_space operation must tolerate
158 * page_mapping() going NULL. By an amazing coincidence,
159 * this comes about because none of the users of the page
160 * in the ->sync_page() methods make essential use of the
161 * page_mapping(), merely passing the page down to the backing
162 * device's unplug functions when it's non-NULL, which in turn
163 * ignore it for all cases but swap, where only page_private(page) is
164 * of interest. When page_mapping() does go NULL, the entire
165 * call stack gracefully ignores the page and returns.
169 mapping = page_mapping(page);
170 if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
171 mapping->a_ops->sync_page(page);
177 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
178 * @mapping: address space structure to write
179 * @start: offset in bytes where the range starts
180 * @end: offset in bytes where the range ends (inclusive)
181 * @sync_mode: enable synchronous operation
183 * Start writeback against all of a mapping's dirty pages that lie
184 * within the byte offsets <start, end> inclusive.
186 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
187 * opposed to a regular memory cleansing writeback. The difference between
188 * these two operations is that if a dirty page/buffer is encountered, it must
189 * be waited upon, and not just skipped over.
191 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
192 loff_t end, int sync_mode)
195 struct writeback_control wbc = {
196 .sync_mode = sync_mode,
197 .nr_to_write = mapping->nrpages * 2,
198 .range_start = start,
202 if (!mapping_cap_writeback_dirty(mapping))
205 ret = do_writepages(mapping, &wbc);
209 static inline int __filemap_fdatawrite(struct address_space *mapping,
212 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
215 int filemap_fdatawrite(struct address_space *mapping)
217 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
219 EXPORT_SYMBOL(filemap_fdatawrite);
221 static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
224 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
228 * filemap_flush - mostly a non-blocking flush
229 * @mapping: target address_space
231 * This is a mostly non-blocking flush. Not suitable for data-integrity
232 * purposes - I/O may not be started against all dirty pages.
234 int filemap_flush(struct address_space *mapping)
236 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
238 EXPORT_SYMBOL(filemap_flush);
241 * wait_on_page_writeback_range - wait for writeback to complete
242 * @mapping: target address_space
243 * @start: beginning page index
244 * @end: ending page index
246 * Wait for writeback to complete against pages indexed by start->end
249 int wait_on_page_writeback_range(struct address_space *mapping,
250 pgoff_t start, pgoff_t end)
260 pagevec_init(&pvec, 0);
262 while ((index <= end) &&
263 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
264 PAGECACHE_TAG_WRITEBACK,
265 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
268 for (i = 0; i < nr_pages; i++) {
269 struct page *page = pvec.pages[i];
271 /* until radix tree lookup accepts end_index */
272 if (page->index > end)
275 wait_on_page_writeback(page);
279 pagevec_release(&pvec);
283 /* Check for outstanding write errors */
284 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
286 if (test_and_clear_bit(AS_EIO, &mapping->flags))
293 * sync_page_range - write and wait on all pages in the passed range
294 * @inode: target inode
295 * @mapping: target address_space
296 * @pos: beginning offset in pages to write
297 * @count: number of bytes to write
299 * Write and wait upon all the pages in the passed range. This is a "data
300 * integrity" operation. It waits upon in-flight writeout before starting and
301 * waiting upon new writeout. If there was an IO error, return it.
303 * We need to re-take i_mutex during the generic_osync_inode list walk because
304 * it is otherwise livelockable.
306 int sync_page_range(struct inode *inode, struct address_space *mapping,
307 loff_t pos, loff_t count)
309 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
310 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
313 if (!mapping_cap_writeback_dirty(mapping) || !count)
315 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
317 mutex_lock(&inode->i_mutex);
318 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
319 mutex_unlock(&inode->i_mutex);
322 ret = wait_on_page_writeback_range(mapping, start, end);
325 EXPORT_SYMBOL(sync_page_range);
328 * sync_page_range_nolock
329 * @inode: target inode
330 * @mapping: target address_space
331 * @pos: beginning offset in pages to write
332 * @count: number of bytes to write
334 * Note: Holding i_mutex across sync_page_range_nolock() is not a good idea
335 * as it forces O_SYNC writers to different parts of the same file
336 * to be serialised right until io completion.
338 int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
339 loff_t pos, loff_t count)
341 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
342 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
345 if (!mapping_cap_writeback_dirty(mapping) || !count)
347 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
349 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
351 ret = wait_on_page_writeback_range(mapping, start, end);
354 EXPORT_SYMBOL(sync_page_range_nolock);
357 * filemap_fdatawait - wait for all under-writeback pages to complete
358 * @mapping: address space structure to wait for
360 * Walk the list of under-writeback pages of the given address space
361 * and wait for all of them.
363 int filemap_fdatawait(struct address_space *mapping)
365 loff_t i_size = i_size_read(mapping->host);
370 return wait_on_page_writeback_range(mapping, 0,
371 (i_size - 1) >> PAGE_CACHE_SHIFT);
373 EXPORT_SYMBOL(filemap_fdatawait);
375 int filemap_write_and_wait(struct address_space *mapping)
379 if (mapping->nrpages) {
380 err = filemap_fdatawrite(mapping);
382 * Even if the above returned error, the pages may be
383 * written partially (e.g. -ENOSPC), so we wait for it.
384 * But the -EIO is special case, it may indicate the worst
385 * thing (e.g. bug) happened, so we avoid waiting for it.
388 int err2 = filemap_fdatawait(mapping);
395 EXPORT_SYMBOL(filemap_write_and_wait);
398 * filemap_write_and_wait_range - write out & wait on a file range
399 * @mapping: the address_space for the pages
400 * @lstart: offset in bytes where the range starts
401 * @lend: offset in bytes where the range ends (inclusive)
403 * Write out and wait upon file offsets lstart->lend, inclusive.
405 * Note that `lend' is inclusive (describes the last byte to be written) so
406 * that this function can be used to write to the very end-of-file (end = -1).
408 int filemap_write_and_wait_range(struct address_space *mapping,
409 loff_t lstart, loff_t lend)
413 if (mapping->nrpages) {
414 err = __filemap_fdatawrite_range(mapping, lstart, lend,
416 /* See comment of filemap_write_and_wait() */
418 int err2 = wait_on_page_writeback_range(mapping,
419 lstart >> PAGE_CACHE_SHIFT,
420 lend >> PAGE_CACHE_SHIFT);
429 * add_to_page_cache - add newly allocated pagecache pages
431 * @mapping: the page's address_space
432 * @offset: page index
433 * @gfp_mask: page allocation mode
435 * This function is used to add newly allocated pagecache pages;
436 * the page is new, so we can just run SetPageLocked() against it.
437 * The other page state flags were set by rmqueue().
439 * This function does not add the page to the LRU. The caller must do that.
441 int add_to_page_cache(struct page *page, struct address_space *mapping,
442 pgoff_t offset, gfp_t gfp_mask)
444 int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
447 write_lock_irq(&mapping->tree_lock);
448 error = radix_tree_insert(&mapping->page_tree, offset, page);
450 page_cache_get(page);
452 page->mapping = mapping;
453 page->index = offset;
455 __inc_zone_page_state(page, NR_FILE_PAGES);
457 write_unlock_irq(&mapping->tree_lock);
458 radix_tree_preload_end();
462 EXPORT_SYMBOL(add_to_page_cache);
464 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
465 pgoff_t offset, gfp_t gfp_mask)
467 int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
474 struct page *__page_cache_alloc(gfp_t gfp)
476 if (cpuset_do_page_mem_spread()) {
477 int n = cpuset_mem_spread_node();
478 return alloc_pages_node(n, gfp, 0);
480 return alloc_pages(gfp, 0);
482 EXPORT_SYMBOL(__page_cache_alloc);
485 static int __sleep_on_page_lock(void *word)
492 * In order to wait for pages to become available there must be
493 * waitqueues associated with pages. By using a hash table of
494 * waitqueues where the bucket discipline is to maintain all
495 * waiters on the same queue and wake all when any of the pages
496 * become available, and for the woken contexts to check to be
497 * sure the appropriate page became available, this saves space
498 * at a cost of "thundering herd" phenomena during rare hash
501 static wait_queue_head_t *page_waitqueue(struct page *page)
503 const struct zone *zone = page_zone(page);
505 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
508 static inline void wake_up_page(struct page *page, int bit)
510 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
513 void fastcall wait_on_page_bit(struct page *page, int bit_nr)
515 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
517 if (test_bit(bit_nr, &page->flags))
518 __wait_on_bit(page_waitqueue(page), &wait, sync_page,
519 TASK_UNINTERRUPTIBLE);
521 EXPORT_SYMBOL(wait_on_page_bit);
524 * unlock_page - unlock a locked page
527 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
528 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
529 * mechananism between PageLocked pages and PageWriteback pages is shared.
530 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
532 * The first mb is necessary to safely close the critical section opened by the
533 * TestSetPageLocked(), the second mb is necessary to enforce ordering between
534 * the clear_bit and the read of the waitqueue (to avoid SMP races with a
535 * parallel wait_on_page_locked()).
537 void fastcall unlock_page(struct page *page)
539 smp_mb__before_clear_bit();
540 if (!TestClearPageLocked(page))
542 smp_mb__after_clear_bit();
543 wake_up_page(page, PG_locked);
545 EXPORT_SYMBOL(unlock_page);
548 * end_page_writeback - end writeback against a page
551 void end_page_writeback(struct page *page)
553 if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
554 if (!test_clear_page_writeback(page))
557 smp_mb__after_clear_bit();
558 wake_up_page(page, PG_writeback);
560 EXPORT_SYMBOL(end_page_writeback);
563 * __lock_page - get a lock on the page, assuming we need to sleep to get it
564 * @page: the page to lock
566 * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
567 * random driver's requestfn sets TASK_RUNNING, we could busywait. However
568 * chances are that on the second loop, the block layer's plug list is empty,
569 * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
571 void fastcall __lock_page(struct page *page)
573 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
575 __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
576 TASK_UNINTERRUPTIBLE);
578 EXPORT_SYMBOL(__lock_page);
581 * Variant of lock_page that does not require the caller to hold a reference
582 * on the page's mapping.
584 void fastcall __lock_page_nosync(struct page *page)
586 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
587 __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
588 TASK_UNINTERRUPTIBLE);
592 * find_get_page - find and get a page reference
593 * @mapping: the address_space to search
594 * @offset: the page index
596 * Is there a pagecache struct page at the given (mapping, offset) tuple?
597 * If yes, increment its refcount and return it; if no, return NULL.
599 struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
603 read_lock_irq(&mapping->tree_lock);
604 page = radix_tree_lookup(&mapping->page_tree, offset);
606 page_cache_get(page);
607 read_unlock_irq(&mapping->tree_lock);
610 EXPORT_SYMBOL(find_get_page);
613 * find_lock_page - locate, pin and lock a pagecache page
614 * @mapping: the address_space to search
615 * @offset: the page index
617 * Locates the desired pagecache page, locks it, increments its reference
618 * count and returns its address.
620 * Returns zero if the page was not present. find_lock_page() may sleep.
622 struct page *find_lock_page(struct address_space *mapping,
628 read_lock_irq(&mapping->tree_lock);
629 page = radix_tree_lookup(&mapping->page_tree, offset);
631 page_cache_get(page);
632 if (TestSetPageLocked(page)) {
633 read_unlock_irq(&mapping->tree_lock);
636 /* Has the page been truncated while we slept? */
637 if (unlikely(page->mapping != mapping)) {
639 page_cache_release(page);
642 VM_BUG_ON(page->index != offset);
646 read_unlock_irq(&mapping->tree_lock);
650 EXPORT_SYMBOL(find_lock_page);
653 * find_or_create_page - locate or add a pagecache page
654 * @mapping: the page's address_space
655 * @index: the page's index into the mapping
656 * @gfp_mask: page allocation mode
658 * Locates a page in the pagecache. If the page is not present, a new page
659 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
660 * LRU list. The returned page is locked and has its reference count
663 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
666 * find_or_create_page() returns the desired page's address, or zero on
669 struct page *find_or_create_page(struct address_space *mapping,
670 pgoff_t index, gfp_t gfp_mask)
675 page = find_lock_page(mapping, index);
677 page = __page_cache_alloc(gfp_mask);
680 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
682 page_cache_release(page);
690 EXPORT_SYMBOL(find_or_create_page);
693 * find_get_pages - gang pagecache lookup
694 * @mapping: The address_space to search
695 * @start: The starting page index
696 * @nr_pages: The maximum number of pages
697 * @pages: Where the resulting pages are placed
699 * find_get_pages() will search for and return a group of up to
700 * @nr_pages pages in the mapping. The pages are placed at @pages.
701 * find_get_pages() takes a reference against the returned pages.
703 * The search returns a group of mapping-contiguous pages with ascending
704 * indexes. There may be holes in the indices due to not-present pages.
706 * find_get_pages() returns the number of pages which were found.
708 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
709 unsigned int nr_pages, struct page **pages)
714 read_lock_irq(&mapping->tree_lock);
715 ret = radix_tree_gang_lookup(&mapping->page_tree,
716 (void **)pages, start, nr_pages);
717 for (i = 0; i < ret; i++)
718 page_cache_get(pages[i]);
719 read_unlock_irq(&mapping->tree_lock);
724 * find_get_pages_contig - gang contiguous pagecache lookup
725 * @mapping: The address_space to search
726 * @index: The starting page index
727 * @nr_pages: The maximum number of pages
728 * @pages: Where the resulting pages are placed
730 * find_get_pages_contig() works exactly like find_get_pages(), except
731 * that the returned number of pages are guaranteed to be contiguous.
733 * find_get_pages_contig() returns the number of pages which were found.
735 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
736 unsigned int nr_pages, struct page **pages)
741 read_lock_irq(&mapping->tree_lock);
742 ret = radix_tree_gang_lookup(&mapping->page_tree,
743 (void **)pages, index, nr_pages);
744 for (i = 0; i < ret; i++) {
745 if (pages[i]->mapping == NULL || pages[i]->index != index)
748 page_cache_get(pages[i]);
751 read_unlock_irq(&mapping->tree_lock);
754 EXPORT_SYMBOL(find_get_pages_contig);
757 * find_get_pages_tag - find and return pages that match @tag
758 * @mapping: the address_space to search
759 * @index: the starting page index
760 * @tag: the tag index
761 * @nr_pages: the maximum number of pages
762 * @pages: where the resulting pages are placed
764 * Like find_get_pages, except we only return pages which are tagged with
765 * @tag. We update @index to index the next page for the traversal.
767 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
768 int tag, unsigned int nr_pages, struct page **pages)
773 read_lock_irq(&mapping->tree_lock);
774 ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
775 (void **)pages, *index, nr_pages, tag);
776 for (i = 0; i < ret; i++)
777 page_cache_get(pages[i]);
779 *index = pages[ret - 1]->index + 1;
780 read_unlock_irq(&mapping->tree_lock);
783 EXPORT_SYMBOL(find_get_pages_tag);
786 * grab_cache_page_nowait - returns locked page at given index in given cache
787 * @mapping: target address_space
788 * @index: the page index
790 * Same as grab_cache_page(), but do not wait if the page is unavailable.
791 * This is intended for speculative data generators, where the data can
792 * be regenerated if the page couldn't be grabbed. This routine should
793 * be safe to call while holding the lock for another page.
795 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
796 * and deadlock against the caller's locked page.
799 grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
801 struct page *page = find_get_page(mapping, index);
804 if (!TestSetPageLocked(page))
806 page_cache_release(page);
809 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
810 if (page && add_to_page_cache_lru(page, mapping, index, GFP_KERNEL)) {
811 page_cache_release(page);
816 EXPORT_SYMBOL(grab_cache_page_nowait);
819 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
820 * a _large_ part of the i/o request. Imagine the worst scenario:
822 * ---R__________________________________________B__________
823 * ^ reading here ^ bad block(assume 4k)
825 * read(R) => miss => readahead(R...B) => media error => frustrating retries
826 * => failing the whole request => read(R) => read(R+1) =>
827 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
828 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
829 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
831 * It is going insane. Fix it by quickly scaling down the readahead size.
833 static void shrink_readahead_size_eio(struct file *filp,
834 struct file_ra_state *ra)
843 * do_generic_mapping_read - generic file read routine
844 * @mapping: address_space to be read
845 * @ra: file's readahead state
846 * @filp: the file to read
847 * @ppos: current file position
848 * @desc: read_descriptor
849 * @actor: read method
851 * This is a generic file read routine, and uses the
852 * mapping->a_ops->readpage() function for the actual low-level stuff.
854 * This is really ugly. But the goto's actually try to clarify some
855 * of the logic when it comes to error handling etc.
857 * Note the struct file* is only passed for the use of readpage.
860 void do_generic_mapping_read(struct address_space *mapping,
861 struct file_ra_state *ra,
864 read_descriptor_t *desc,
867 struct inode *inode = mapping->host;
871 unsigned long offset; /* offset into pagecache page */
872 unsigned int prev_offset;
875 index = *ppos >> PAGE_CACHE_SHIFT;
876 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
877 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
878 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
879 offset = *ppos & ~PAGE_CACHE_MASK;
885 unsigned long nr, ret;
889 page = find_get_page(mapping, index);
891 page_cache_sync_readahead(mapping,
893 index, last_index - index);
894 page = find_get_page(mapping, index);
895 if (unlikely(page == NULL))
898 if (PageReadahead(page)) {
899 page_cache_async_readahead(mapping,
901 index, last_index - index);
903 if (!PageUptodate(page))
904 goto page_not_up_to_date;
907 * i_size must be checked after we know the page is Uptodate.
909 * Checking i_size after the check allows us to calculate
910 * the correct value for "nr", which means the zero-filled
911 * part of the page is not copied back to userspace (unless
912 * another truncate extends the file - this is desired though).
915 isize = i_size_read(inode);
916 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
917 if (unlikely(!isize || index > end_index)) {
918 page_cache_release(page);
922 /* nr is the maximum number of bytes to copy from this page */
923 nr = PAGE_CACHE_SIZE;
924 if (index == end_index) {
925 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
927 page_cache_release(page);
933 /* If users can be writing to this page using arbitrary
934 * virtual addresses, take care about potential aliasing
935 * before reading the page on the kernel side.
937 if (mapping_writably_mapped(mapping))
938 flush_dcache_page(page);
941 * When a sequential read accesses a page several times,
942 * only mark it as accessed the first time.
944 if (prev_index != index || offset != prev_offset)
945 mark_page_accessed(page);
949 * Ok, we have the page, and it's up-to-date, so
950 * now we can copy it to user space...
952 * The actor routine returns how many bytes were actually used..
953 * NOTE! This may not be the same as how much of a user buffer
954 * we filled up (we may be padding etc), so we can only update
955 * "pos" here (the actor routine has to update the user buffer
956 * pointers and the remaining count).
958 ret = actor(desc, page, offset, nr);
960 index += offset >> PAGE_CACHE_SHIFT;
961 offset &= ~PAGE_CACHE_MASK;
962 prev_offset = offset;
964 page_cache_release(page);
965 if (ret == nr && desc->count)
970 /* Get exclusive access to the page ... */
973 /* Did it get truncated before we got the lock? */
974 if (!page->mapping) {
976 page_cache_release(page);
980 /* Did somebody else fill it already? */
981 if (PageUptodate(page)) {
987 /* Start the actual read. The read will unlock the page. */
988 error = mapping->a_ops->readpage(filp, page);
990 if (unlikely(error)) {
991 if (error == AOP_TRUNCATED_PAGE) {
992 page_cache_release(page);
998 if (!PageUptodate(page)) {
1000 if (!PageUptodate(page)) {
1001 if (page->mapping == NULL) {
1003 * invalidate_inode_pages got it
1006 page_cache_release(page);
1011 shrink_readahead_size_eio(filp, ra);
1012 goto readpage_error;
1020 /* UHHUH! A synchronous read error occurred. Report it */
1021 desc->error = error;
1022 page_cache_release(page);
1027 * Ok, it wasn't cached, so we need to create a new
1030 page = page_cache_alloc_cold(mapping);
1032 desc->error = -ENOMEM;
1035 error = add_to_page_cache_lru(page, mapping,
1038 page_cache_release(page);
1039 if (error == -EEXIST)
1041 desc->error = error;
1048 ra->prev_pos = prev_index;
1049 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1050 ra->prev_pos |= prev_offset;
1052 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1054 file_accessed(filp);
1056 EXPORT_SYMBOL(do_generic_mapping_read);
1058 int file_read_actor(read_descriptor_t *desc, struct page *page,
1059 unsigned long offset, unsigned long size)
1062 unsigned long left, count = desc->count;
1068 * Faults on the destination of a read are common, so do it before
1071 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1072 kaddr = kmap_atomic(page, KM_USER0);
1073 left = __copy_to_user_inatomic(desc->arg.buf,
1074 kaddr + offset, size);
1075 kunmap_atomic(kaddr, KM_USER0);
1080 /* Do it the slow way */
1082 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1087 desc->error = -EFAULT;
1090 desc->count = count - size;
1091 desc->written += size;
1092 desc->arg.buf += size;
1097 * Performs necessary checks before doing a write
1098 * @iov: io vector request
1099 * @nr_segs: number of segments in the iovec
1100 * @count: number of bytes to write
1101 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1103 * Adjust number of segments and amount of bytes to write (nr_segs should be
1104 * properly initialized first). Returns appropriate error code that caller
1105 * should return or zero in case that write should be allowed.
1107 int generic_segment_checks(const struct iovec *iov,
1108 unsigned long *nr_segs, size_t *count, int access_flags)
1112 for (seg = 0; seg < *nr_segs; seg++) {
1113 const struct iovec *iv = &iov[seg];
1116 * If any segment has a negative length, or the cumulative
1117 * length ever wraps negative then return -EINVAL.
1120 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1122 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1127 cnt -= iv->iov_len; /* This segment is no good */
1133 EXPORT_SYMBOL(generic_segment_checks);
1136 * generic_file_aio_read - generic filesystem read routine
1137 * @iocb: kernel I/O control block
1138 * @iov: io vector request
1139 * @nr_segs: number of segments in the iovec
1140 * @pos: current file position
1142 * This is the "read()" routine for all filesystems
1143 * that can use the page cache directly.
1146 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1147 unsigned long nr_segs, loff_t pos)
1149 struct file *filp = iocb->ki_filp;
1153 loff_t *ppos = &iocb->ki_pos;
1156 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1160 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1161 if (filp->f_flags & O_DIRECT) {
1163 struct address_space *mapping;
1164 struct inode *inode;
1166 mapping = filp->f_mapping;
1167 inode = mapping->host;
1170 goto out; /* skip atime */
1171 size = i_size_read(inode);
1173 retval = generic_file_direct_IO(READ, iocb,
1176 *ppos = pos + retval;
1178 if (likely(retval != 0)) {
1179 file_accessed(filp);
1186 for (seg = 0; seg < nr_segs; seg++) {
1187 read_descriptor_t desc;
1190 desc.arg.buf = iov[seg].iov_base;
1191 desc.count = iov[seg].iov_len;
1192 if (desc.count == 0)
1195 do_generic_file_read(filp,ppos,&desc,file_read_actor);
1196 retval += desc.written;
1198 retval = retval ?: desc.error;
1208 EXPORT_SYMBOL(generic_file_aio_read);
1211 do_readahead(struct address_space *mapping, struct file *filp,
1212 pgoff_t index, unsigned long nr)
1214 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1217 force_page_cache_readahead(mapping, filp, index,
1218 max_sane_readahead(nr));
1222 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1230 if (file->f_mode & FMODE_READ) {
1231 struct address_space *mapping = file->f_mapping;
1232 pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1233 pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1234 unsigned long len = end - start + 1;
1235 ret = do_readahead(mapping, file, start, len);
1244 * page_cache_read - adds requested page to the page cache if not already there
1245 * @file: file to read
1246 * @offset: page index
1248 * This adds the requested page to the page cache if it isn't already there,
1249 * and schedules an I/O to read in its contents from disk.
1251 static int fastcall page_cache_read(struct file * file, pgoff_t offset)
1253 struct address_space *mapping = file->f_mapping;
1258 page = page_cache_alloc_cold(mapping);
1262 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1264 ret = mapping->a_ops->readpage(file, page);
1265 else if (ret == -EEXIST)
1266 ret = 0; /* losing race to add is OK */
1268 page_cache_release(page);
1270 } while (ret == AOP_TRUNCATED_PAGE);
1275 #define MMAP_LOTSAMISS (100)
1278 * filemap_fault - read in file data for page fault handling
1279 * @vma: vma in which the fault was taken
1280 * @vmf: struct vm_fault containing details of the fault
1282 * filemap_fault() is invoked via the vma operations vector for a
1283 * mapped memory region to read in file data during a page fault.
1285 * The goto's are kind of ugly, but this streamlines the normal case of having
1286 * it in the page cache, and handles the special cases reasonably without
1287 * having a lot of duplicated code.
1289 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1292 struct file *file = vma->vm_file;
1293 struct address_space *mapping = file->f_mapping;
1294 struct file_ra_state *ra = &file->f_ra;
1295 struct inode *inode = mapping->host;
1298 int did_readaround = 0;
1301 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1302 if (vmf->pgoff >= size)
1303 goto outside_data_content;
1305 /* If we don't want any read-ahead, don't bother */
1306 if (VM_RandomReadHint(vma))
1307 goto no_cached_page;
1310 * Do we have something in the page cache already?
1313 page = find_lock_page(mapping, vmf->pgoff);
1315 * For sequential accesses, we use the generic readahead logic.
1317 if (VM_SequentialReadHint(vma)) {
1319 page_cache_sync_readahead(mapping, ra, file,
1321 page = find_lock_page(mapping, vmf->pgoff);
1323 goto no_cached_page;
1325 if (PageReadahead(page)) {
1326 page_cache_async_readahead(mapping, ra, file, page,
1332 unsigned long ra_pages;
1337 * Do we miss much more than hit in this file? If so,
1338 * stop bothering with read-ahead. It will only hurt.
1340 if (ra->mmap_miss > MMAP_LOTSAMISS)
1341 goto no_cached_page;
1344 * To keep the pgmajfault counter straight, we need to
1345 * check did_readaround, as this is an inner loop.
1347 if (!did_readaround) {
1348 ret = VM_FAULT_MAJOR;
1349 count_vm_event(PGMAJFAULT);
1352 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1356 if (vmf->pgoff > ra_pages / 2)
1357 start = vmf->pgoff - ra_pages / 2;
1358 do_page_cache_readahead(mapping, file, start, ra_pages);
1360 page = find_lock_page(mapping, vmf->pgoff);
1362 goto no_cached_page;
1365 if (!did_readaround)
1369 * We have a locked page in the page cache, now we need to check
1370 * that it's up-to-date. If not, it is going to be due to an error.
1372 if (unlikely(!PageUptodate(page)))
1373 goto page_not_uptodate;
1375 /* Must recheck i_size under page lock */
1376 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1377 if (unlikely(vmf->pgoff >= size)) {
1379 page_cache_release(page);
1380 goto outside_data_content;
1384 * Found the page and have a reference on it.
1386 mark_page_accessed(page);
1387 ra->prev_pos = (loff_t)page->index << PAGE_CACHE_SHIFT;
1389 return ret | VM_FAULT_LOCKED;
1391 outside_data_content:
1393 * An external ptracer can access pages that normally aren't
1396 if (vma->vm_mm == current->mm)
1397 return VM_FAULT_SIGBUS;
1399 /* Fall through to the non-read-ahead case */
1402 * We're only likely to ever get here if MADV_RANDOM is in
1405 error = page_cache_read(file, vmf->pgoff);
1408 * The page we want has now been added to the page cache.
1409 * In the unlikely event that someone removed it in the
1410 * meantime, we'll just come back here and read it again.
1416 * An error return from page_cache_read can result if the
1417 * system is low on memory, or a problem occurs while trying
1420 if (error == -ENOMEM)
1421 return VM_FAULT_OOM;
1422 return VM_FAULT_SIGBUS;
1426 if (!did_readaround) {
1427 ret = VM_FAULT_MAJOR;
1428 count_vm_event(PGMAJFAULT);
1432 * Umm, take care of errors if the page isn't up-to-date.
1433 * Try to re-read it _once_. We do this synchronously,
1434 * because there really aren't any performance issues here
1435 * and we need to check for errors.
1437 ClearPageError(page);
1438 error = mapping->a_ops->readpage(file, page);
1439 page_cache_release(page);
1441 if (!error || error == AOP_TRUNCATED_PAGE)
1444 /* Things didn't work out. Return zero to tell the mm layer so. */
1445 shrink_readahead_size_eio(file, ra);
1446 return VM_FAULT_SIGBUS;
1448 EXPORT_SYMBOL(filemap_fault);
1450 struct vm_operations_struct generic_file_vm_ops = {
1451 .fault = filemap_fault,
1454 /* This is used for a general mmap of a disk file */
1456 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1458 struct address_space *mapping = file->f_mapping;
1460 if (!mapping->a_ops->readpage)
1462 file_accessed(file);
1463 vma->vm_ops = &generic_file_vm_ops;
1464 vma->vm_flags |= VM_CAN_NONLINEAR;
1469 * This is for filesystems which do not implement ->writepage.
1471 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1473 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1475 return generic_file_mmap(file, vma);
1478 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1482 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1486 #endif /* CONFIG_MMU */
1488 EXPORT_SYMBOL(generic_file_mmap);
1489 EXPORT_SYMBOL(generic_file_readonly_mmap);
1491 static struct page *__read_cache_page(struct address_space *mapping,
1493 int (*filler)(void *,struct page*),
1499 page = find_get_page(mapping, index);
1501 page = page_cache_alloc_cold(mapping);
1503 return ERR_PTR(-ENOMEM);
1504 err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
1505 if (unlikely(err)) {
1506 page_cache_release(page);
1509 /* Presumably ENOMEM for radix tree node */
1510 return ERR_PTR(err);
1512 err = filler(data, page);
1514 page_cache_release(page);
1515 page = ERR_PTR(err);
1522 * Same as read_cache_page, but don't wait for page to become unlocked
1523 * after submitting it to the filler.
1525 struct page *read_cache_page_async(struct address_space *mapping,
1527 int (*filler)(void *,struct page*),
1534 page = __read_cache_page(mapping, index, filler, data);
1537 if (PageUptodate(page))
1541 if (!page->mapping) {
1543 page_cache_release(page);
1546 if (PageUptodate(page)) {
1550 err = filler(data, page);
1552 page_cache_release(page);
1553 return ERR_PTR(err);
1556 mark_page_accessed(page);
1559 EXPORT_SYMBOL(read_cache_page_async);
1562 * read_cache_page - read into page cache, fill it if needed
1563 * @mapping: the page's address_space
1564 * @index: the page index
1565 * @filler: function to perform the read
1566 * @data: destination for read data
1568 * Read into the page cache. If a page already exists, and PageUptodate() is
1569 * not set, try to fill the page then wait for it to become unlocked.
1571 * If the page does not get brought uptodate, return -EIO.
1573 struct page *read_cache_page(struct address_space *mapping,
1575 int (*filler)(void *,struct page*),
1580 page = read_cache_page_async(mapping, index, filler, data);
1583 wait_on_page_locked(page);
1584 if (!PageUptodate(page)) {
1585 page_cache_release(page);
1586 page = ERR_PTR(-EIO);
1591 EXPORT_SYMBOL(read_cache_page);
1594 * The logic we want is
1596 * if suid or (sgid and xgrp)
1599 int should_remove_suid(struct dentry *dentry)
1601 mode_t mode = dentry->d_inode->i_mode;
1604 /* suid always must be killed */
1605 if (unlikely(mode & S_ISUID))
1606 kill = ATTR_KILL_SUID;
1609 * sgid without any exec bits is just a mandatory locking mark; leave
1610 * it alone. If some exec bits are set, it's a real sgid; kill it.
1612 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1613 kill |= ATTR_KILL_SGID;
1615 if (unlikely(kill && !capable(CAP_FSETID)))
1620 EXPORT_SYMBOL(should_remove_suid);
1622 int __remove_suid(struct dentry *dentry, int kill)
1624 struct iattr newattrs;
1626 newattrs.ia_valid = ATTR_FORCE | kill;
1627 return notify_change(dentry, &newattrs);
1630 int remove_suid(struct dentry *dentry)
1632 int killsuid = should_remove_suid(dentry);
1633 int killpriv = security_inode_need_killpriv(dentry);
1639 error = security_inode_killpriv(dentry);
1640 if (!error && killsuid)
1641 error = __remove_suid(dentry, killsuid);
1645 EXPORT_SYMBOL(remove_suid);
1647 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
1648 const struct iovec *iov, size_t base, size_t bytes)
1650 size_t copied = 0, left = 0;
1653 char __user *buf = iov->iov_base + base;
1654 int copy = min(bytes, iov->iov_len - base);
1657 left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
1666 return copied - left;
1670 * Copy as much as we can into the page and return the number of bytes which
1671 * were sucessfully copied. If a fault is encountered then return the number of
1672 * bytes which were copied.
1674 size_t iov_iter_copy_from_user_atomic(struct page *page,
1675 struct iov_iter *i, unsigned long offset, size_t bytes)
1680 BUG_ON(!in_atomic());
1681 kaddr = kmap_atomic(page, KM_USER0);
1682 if (likely(i->nr_segs == 1)) {
1684 char __user *buf = i->iov->iov_base + i->iov_offset;
1685 left = __copy_from_user_inatomic_nocache(kaddr + offset,
1687 copied = bytes - left;
1689 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1690 i->iov, i->iov_offset, bytes);
1692 kunmap_atomic(kaddr, KM_USER0);
1696 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
1699 * This has the same sideeffects and return value as
1700 * iov_iter_copy_from_user_atomic().
1701 * The difference is that it attempts to resolve faults.
1702 * Page must not be locked.
1704 size_t iov_iter_copy_from_user(struct page *page,
1705 struct iov_iter *i, unsigned long offset, size_t bytes)
1711 if (likely(i->nr_segs == 1)) {
1713 char __user *buf = i->iov->iov_base + i->iov_offset;
1714 left = __copy_from_user_nocache(kaddr + offset, buf, bytes);
1715 copied = bytes - left;
1717 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1718 i->iov, i->iov_offset, bytes);
1723 EXPORT_SYMBOL(iov_iter_copy_from_user);
1725 static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
1727 if (likely(i->nr_segs == 1)) {
1728 i->iov_offset += bytes;
1730 const struct iovec *iov = i->iov;
1731 size_t base = i->iov_offset;
1734 int copy = min(bytes, iov->iov_len - base);
1738 if (iov->iov_len == base) {
1744 i->iov_offset = base;
1748 void iov_iter_advance(struct iov_iter *i, size_t bytes)
1750 BUG_ON(i->count < bytes);
1752 __iov_iter_advance_iov(i, bytes);
1755 EXPORT_SYMBOL(iov_iter_advance);
1758 * Fault in the first iovec of the given iov_iter, to a maximum length
1759 * of bytes. Returns 0 on success, or non-zero if the memory could not be
1760 * accessed (ie. because it is an invalid address).
1762 * writev-intensive code may want this to prefault several iovecs -- that
1763 * would be possible (callers must not rely on the fact that _only_ the
1764 * first iovec will be faulted with the current implementation).
1766 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
1768 char __user *buf = i->iov->iov_base + i->iov_offset;
1769 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
1770 return fault_in_pages_readable(buf, bytes);
1772 EXPORT_SYMBOL(iov_iter_fault_in_readable);
1775 * Return the count of just the current iov_iter segment.
1777 size_t iov_iter_single_seg_count(struct iov_iter *i)
1779 const struct iovec *iov = i->iov;
1780 if (i->nr_segs == 1)
1783 return min(i->count, iov->iov_len - i->iov_offset);
1785 EXPORT_SYMBOL(iov_iter_single_seg_count);
1788 * Performs necessary checks before doing a write
1790 * Can adjust writing position or amount of bytes to write.
1791 * Returns appropriate error code that caller should return or
1792 * zero in case that write should be allowed.
1794 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1796 struct inode *inode = file->f_mapping->host;
1797 unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
1799 if (unlikely(*pos < 0))
1803 /* FIXME: this is for backwards compatibility with 2.4 */
1804 if (file->f_flags & O_APPEND)
1805 *pos = i_size_read(inode);
1807 if (limit != RLIM_INFINITY) {
1808 if (*pos >= limit) {
1809 send_sig(SIGXFSZ, current, 0);
1812 if (*count > limit - (typeof(limit))*pos) {
1813 *count = limit - (typeof(limit))*pos;
1821 if (unlikely(*pos + *count > MAX_NON_LFS &&
1822 !(file->f_flags & O_LARGEFILE))) {
1823 if (*pos >= MAX_NON_LFS) {
1826 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1827 *count = MAX_NON_LFS - (unsigned long)*pos;
1832 * Are we about to exceed the fs block limit ?
1834 * If we have written data it becomes a short write. If we have
1835 * exceeded without writing data we send a signal and return EFBIG.
1836 * Linus frestrict idea will clean these up nicely..
1838 if (likely(!isblk)) {
1839 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1840 if (*count || *pos > inode->i_sb->s_maxbytes) {
1843 /* zero-length writes at ->s_maxbytes are OK */
1846 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1847 *count = inode->i_sb->s_maxbytes - *pos;
1851 if (bdev_read_only(I_BDEV(inode)))
1853 isize = i_size_read(inode);
1854 if (*pos >= isize) {
1855 if (*count || *pos > isize)
1859 if (*pos + *count > isize)
1860 *count = isize - *pos;
1867 EXPORT_SYMBOL(generic_write_checks);
1869 int pagecache_write_begin(struct file *file, struct address_space *mapping,
1870 loff_t pos, unsigned len, unsigned flags,
1871 struct page **pagep, void **fsdata)
1873 const struct address_space_operations *aops = mapping->a_ops;
1875 if (aops->write_begin) {
1876 return aops->write_begin(file, mapping, pos, len, flags,
1880 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1881 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1882 struct inode *inode = mapping->host;
1885 page = __grab_cache_page(mapping, index);
1890 if (flags & AOP_FLAG_UNINTERRUPTIBLE && !PageUptodate(page)) {
1892 * There is no way to resolve a short write situation
1893 * for a !Uptodate page (except by double copying in
1894 * the caller done by generic_perform_write_2copy).
1896 * Instead, we have to bring it uptodate here.
1898 ret = aops->readpage(file, page);
1899 page_cache_release(page);
1901 if (ret == AOP_TRUNCATED_PAGE)
1908 ret = aops->prepare_write(file, page, offset, offset+len);
1911 page_cache_release(page);
1912 if (pos + len > inode->i_size)
1913 vmtruncate(inode, inode->i_size);
1918 EXPORT_SYMBOL(pagecache_write_begin);
1920 int pagecache_write_end(struct file *file, struct address_space *mapping,
1921 loff_t pos, unsigned len, unsigned copied,
1922 struct page *page, void *fsdata)
1924 const struct address_space_operations *aops = mapping->a_ops;
1927 if (aops->write_end) {
1928 mark_page_accessed(page);
1929 ret = aops->write_end(file, mapping, pos, len, copied,
1932 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1933 struct inode *inode = mapping->host;
1935 flush_dcache_page(page);
1936 ret = aops->commit_write(file, page, offset, offset+len);
1938 mark_page_accessed(page);
1939 page_cache_release(page);
1942 if (pos + len > inode->i_size)
1943 vmtruncate(inode, inode->i_size);
1945 ret = min_t(size_t, copied, ret);
1952 EXPORT_SYMBOL(pagecache_write_end);
1955 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
1956 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
1957 size_t count, size_t ocount)
1959 struct file *file = iocb->ki_filp;
1960 struct address_space *mapping = file->f_mapping;
1961 struct inode *inode = mapping->host;
1964 if (count != ocount)
1965 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
1967 written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
1969 loff_t end = pos + written;
1970 if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
1971 i_size_write(inode, end);
1972 mark_inode_dirty(inode);
1978 * Sync the fs metadata but not the minor inode changes and
1979 * of course not the data as we did direct DMA for the IO.
1980 * i_mutex is held, which protects generic_osync_inode() from
1981 * livelocking. AIO O_DIRECT ops attempt to sync metadata here.
1983 if ((written >= 0 || written == -EIOCBQUEUED) &&
1984 ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
1985 int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1991 EXPORT_SYMBOL(generic_file_direct_write);
1994 * Find or create a page at the given pagecache position. Return the locked
1995 * page. This function is specifically for buffered writes.
1997 struct page *__grab_cache_page(struct address_space *mapping, pgoff_t index)
2002 page = find_lock_page(mapping, index);
2006 page = page_cache_alloc(mapping);
2009 status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
2010 if (unlikely(status)) {
2011 page_cache_release(page);
2012 if (status == -EEXIST)
2018 EXPORT_SYMBOL(__grab_cache_page);
2020 static ssize_t generic_perform_write_2copy(struct file *file,
2021 struct iov_iter *i, loff_t pos)
2023 struct address_space *mapping = file->f_mapping;
2024 const struct address_space_operations *a_ops = mapping->a_ops;
2025 struct inode *inode = mapping->host;
2027 ssize_t written = 0;
2030 struct page *src_page;
2032 pgoff_t index; /* Pagecache index for current page */
2033 unsigned long offset; /* Offset into pagecache page */
2034 unsigned long bytes; /* Bytes to write to page */
2035 size_t copied; /* Bytes copied from user */
2037 offset = (pos & (PAGE_CACHE_SIZE - 1));
2038 index = pos >> PAGE_CACHE_SHIFT;
2039 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2043 * a non-NULL src_page indicates that we're doing the
2044 * copy via get_user_pages and kmap.
2049 * Bring in the user page that we will copy from _first_.
2050 * Otherwise there's a nasty deadlock on copying from the
2051 * same page as we're writing to, without it being marked
2054 * Not only is this an optimisation, but it is also required
2055 * to check that the address is actually valid, when atomic
2056 * usercopies are used, below.
2058 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2063 page = __grab_cache_page(mapping, index);
2070 * non-uptodate pages cannot cope with short copies, and we
2071 * cannot take a pagefault with the destination page locked.
2072 * So pin the source page to copy it.
2074 if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) {
2077 src_page = alloc_page(GFP_KERNEL);
2079 page_cache_release(page);
2085 * Cannot get_user_pages with a page locked for the
2086 * same reason as we can't take a page fault with a
2087 * page locked (as explained below).
2089 copied = iov_iter_copy_from_user(src_page, i,
2091 if (unlikely(copied == 0)) {
2093 page_cache_release(page);
2094 page_cache_release(src_page);
2101 * Can't handle the page going uptodate here, because
2102 * that means we would use non-atomic usercopies, which
2103 * zero out the tail of the page, which can cause
2104 * zeroes to become transiently visible. We could just
2105 * use a non-zeroing copy, but the APIs aren't too
2108 if (unlikely(!page->mapping || PageUptodate(page))) {
2110 page_cache_release(page);
2111 page_cache_release(src_page);
2116 status = a_ops->prepare_write(file, page, offset, offset+bytes);
2117 if (unlikely(status))
2118 goto fs_write_aop_error;
2122 * Must not enter the pagefault handler here, because
2123 * we hold the page lock, so we might recursively
2124 * deadlock on the same lock, or get an ABBA deadlock
2125 * against a different lock, or against the mmap_sem
2126 * (which nests outside the page lock). So increment
2127 * preempt count, and use _atomic usercopies.
2129 * The page is uptodate so we are OK to encounter a
2130 * short copy: if unmodified parts of the page are
2131 * marked dirty and written out to disk, it doesn't
2134 pagefault_disable();
2135 copied = iov_iter_copy_from_user_atomic(page, i,
2140 src = kmap_atomic(src_page, KM_USER0);
2141 dst = kmap_atomic(page, KM_USER1);
2142 memcpy(dst + offset, src + offset, bytes);
2143 kunmap_atomic(dst, KM_USER1);
2144 kunmap_atomic(src, KM_USER0);
2147 flush_dcache_page(page);
2149 status = a_ops->commit_write(file, page, offset, offset+bytes);
2150 if (unlikely(status < 0))
2151 goto fs_write_aop_error;
2152 if (unlikely(status > 0)) /* filesystem did partial write */
2153 copied = min_t(size_t, copied, status);
2156 mark_page_accessed(page);
2157 page_cache_release(page);
2159 page_cache_release(src_page);
2161 iov_iter_advance(i, copied);
2165 balance_dirty_pages_ratelimited(mapping);
2171 page_cache_release(page);
2173 page_cache_release(src_page);
2176 * prepare_write() may have instantiated a few blocks
2177 * outside i_size. Trim these off again. Don't need
2178 * i_size_read because we hold i_mutex.
2180 if (pos + bytes > inode->i_size)
2181 vmtruncate(inode, inode->i_size);
2183 } while (iov_iter_count(i));
2185 return written ? written : status;
2188 static ssize_t generic_perform_write(struct file *file,
2189 struct iov_iter *i, loff_t pos)
2191 struct address_space *mapping = file->f_mapping;
2192 const struct address_space_operations *a_ops = mapping->a_ops;
2194 ssize_t written = 0;
2195 unsigned int flags = 0;
2198 * Copies from kernel address space cannot fail (NFSD is a big user).
2200 if (segment_eq(get_fs(), KERNEL_DS))
2201 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2205 pgoff_t index; /* Pagecache index for current page */
2206 unsigned long offset; /* Offset into pagecache page */
2207 unsigned long bytes; /* Bytes to write to page */
2208 size_t copied; /* Bytes copied from user */
2211 offset = (pos & (PAGE_CACHE_SIZE - 1));
2212 index = pos >> PAGE_CACHE_SHIFT;
2213 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2219 * Bring in the user page that we will copy from _first_.
2220 * Otherwise there's a nasty deadlock on copying from the
2221 * same page as we're writing to, without it being marked
2224 * Not only is this an optimisation, but it is also required
2225 * to check that the address is actually valid, when atomic
2226 * usercopies are used, below.
2228 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2233 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2235 if (unlikely(status))
2238 pagefault_disable();
2239 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2241 flush_dcache_page(page);
2243 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2245 if (unlikely(status < 0))
2251 if (unlikely(copied == 0)) {
2253 * If we were unable to copy any data at all, we must
2254 * fall back to a single segment length write.
2256 * If we didn't fallback here, we could livelock
2257 * because not all segments in the iov can be copied at
2258 * once without a pagefault.
2260 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2261 iov_iter_single_seg_count(i));
2264 iov_iter_advance(i, copied);
2268 balance_dirty_pages_ratelimited(mapping);
2270 } while (iov_iter_count(i));
2272 return written ? written : status;
2276 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2277 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2278 size_t count, ssize_t written)
2280 struct file *file = iocb->ki_filp;
2281 struct address_space *mapping = file->f_mapping;
2282 const struct address_space_operations *a_ops = mapping->a_ops;
2283 struct inode *inode = mapping->host;
2287 iov_iter_init(&i, iov, nr_segs, count, written);
2288 if (a_ops->write_begin)
2289 status = generic_perform_write(file, &i, pos);
2291 status = generic_perform_write_2copy(file, &i, pos);
2293 if (likely(status >= 0)) {
2295 *ppos = pos + status;
2298 * For now, when the user asks for O_SYNC, we'll actually give
2301 if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2302 if (!a_ops->writepage || !is_sync_kiocb(iocb))
2303 status = generic_osync_inode(inode, mapping,
2304 OSYNC_METADATA|OSYNC_DATA);
2309 * If we get here for O_DIRECT writes then we must have fallen through
2310 * to buffered writes (block instantiation inside i_size). So we sync
2311 * the file data here, to try to honour O_DIRECT expectations.
2313 if (unlikely(file->f_flags & O_DIRECT) && written)
2314 status = filemap_write_and_wait(mapping);
2316 return written ? written : status;
2318 EXPORT_SYMBOL(generic_file_buffered_write);
2321 __generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2322 unsigned long nr_segs, loff_t *ppos)
2324 struct file *file = iocb->ki_filp;
2325 struct address_space * mapping = file->f_mapping;
2326 size_t ocount; /* original count */
2327 size_t count; /* after file limit checks */
2328 struct inode *inode = mapping->host;
2334 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2341 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2343 /* We can write back this queue in page reclaim */
2344 current->backing_dev_info = mapping->backing_dev_info;
2347 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2354 err = remove_suid(file->f_path.dentry);
2358 file_update_time(file);
2360 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2361 if (unlikely(file->f_flags & O_DIRECT)) {
2363 ssize_t written_buffered;
2365 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2366 ppos, count, ocount);
2367 if (written < 0 || written == count)
2370 * direct-io write to a hole: fall through to buffered I/O
2371 * for completing the rest of the request.
2375 written_buffered = generic_file_buffered_write(iocb, iov,
2376 nr_segs, pos, ppos, count,
2379 * If generic_file_buffered_write() retuned a synchronous error
2380 * then we want to return the number of bytes which were
2381 * direct-written, or the error code if that was zero. Note
2382 * that this differs from normal direct-io semantics, which
2383 * will return -EFOO even if some bytes were written.
2385 if (written_buffered < 0) {
2386 err = written_buffered;
2391 * We need to ensure that the page cache pages are written to
2392 * disk and invalidated to preserve the expected O_DIRECT
2395 endbyte = pos + written_buffered - written - 1;
2396 err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
2397 SYNC_FILE_RANGE_WAIT_BEFORE|
2398 SYNC_FILE_RANGE_WRITE|
2399 SYNC_FILE_RANGE_WAIT_AFTER);
2401 written = written_buffered;
2402 invalidate_mapping_pages(mapping,
2403 pos >> PAGE_CACHE_SHIFT,
2404 endbyte >> PAGE_CACHE_SHIFT);
2407 * We don't know how much we wrote, so just return
2408 * the number of bytes which were direct-written
2412 written = generic_file_buffered_write(iocb, iov, nr_segs,
2413 pos, ppos, count, written);
2416 current->backing_dev_info = NULL;
2417 return written ? written : err;
2420 ssize_t generic_file_aio_write_nolock(struct kiocb *iocb,
2421 const struct iovec *iov, unsigned long nr_segs, loff_t pos)
2423 struct file *file = iocb->ki_filp;
2424 struct address_space *mapping = file->f_mapping;
2425 struct inode *inode = mapping->host;
2428 BUG_ON(iocb->ki_pos != pos);
2430 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2433 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2436 err = sync_page_range_nolock(inode, mapping, pos, ret);
2442 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2444 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2445 unsigned long nr_segs, loff_t pos)
2447 struct file *file = iocb->ki_filp;
2448 struct address_space *mapping = file->f_mapping;
2449 struct inode *inode = mapping->host;
2452 BUG_ON(iocb->ki_pos != pos);
2454 mutex_lock(&inode->i_mutex);
2455 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2457 mutex_unlock(&inode->i_mutex);
2459 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2462 err = sync_page_range(inode, mapping, pos, ret);
2468 EXPORT_SYMBOL(generic_file_aio_write);
2471 * Called under i_mutex for writes to S_ISREG files. Returns -EIO if something
2472 * went wrong during pagecache shootdown.
2475 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2476 loff_t offset, unsigned long nr_segs)
2478 struct file *file = iocb->ki_filp;
2479 struct address_space *mapping = file->f_mapping;
2482 pgoff_t end = 0; /* silence gcc */
2485 * If it's a write, unmap all mmappings of the file up-front. This
2486 * will cause any pte dirty bits to be propagated into the pageframes
2487 * for the subsequent filemap_write_and_wait().
2490 write_len = iov_length(iov, nr_segs);
2491 end = (offset + write_len - 1) >> PAGE_CACHE_SHIFT;
2492 if (mapping_mapped(mapping))
2493 unmap_mapping_range(mapping, offset, write_len, 0);
2496 retval = filemap_write_and_wait(mapping);
2501 * After a write we want buffered reads to be sure to go to disk to get
2502 * the new data. We invalidate clean cached page from the region we're
2503 * about to write. We do this *before* the write so that we can return
2504 * -EIO without clobbering -EIOCBQUEUED from ->direct_IO().
2506 if (rw == WRITE && mapping->nrpages) {
2507 retval = invalidate_inode_pages2_range(mapping,
2508 offset >> PAGE_CACHE_SHIFT, end);
2513 retval = mapping->a_ops->direct_IO(rw, iocb, iov, offset, nr_segs);
2518 * Finally, try again to invalidate clean pages which might have been
2519 * faulted in by get_user_pages() if the source of the write was an
2520 * mmap()ed region of the file we're writing. That's a pretty crazy
2521 * thing to do, so we don't support it 100%. If this invalidation
2522 * fails and we have -EIOCBQUEUED we ignore the failure.
2524 if (rw == WRITE && mapping->nrpages) {
2525 int err = invalidate_inode_pages2_range(mapping,
2526 offset >> PAGE_CACHE_SHIFT, end);
2527 if (err && retval >= 0)
2535 * try_to_release_page() - release old fs-specific metadata on a page
2537 * @page: the page which the kernel is trying to free
2538 * @gfp_mask: memory allocation flags (and I/O mode)
2540 * The address_space is to try to release any data against the page
2541 * (presumably at page->private). If the release was successful, return `1'.
2542 * Otherwise return zero.
2544 * The @gfp_mask argument specifies whether I/O may be performed to release
2545 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
2547 * NOTE: @gfp_mask may go away, and this function may become non-blocking.
2549 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2551 struct address_space * const mapping = page->mapping;
2553 BUG_ON(!PageLocked(page));
2554 if (PageWriteback(page))
2557 if (mapping && mapping->a_ops->releasepage)
2558 return mapping->a_ops->releasepage(page, gfp_mask);
2559 return try_to_free_buffers(page);
2562 EXPORT_SYMBOL(try_to_release_page);