spi-topcliff-pch: supports a spi mode setup and bit order setup by IO control
[zen-stable.git] / mm / filemap.c
blobb66275757c281b39e1d7cc0fecf6465bea5b4257
1 /*
2 * linux/mm/filemap.c
4 * Copyright (C) 1994-1999 Linus Torvalds
5 */
7 /*
8 * This file handles the generic file mmap semantics used by
9 * most "normal" filesystems (but you don't /have/ to use this:
10 * the NFS filesystem used to do this differently, for example)
12 #include <linux/export.h>
13 #include <linux/compiler.h>
14 #include <linux/fs.h>
15 #include <linux/uaccess.h>
16 #include <linux/aio.h>
17 #include <linux/capability.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/gfp.h>
20 #include <linux/mm.h>
21 #include <linux/swap.h>
22 #include <linux/mman.h>
23 #include <linux/pagemap.h>
24 #include <linux/file.h>
25 #include <linux/uio.h>
26 #include <linux/hash.h>
27 #include <linux/writeback.h>
28 #include <linux/backing-dev.h>
29 #include <linux/pagevec.h>
30 #include <linux/blkdev.h>
31 #include <linux/security.h>
32 #include <linux/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/cleancache.h>
37 #include "internal.h"
40 * FIXME: remove all knowledge of the buffer layer from the core VM
42 #include <linux/buffer_head.h> /* for try_to_free_buffers */
44 #include <asm/mman.h>
47 * Shared mappings implemented 30.11.1994. It's not fully working yet,
48 * though.
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>
59 * Lock ordering:
61 * ->i_mmap_mutex (truncate_pagecache)
62 * ->private_lock (__free_pte->__set_page_dirty_buffers)
63 * ->swap_lock (exclusive_swap_page, others)
64 * ->mapping->tree_lock
66 * ->i_mutex
67 * ->i_mmap_mutex (truncate->unmap_mapping_range)
69 * ->mmap_sem
70 * ->i_mmap_mutex
71 * ->page_table_lock or pte_lock (various, mainly in memory.c)
72 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
74 * ->mmap_sem
75 * ->lock_page (access_process_vm)
77 * ->i_mutex (generic_file_buffered_write)
78 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
80 * bdi->wb.list_lock
81 * sb_lock (fs/fs-writeback.c)
82 * ->mapping->tree_lock (__sync_single_inode)
84 * ->i_mmap_mutex
85 * ->anon_vma.lock (vma_adjust)
87 * ->anon_vma.lock
88 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
90 * ->page_table_lock or pte_lock
91 * ->swap_lock (try_to_unmap_one)
92 * ->private_lock (try_to_unmap_one)
93 * ->tree_lock (try_to_unmap_one)
94 * ->zone.lru_lock (follow_page->mark_page_accessed)
95 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
96 * ->private_lock (page_remove_rmap->set_page_dirty)
97 * ->tree_lock (page_remove_rmap->set_page_dirty)
98 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
99 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
100 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
101 * ->inode->i_lock (zap_pte_range->set_page_dirty)
102 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
104 * (code doesn't rely on that order, so you could switch it around)
105 * ->tasklist_lock (memory_failure, collect_procs_ao)
106 * ->i_mmap_mutex
110 * Delete a page from the page cache and free it. Caller has to make
111 * sure the page is locked and that nobody else uses it - or that usage
112 * is safe. The caller must hold the mapping's tree_lock.
114 void __delete_from_page_cache(struct page *page)
116 struct address_space *mapping = page->mapping;
119 * if we're uptodate, flush out into the cleancache, otherwise
120 * invalidate any existing cleancache entries. We can't leave
121 * stale data around in the cleancache once our page is gone
123 if (PageUptodate(page) && PageMappedToDisk(page))
124 cleancache_put_page(page);
125 else
126 cleancache_flush_page(mapping, page);
128 radix_tree_delete(&mapping->page_tree, page->index);
129 page->mapping = NULL;
130 /* Leave page->index set: truncation lookup relies upon it */
131 mapping->nrpages--;
132 __dec_zone_page_state(page, NR_FILE_PAGES);
133 if (PageSwapBacked(page))
134 __dec_zone_page_state(page, NR_SHMEM);
135 BUG_ON(page_mapped(page));
138 * Some filesystems seem to re-dirty the page even after
139 * the VM has canceled the dirty bit (eg ext3 journaling).
141 * Fix it up by doing a final dirty accounting check after
142 * having removed the page entirely.
144 if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
145 dec_zone_page_state(page, NR_FILE_DIRTY);
146 dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
151 * delete_from_page_cache - delete page from page cache
152 * @page: the page which the kernel is trying to remove from page cache
154 * This must be called only on pages that have been verified to be in the page
155 * cache and locked. It will never put the page into the free list, the caller
156 * has a reference on the page.
158 void delete_from_page_cache(struct page *page)
160 struct address_space *mapping = page->mapping;
161 void (*freepage)(struct page *);
163 BUG_ON(!PageLocked(page));
165 freepage = mapping->a_ops->freepage;
166 spin_lock_irq(&mapping->tree_lock);
167 __delete_from_page_cache(page);
168 spin_unlock_irq(&mapping->tree_lock);
169 mem_cgroup_uncharge_cache_page(page);
171 if (freepage)
172 freepage(page);
173 page_cache_release(page);
175 EXPORT_SYMBOL(delete_from_page_cache);
177 static int sleep_on_page(void *word)
179 io_schedule();
180 return 0;
183 static int sleep_on_page_killable(void *word)
185 sleep_on_page(word);
186 return fatal_signal_pending(current) ? -EINTR : 0;
190 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
191 * @mapping: address space structure to write
192 * @start: offset in bytes where the range starts
193 * @end: offset in bytes where the range ends (inclusive)
194 * @sync_mode: enable synchronous operation
196 * Start writeback against all of a mapping's dirty pages that lie
197 * within the byte offsets <start, end> inclusive.
199 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
200 * opposed to a regular memory cleansing writeback. The difference between
201 * these two operations is that if a dirty page/buffer is encountered, it must
202 * be waited upon, and not just skipped over.
204 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
205 loff_t end, int sync_mode)
207 int ret;
208 struct writeback_control wbc = {
209 .sync_mode = sync_mode,
210 .nr_to_write = LONG_MAX,
211 .range_start = start,
212 .range_end = end,
215 if (!mapping_cap_writeback_dirty(mapping))
216 return 0;
218 ret = do_writepages(mapping, &wbc);
219 return ret;
222 static inline int __filemap_fdatawrite(struct address_space *mapping,
223 int sync_mode)
225 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
228 int filemap_fdatawrite(struct address_space *mapping)
230 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
232 EXPORT_SYMBOL(filemap_fdatawrite);
234 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
235 loff_t end)
237 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
239 EXPORT_SYMBOL(filemap_fdatawrite_range);
242 * filemap_flush - mostly a non-blocking flush
243 * @mapping: target address_space
245 * This is a mostly non-blocking flush. Not suitable for data-integrity
246 * purposes - I/O may not be started against all dirty pages.
248 int filemap_flush(struct address_space *mapping)
250 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
252 EXPORT_SYMBOL(filemap_flush);
255 * filemap_fdatawait_range - wait for writeback to complete
256 * @mapping: address space structure to wait for
257 * @start_byte: offset in bytes where the range starts
258 * @end_byte: offset in bytes where the range ends (inclusive)
260 * Walk the list of under-writeback pages of the given address space
261 * in the given range and wait for all of them.
263 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
264 loff_t end_byte)
266 pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
267 pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
268 struct pagevec pvec;
269 int nr_pages;
270 int ret = 0;
272 if (end_byte < start_byte)
273 return 0;
275 pagevec_init(&pvec, 0);
276 while ((index <= end) &&
277 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
278 PAGECACHE_TAG_WRITEBACK,
279 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
280 unsigned i;
282 for (i = 0; i < nr_pages; i++) {
283 struct page *page = pvec.pages[i];
285 /* until radix tree lookup accepts end_index */
286 if (page->index > end)
287 continue;
289 wait_on_page_writeback(page);
290 if (TestClearPageError(page))
291 ret = -EIO;
293 pagevec_release(&pvec);
294 cond_resched();
297 /* Check for outstanding write errors */
298 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
299 ret = -ENOSPC;
300 if (test_and_clear_bit(AS_EIO, &mapping->flags))
301 ret = -EIO;
303 return ret;
305 EXPORT_SYMBOL(filemap_fdatawait_range);
308 * filemap_fdatawait - wait for all under-writeback pages to complete
309 * @mapping: address space structure to wait for
311 * Walk the list of under-writeback pages of the given address space
312 * and wait for all of them.
314 int filemap_fdatawait(struct address_space *mapping)
316 loff_t i_size = i_size_read(mapping->host);
318 if (i_size == 0)
319 return 0;
321 return filemap_fdatawait_range(mapping, 0, i_size - 1);
323 EXPORT_SYMBOL(filemap_fdatawait);
325 int filemap_write_and_wait(struct address_space *mapping)
327 int err = 0;
329 if (mapping->nrpages) {
330 err = filemap_fdatawrite(mapping);
332 * Even if the above returned error, the pages may be
333 * written partially (e.g. -ENOSPC), so we wait for it.
334 * But the -EIO is special case, it may indicate the worst
335 * thing (e.g. bug) happened, so we avoid waiting for it.
337 if (err != -EIO) {
338 int err2 = filemap_fdatawait(mapping);
339 if (!err)
340 err = err2;
343 return err;
345 EXPORT_SYMBOL(filemap_write_and_wait);
348 * filemap_write_and_wait_range - write out & wait on a file range
349 * @mapping: the address_space for the pages
350 * @lstart: offset in bytes where the range starts
351 * @lend: offset in bytes where the range ends (inclusive)
353 * Write out and wait upon file offsets lstart->lend, inclusive.
355 * Note that `lend' is inclusive (describes the last byte to be written) so
356 * that this function can be used to write to the very end-of-file (end = -1).
358 int filemap_write_and_wait_range(struct address_space *mapping,
359 loff_t lstart, loff_t lend)
361 int err = 0;
363 if (mapping->nrpages) {
364 err = __filemap_fdatawrite_range(mapping, lstart, lend,
365 WB_SYNC_ALL);
366 /* See comment of filemap_write_and_wait() */
367 if (err != -EIO) {
368 int err2 = filemap_fdatawait_range(mapping,
369 lstart, lend);
370 if (!err)
371 err = err2;
374 return err;
376 EXPORT_SYMBOL(filemap_write_and_wait_range);
379 * replace_page_cache_page - replace a pagecache page with a new one
380 * @old: page to be replaced
381 * @new: page to replace with
382 * @gfp_mask: allocation mode
384 * This function replaces a page in the pagecache with a new one. On
385 * success it acquires the pagecache reference for the new page and
386 * drops it for the old page. Both the old and new pages must be
387 * locked. This function does not add the new page to the LRU, the
388 * caller must do that.
390 * The remove + add is atomic. The only way this function can fail is
391 * memory allocation failure.
393 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
395 int error;
397 VM_BUG_ON(!PageLocked(old));
398 VM_BUG_ON(!PageLocked(new));
399 VM_BUG_ON(new->mapping);
401 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
402 if (!error) {
403 struct address_space *mapping = old->mapping;
404 void (*freepage)(struct page *);
406 pgoff_t offset = old->index;
407 freepage = mapping->a_ops->freepage;
409 page_cache_get(new);
410 new->mapping = mapping;
411 new->index = offset;
413 spin_lock_irq(&mapping->tree_lock);
414 __delete_from_page_cache(old);
415 error = radix_tree_insert(&mapping->page_tree, offset, new);
416 BUG_ON(error);
417 mapping->nrpages++;
418 __inc_zone_page_state(new, NR_FILE_PAGES);
419 if (PageSwapBacked(new))
420 __inc_zone_page_state(new, NR_SHMEM);
421 spin_unlock_irq(&mapping->tree_lock);
422 /* mem_cgroup codes must not be called under tree_lock */
423 mem_cgroup_replace_page_cache(old, new);
424 radix_tree_preload_end();
425 if (freepage)
426 freepage(old);
427 page_cache_release(old);
430 return error;
432 EXPORT_SYMBOL_GPL(replace_page_cache_page);
435 * add_to_page_cache_locked - add a locked page to the pagecache
436 * @page: page to add
437 * @mapping: the page's address_space
438 * @offset: page index
439 * @gfp_mask: page allocation mode
441 * This function is used to add a page to the pagecache. It must be locked.
442 * This function does not add the page to the LRU. The caller must do that.
444 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
445 pgoff_t offset, gfp_t gfp_mask)
447 int error;
449 VM_BUG_ON(!PageLocked(page));
450 VM_BUG_ON(PageSwapBacked(page));
452 error = mem_cgroup_cache_charge(page, current->mm,
453 gfp_mask & GFP_RECLAIM_MASK);
454 if (error)
455 goto out;
457 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
458 if (error == 0) {
459 page_cache_get(page);
460 page->mapping = mapping;
461 page->index = offset;
463 spin_lock_irq(&mapping->tree_lock);
464 error = radix_tree_insert(&mapping->page_tree, offset, page);
465 if (likely(!error)) {
466 mapping->nrpages++;
467 __inc_zone_page_state(page, NR_FILE_PAGES);
468 spin_unlock_irq(&mapping->tree_lock);
469 } else {
470 page->mapping = NULL;
471 /* Leave page->index set: truncation relies upon it */
472 spin_unlock_irq(&mapping->tree_lock);
473 mem_cgroup_uncharge_cache_page(page);
474 page_cache_release(page);
476 radix_tree_preload_end();
477 } else
478 mem_cgroup_uncharge_cache_page(page);
479 out:
480 return error;
482 EXPORT_SYMBOL(add_to_page_cache_locked);
484 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
485 pgoff_t offset, gfp_t gfp_mask)
487 int ret;
489 ret = add_to_page_cache(page, mapping, offset, gfp_mask);
490 if (ret == 0)
491 lru_cache_add_file(page);
492 return ret;
494 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
496 #ifdef CONFIG_NUMA
497 struct page *__page_cache_alloc(gfp_t gfp)
499 int n;
500 struct page *page;
502 if (cpuset_do_page_mem_spread()) {
503 get_mems_allowed();
504 n = cpuset_mem_spread_node();
505 page = alloc_pages_exact_node(n, gfp, 0);
506 put_mems_allowed();
507 return page;
509 return alloc_pages(gfp, 0);
511 EXPORT_SYMBOL(__page_cache_alloc);
512 #endif
515 * In order to wait for pages to become available there must be
516 * waitqueues associated with pages. By using a hash table of
517 * waitqueues where the bucket discipline is to maintain all
518 * waiters on the same queue and wake all when any of the pages
519 * become available, and for the woken contexts to check to be
520 * sure the appropriate page became available, this saves space
521 * at a cost of "thundering herd" phenomena during rare hash
522 * collisions.
524 static wait_queue_head_t *page_waitqueue(struct page *page)
526 const struct zone *zone = page_zone(page);
528 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
531 static inline void wake_up_page(struct page *page, int bit)
533 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
536 void wait_on_page_bit(struct page *page, int bit_nr)
538 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
540 if (test_bit(bit_nr, &page->flags))
541 __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,
542 TASK_UNINTERRUPTIBLE);
544 EXPORT_SYMBOL(wait_on_page_bit);
546 int wait_on_page_bit_killable(struct page *page, int bit_nr)
548 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
550 if (!test_bit(bit_nr, &page->flags))
551 return 0;
553 return __wait_on_bit(page_waitqueue(page), &wait,
554 sleep_on_page_killable, TASK_KILLABLE);
558 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
559 * @page: Page defining the wait queue of interest
560 * @waiter: Waiter to add to the queue
562 * Add an arbitrary @waiter to the wait queue for the nominated @page.
564 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
566 wait_queue_head_t *q = page_waitqueue(page);
567 unsigned long flags;
569 spin_lock_irqsave(&q->lock, flags);
570 __add_wait_queue(q, waiter);
571 spin_unlock_irqrestore(&q->lock, flags);
573 EXPORT_SYMBOL_GPL(add_page_wait_queue);
576 * unlock_page - unlock a locked page
577 * @page: the page
579 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
580 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
581 * mechananism between PageLocked pages and PageWriteback pages is shared.
582 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
584 * The mb is necessary to enforce ordering between the clear_bit and the read
585 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
587 void unlock_page(struct page *page)
589 VM_BUG_ON(!PageLocked(page));
590 clear_bit_unlock(PG_locked, &page->flags);
591 smp_mb__after_clear_bit();
592 wake_up_page(page, PG_locked);
594 EXPORT_SYMBOL(unlock_page);
597 * end_page_writeback - end writeback against a page
598 * @page: the page
600 void end_page_writeback(struct page *page)
602 if (TestClearPageReclaim(page))
603 rotate_reclaimable_page(page);
605 if (!test_clear_page_writeback(page))
606 BUG();
608 smp_mb__after_clear_bit();
609 wake_up_page(page, PG_writeback);
611 EXPORT_SYMBOL(end_page_writeback);
614 * __lock_page - get a lock on the page, assuming we need to sleep to get it
615 * @page: the page to lock
617 void __lock_page(struct page *page)
619 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
621 __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,
622 TASK_UNINTERRUPTIBLE);
624 EXPORT_SYMBOL(__lock_page);
626 int __lock_page_killable(struct page *page)
628 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
630 return __wait_on_bit_lock(page_waitqueue(page), &wait,
631 sleep_on_page_killable, TASK_KILLABLE);
633 EXPORT_SYMBOL_GPL(__lock_page_killable);
635 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
636 unsigned int flags)
638 if (flags & FAULT_FLAG_ALLOW_RETRY) {
640 * CAUTION! In this case, mmap_sem is not released
641 * even though return 0.
643 if (flags & FAULT_FLAG_RETRY_NOWAIT)
644 return 0;
646 up_read(&mm->mmap_sem);
647 if (flags & FAULT_FLAG_KILLABLE)
648 wait_on_page_locked_killable(page);
649 else
650 wait_on_page_locked(page);
651 return 0;
652 } else {
653 if (flags & FAULT_FLAG_KILLABLE) {
654 int ret;
656 ret = __lock_page_killable(page);
657 if (ret) {
658 up_read(&mm->mmap_sem);
659 return 0;
661 } else
662 __lock_page(page);
663 return 1;
668 * find_get_page - find and get a page reference
669 * @mapping: the address_space to search
670 * @offset: the page index
672 * Is there a pagecache struct page at the given (mapping, offset) tuple?
673 * If yes, increment its refcount and return it; if no, return NULL.
675 struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
677 void **pagep;
678 struct page *page;
680 rcu_read_lock();
681 repeat:
682 page = NULL;
683 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
684 if (pagep) {
685 page = radix_tree_deref_slot(pagep);
686 if (unlikely(!page))
687 goto out;
688 if (radix_tree_exception(page)) {
689 if (radix_tree_deref_retry(page))
690 goto repeat;
692 * Otherwise, shmem/tmpfs must be storing a swap entry
693 * here as an exceptional entry: so return it without
694 * attempting to raise page count.
696 goto out;
698 if (!page_cache_get_speculative(page))
699 goto repeat;
702 * Has the page moved?
703 * This is part of the lockless pagecache protocol. See
704 * include/linux/pagemap.h for details.
706 if (unlikely(page != *pagep)) {
707 page_cache_release(page);
708 goto repeat;
711 out:
712 rcu_read_unlock();
714 return page;
716 EXPORT_SYMBOL(find_get_page);
719 * find_lock_page - locate, pin and lock a pagecache page
720 * @mapping: the address_space to search
721 * @offset: the page index
723 * Locates the desired pagecache page, locks it, increments its reference
724 * count and returns its address.
726 * Returns zero if the page was not present. find_lock_page() may sleep.
728 struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
730 struct page *page;
732 repeat:
733 page = find_get_page(mapping, offset);
734 if (page && !radix_tree_exception(page)) {
735 lock_page(page);
736 /* Has the page been truncated? */
737 if (unlikely(page->mapping != mapping)) {
738 unlock_page(page);
739 page_cache_release(page);
740 goto repeat;
742 VM_BUG_ON(page->index != offset);
744 return page;
746 EXPORT_SYMBOL(find_lock_page);
749 * find_or_create_page - locate or add a pagecache page
750 * @mapping: the page's address_space
751 * @index: the page's index into the mapping
752 * @gfp_mask: page allocation mode
754 * Locates a page in the pagecache. If the page is not present, a new page
755 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
756 * LRU list. The returned page is locked and has its reference count
757 * incremented.
759 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
760 * allocation!
762 * find_or_create_page() returns the desired page's address, or zero on
763 * memory exhaustion.
765 struct page *find_or_create_page(struct address_space *mapping,
766 pgoff_t index, gfp_t gfp_mask)
768 struct page *page;
769 int err;
770 repeat:
771 page = find_lock_page(mapping, index);
772 if (!page) {
773 page = __page_cache_alloc(gfp_mask);
774 if (!page)
775 return NULL;
777 * We want a regular kernel memory (not highmem or DMA etc)
778 * allocation for the radix tree nodes, but we need to honour
779 * the context-specific requirements the caller has asked for.
780 * GFP_RECLAIM_MASK collects those requirements.
782 err = add_to_page_cache_lru(page, mapping, index,
783 (gfp_mask & GFP_RECLAIM_MASK));
784 if (unlikely(err)) {
785 page_cache_release(page);
786 page = NULL;
787 if (err == -EEXIST)
788 goto repeat;
791 return page;
793 EXPORT_SYMBOL(find_or_create_page);
796 * find_get_pages - gang pagecache lookup
797 * @mapping: The address_space to search
798 * @start: The starting page index
799 * @nr_pages: The maximum number of pages
800 * @pages: Where the resulting pages are placed
802 * find_get_pages() will search for and return a group of up to
803 * @nr_pages pages in the mapping. The pages are placed at @pages.
804 * find_get_pages() takes a reference against the returned pages.
806 * The search returns a group of mapping-contiguous pages with ascending
807 * indexes. There may be holes in the indices due to not-present pages.
809 * find_get_pages() returns the number of pages which were found.
811 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
812 unsigned int nr_pages, struct page **pages)
814 unsigned int i;
815 unsigned int ret;
816 unsigned int nr_found, nr_skip;
818 rcu_read_lock();
819 restart:
820 nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
821 (void ***)pages, NULL, start, nr_pages);
822 ret = 0;
823 nr_skip = 0;
824 for (i = 0; i < nr_found; i++) {
825 struct page *page;
826 repeat:
827 page = radix_tree_deref_slot((void **)pages[i]);
828 if (unlikely(!page))
829 continue;
831 if (radix_tree_exception(page)) {
832 if (radix_tree_deref_retry(page)) {
834 * Transient condition which can only trigger
835 * when entry at index 0 moves out of or back
836 * to root: none yet gotten, safe to restart.
838 WARN_ON(start | i);
839 goto restart;
842 * Otherwise, shmem/tmpfs must be storing a swap entry
843 * here as an exceptional entry: so skip over it -
844 * we only reach this from invalidate_mapping_pages().
846 nr_skip++;
847 continue;
850 if (!page_cache_get_speculative(page))
851 goto repeat;
853 /* Has the page moved? */
854 if (unlikely(page != *((void **)pages[i]))) {
855 page_cache_release(page);
856 goto repeat;
859 pages[ret] = page;
860 ret++;
864 * If all entries were removed before we could secure them,
865 * try again, because callers stop trying once 0 is returned.
867 if (unlikely(!ret && nr_found > nr_skip))
868 goto restart;
869 rcu_read_unlock();
870 return ret;
874 * find_get_pages_contig - gang contiguous pagecache lookup
875 * @mapping: The address_space to search
876 * @index: The starting page index
877 * @nr_pages: The maximum number of pages
878 * @pages: Where the resulting pages are placed
880 * find_get_pages_contig() works exactly like find_get_pages(), except
881 * that the returned number of pages are guaranteed to be contiguous.
883 * find_get_pages_contig() returns the number of pages which were found.
885 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
886 unsigned int nr_pages, struct page **pages)
888 unsigned int i;
889 unsigned int ret;
890 unsigned int nr_found;
892 rcu_read_lock();
893 restart:
894 nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
895 (void ***)pages, NULL, index, nr_pages);
896 ret = 0;
897 for (i = 0; i < nr_found; i++) {
898 struct page *page;
899 repeat:
900 page = radix_tree_deref_slot((void **)pages[i]);
901 if (unlikely(!page))
902 continue;
904 if (radix_tree_exception(page)) {
905 if (radix_tree_deref_retry(page)) {
907 * Transient condition which can only trigger
908 * when entry at index 0 moves out of or back
909 * to root: none yet gotten, safe to restart.
911 goto restart;
914 * Otherwise, shmem/tmpfs must be storing a swap entry
915 * here as an exceptional entry: so stop looking for
916 * contiguous pages.
918 break;
921 if (!page_cache_get_speculative(page))
922 goto repeat;
924 /* Has the page moved? */
925 if (unlikely(page != *((void **)pages[i]))) {
926 page_cache_release(page);
927 goto repeat;
931 * must check mapping and index after taking the ref.
932 * otherwise we can get both false positives and false
933 * negatives, which is just confusing to the caller.
935 if (page->mapping == NULL || page->index != index) {
936 page_cache_release(page);
937 break;
940 pages[ret] = page;
941 ret++;
942 index++;
944 rcu_read_unlock();
945 return ret;
947 EXPORT_SYMBOL(find_get_pages_contig);
950 * find_get_pages_tag - find and return pages that match @tag
951 * @mapping: the address_space to search
952 * @index: the starting page index
953 * @tag: the tag index
954 * @nr_pages: the maximum number of pages
955 * @pages: where the resulting pages are placed
957 * Like find_get_pages, except we only return pages which are tagged with
958 * @tag. We update @index to index the next page for the traversal.
960 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
961 int tag, unsigned int nr_pages, struct page **pages)
963 unsigned int i;
964 unsigned int ret;
965 unsigned int nr_found;
967 rcu_read_lock();
968 restart:
969 nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,
970 (void ***)pages, *index, nr_pages, tag);
971 ret = 0;
972 for (i = 0; i < nr_found; i++) {
973 struct page *page;
974 repeat:
975 page = radix_tree_deref_slot((void **)pages[i]);
976 if (unlikely(!page))
977 continue;
979 if (radix_tree_exception(page)) {
980 if (radix_tree_deref_retry(page)) {
982 * Transient condition which can only trigger
983 * when entry at index 0 moves out of or back
984 * to root: none yet gotten, safe to restart.
986 goto restart;
989 * This function is never used on a shmem/tmpfs
990 * mapping, so a swap entry won't be found here.
992 BUG();
995 if (!page_cache_get_speculative(page))
996 goto repeat;
998 /* Has the page moved? */
999 if (unlikely(page != *((void **)pages[i]))) {
1000 page_cache_release(page);
1001 goto repeat;
1004 pages[ret] = page;
1005 ret++;
1009 * If all entries were removed before we could secure them,
1010 * try again, because callers stop trying once 0 is returned.
1012 if (unlikely(!ret && nr_found))
1013 goto restart;
1014 rcu_read_unlock();
1016 if (ret)
1017 *index = pages[ret - 1]->index + 1;
1019 return ret;
1021 EXPORT_SYMBOL(find_get_pages_tag);
1024 * grab_cache_page_nowait - returns locked page at given index in given cache
1025 * @mapping: target address_space
1026 * @index: the page index
1028 * Same as grab_cache_page(), but do not wait if the page is unavailable.
1029 * This is intended for speculative data generators, where the data can
1030 * be regenerated if the page couldn't be grabbed. This routine should
1031 * be safe to call while holding the lock for another page.
1033 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
1034 * and deadlock against the caller's locked page.
1036 struct page *
1037 grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
1039 struct page *page = find_get_page(mapping, index);
1041 if (page) {
1042 if (trylock_page(page))
1043 return page;
1044 page_cache_release(page);
1045 return NULL;
1047 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
1048 if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
1049 page_cache_release(page);
1050 page = NULL;
1052 return page;
1054 EXPORT_SYMBOL(grab_cache_page_nowait);
1057 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1058 * a _large_ part of the i/o request. Imagine the worst scenario:
1060 * ---R__________________________________________B__________
1061 * ^ reading here ^ bad block(assume 4k)
1063 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1064 * => failing the whole request => read(R) => read(R+1) =>
1065 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1066 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1067 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1069 * It is going insane. Fix it by quickly scaling down the readahead size.
1071 static void shrink_readahead_size_eio(struct file *filp,
1072 struct file_ra_state *ra)
1074 ra->ra_pages /= 4;
1078 * do_generic_file_read - generic file read routine
1079 * @filp: the file to read
1080 * @ppos: current file position
1081 * @desc: read_descriptor
1082 * @actor: read method
1084 * This is a generic file read routine, and uses the
1085 * mapping->a_ops->readpage() function for the actual low-level stuff.
1087 * This is really ugly. But the goto's actually try to clarify some
1088 * of the logic when it comes to error handling etc.
1090 static void do_generic_file_read(struct file *filp, loff_t *ppos,
1091 read_descriptor_t *desc, read_actor_t actor)
1093 struct address_space *mapping = filp->f_mapping;
1094 struct inode *inode = mapping->host;
1095 struct file_ra_state *ra = &filp->f_ra;
1096 pgoff_t index;
1097 pgoff_t last_index;
1098 pgoff_t prev_index;
1099 unsigned long offset; /* offset into pagecache page */
1100 unsigned int prev_offset;
1101 int error;
1103 index = *ppos >> PAGE_CACHE_SHIFT;
1104 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
1105 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1106 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
1107 offset = *ppos & ~PAGE_CACHE_MASK;
1109 for (;;) {
1110 struct page *page;
1111 pgoff_t end_index;
1112 loff_t isize;
1113 unsigned long nr, ret;
1115 cond_resched();
1116 find_page:
1117 page = find_get_page(mapping, index);
1118 if (!page) {
1119 page_cache_sync_readahead(mapping,
1120 ra, filp,
1121 index, last_index - index);
1122 page = find_get_page(mapping, index);
1123 if (unlikely(page == NULL))
1124 goto no_cached_page;
1126 if (PageReadahead(page)) {
1127 page_cache_async_readahead(mapping,
1128 ra, filp, page,
1129 index, last_index - index);
1131 if (!PageUptodate(page)) {
1132 if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
1133 !mapping->a_ops->is_partially_uptodate)
1134 goto page_not_up_to_date;
1135 if (!trylock_page(page))
1136 goto page_not_up_to_date;
1137 /* Did it get truncated before we got the lock? */
1138 if (!page->mapping)
1139 goto page_not_up_to_date_locked;
1140 if (!mapping->a_ops->is_partially_uptodate(page,
1141 desc, offset))
1142 goto page_not_up_to_date_locked;
1143 unlock_page(page);
1145 page_ok:
1147 * i_size must be checked after we know the page is Uptodate.
1149 * Checking i_size after the check allows us to calculate
1150 * the correct value for "nr", which means the zero-filled
1151 * part of the page is not copied back to userspace (unless
1152 * another truncate extends the file - this is desired though).
1155 isize = i_size_read(inode);
1156 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1157 if (unlikely(!isize || index > end_index)) {
1158 page_cache_release(page);
1159 goto out;
1162 /* nr is the maximum number of bytes to copy from this page */
1163 nr = PAGE_CACHE_SIZE;
1164 if (index == end_index) {
1165 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1166 if (nr <= offset) {
1167 page_cache_release(page);
1168 goto out;
1171 nr = nr - offset;
1173 /* If users can be writing to this page using arbitrary
1174 * virtual addresses, take care about potential aliasing
1175 * before reading the page on the kernel side.
1177 if (mapping_writably_mapped(mapping))
1178 flush_dcache_page(page);
1181 * When a sequential read accesses a page several times,
1182 * only mark it as accessed the first time.
1184 if (prev_index != index || offset != prev_offset)
1185 mark_page_accessed(page);
1186 prev_index = index;
1189 * Ok, we have the page, and it's up-to-date, so
1190 * now we can copy it to user space...
1192 * The actor routine returns how many bytes were actually used..
1193 * NOTE! This may not be the same as how much of a user buffer
1194 * we filled up (we may be padding etc), so we can only update
1195 * "pos" here (the actor routine has to update the user buffer
1196 * pointers and the remaining count).
1198 ret = actor(desc, page, offset, nr);
1199 offset += ret;
1200 index += offset >> PAGE_CACHE_SHIFT;
1201 offset &= ~PAGE_CACHE_MASK;
1202 prev_offset = offset;
1204 page_cache_release(page);
1205 if (ret == nr && desc->count)
1206 continue;
1207 goto out;
1209 page_not_up_to_date:
1210 /* Get exclusive access to the page ... */
1211 error = lock_page_killable(page);
1212 if (unlikely(error))
1213 goto readpage_error;
1215 page_not_up_to_date_locked:
1216 /* Did it get truncated before we got the lock? */
1217 if (!page->mapping) {
1218 unlock_page(page);
1219 page_cache_release(page);
1220 continue;
1223 /* Did somebody else fill it already? */
1224 if (PageUptodate(page)) {
1225 unlock_page(page);
1226 goto page_ok;
1229 readpage:
1231 * A previous I/O error may have been due to temporary
1232 * failures, eg. multipath errors.
1233 * PG_error will be set again if readpage fails.
1235 ClearPageError(page);
1236 /* Start the actual read. The read will unlock the page. */
1237 error = mapping->a_ops->readpage(filp, page);
1239 if (unlikely(error)) {
1240 if (error == AOP_TRUNCATED_PAGE) {
1241 page_cache_release(page);
1242 goto find_page;
1244 goto readpage_error;
1247 if (!PageUptodate(page)) {
1248 error = lock_page_killable(page);
1249 if (unlikely(error))
1250 goto readpage_error;
1251 if (!PageUptodate(page)) {
1252 if (page->mapping == NULL) {
1254 * invalidate_mapping_pages got it
1256 unlock_page(page);
1257 page_cache_release(page);
1258 goto find_page;
1260 unlock_page(page);
1261 shrink_readahead_size_eio(filp, ra);
1262 error = -EIO;
1263 goto readpage_error;
1265 unlock_page(page);
1268 goto page_ok;
1270 readpage_error:
1271 /* UHHUH! A synchronous read error occurred. Report it */
1272 desc->error = error;
1273 page_cache_release(page);
1274 goto out;
1276 no_cached_page:
1278 * Ok, it wasn't cached, so we need to create a new
1279 * page..
1281 page = page_cache_alloc_cold(mapping);
1282 if (!page) {
1283 desc->error = -ENOMEM;
1284 goto out;
1286 error = add_to_page_cache_lru(page, mapping,
1287 index, GFP_KERNEL);
1288 if (error) {
1289 page_cache_release(page);
1290 if (error == -EEXIST)
1291 goto find_page;
1292 desc->error = error;
1293 goto out;
1295 goto readpage;
1298 out:
1299 ra->prev_pos = prev_index;
1300 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1301 ra->prev_pos |= prev_offset;
1303 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1304 file_accessed(filp);
1307 int file_read_actor(read_descriptor_t *desc, struct page *page,
1308 unsigned long offset, unsigned long size)
1310 char *kaddr;
1311 unsigned long left, count = desc->count;
1313 if (size > count)
1314 size = count;
1317 * Faults on the destination of a read are common, so do it before
1318 * taking the kmap.
1320 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1321 kaddr = kmap_atomic(page, KM_USER0);
1322 left = __copy_to_user_inatomic(desc->arg.buf,
1323 kaddr + offset, size);
1324 kunmap_atomic(kaddr, KM_USER0);
1325 if (left == 0)
1326 goto success;
1329 /* Do it the slow way */
1330 kaddr = kmap(page);
1331 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1332 kunmap(page);
1334 if (left) {
1335 size -= left;
1336 desc->error = -EFAULT;
1338 success:
1339 desc->count = count - size;
1340 desc->written += size;
1341 desc->arg.buf += size;
1342 return size;
1346 * Performs necessary checks before doing a write
1347 * @iov: io vector request
1348 * @nr_segs: number of segments in the iovec
1349 * @count: number of bytes to write
1350 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1352 * Adjust number of segments and amount of bytes to write (nr_segs should be
1353 * properly initialized first). Returns appropriate error code that caller
1354 * should return or zero in case that write should be allowed.
1356 int generic_segment_checks(const struct iovec *iov,
1357 unsigned long *nr_segs, size_t *count, int access_flags)
1359 unsigned long seg;
1360 size_t cnt = 0;
1361 for (seg = 0; seg < *nr_segs; seg++) {
1362 const struct iovec *iv = &iov[seg];
1365 * If any segment has a negative length, or the cumulative
1366 * length ever wraps negative then return -EINVAL.
1368 cnt += iv->iov_len;
1369 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1370 return -EINVAL;
1371 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1372 continue;
1373 if (seg == 0)
1374 return -EFAULT;
1375 *nr_segs = seg;
1376 cnt -= iv->iov_len; /* This segment is no good */
1377 break;
1379 *count = cnt;
1380 return 0;
1382 EXPORT_SYMBOL(generic_segment_checks);
1385 * generic_file_aio_read - generic filesystem read routine
1386 * @iocb: kernel I/O control block
1387 * @iov: io vector request
1388 * @nr_segs: number of segments in the iovec
1389 * @pos: current file position
1391 * This is the "read()" routine for all filesystems
1392 * that can use the page cache directly.
1394 ssize_t
1395 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1396 unsigned long nr_segs, loff_t pos)
1398 struct file *filp = iocb->ki_filp;
1399 ssize_t retval;
1400 unsigned long seg = 0;
1401 size_t count;
1402 loff_t *ppos = &iocb->ki_pos;
1404 count = 0;
1405 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1406 if (retval)
1407 return retval;
1409 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1410 if (filp->f_flags & O_DIRECT) {
1411 loff_t size;
1412 struct address_space *mapping;
1413 struct inode *inode;
1415 mapping = filp->f_mapping;
1416 inode = mapping->host;
1417 if (!count)
1418 goto out; /* skip atime */
1419 size = i_size_read(inode);
1420 if (pos < size) {
1421 retval = filemap_write_and_wait_range(mapping, pos,
1422 pos + iov_length(iov, nr_segs) - 1);
1423 if (!retval) {
1424 struct blk_plug plug;
1426 blk_start_plug(&plug);
1427 retval = mapping->a_ops->direct_IO(READ, iocb,
1428 iov, pos, nr_segs);
1429 blk_finish_plug(&plug);
1431 if (retval > 0) {
1432 *ppos = pos + retval;
1433 count -= retval;
1437 * Btrfs can have a short DIO read if we encounter
1438 * compressed extents, so if there was an error, or if
1439 * we've already read everything we wanted to, or if
1440 * there was a short read because we hit EOF, go ahead
1441 * and return. Otherwise fallthrough to buffered io for
1442 * the rest of the read.
1444 if (retval < 0 || !count || *ppos >= size) {
1445 file_accessed(filp);
1446 goto out;
1451 count = retval;
1452 for (seg = 0; seg < nr_segs; seg++) {
1453 read_descriptor_t desc;
1454 loff_t offset = 0;
1457 * If we did a short DIO read we need to skip the section of the
1458 * iov that we've already read data into.
1460 if (count) {
1461 if (count > iov[seg].iov_len) {
1462 count -= iov[seg].iov_len;
1463 continue;
1465 offset = count;
1466 count = 0;
1469 desc.written = 0;
1470 desc.arg.buf = iov[seg].iov_base + offset;
1471 desc.count = iov[seg].iov_len - offset;
1472 if (desc.count == 0)
1473 continue;
1474 desc.error = 0;
1475 do_generic_file_read(filp, ppos, &desc, file_read_actor);
1476 retval += desc.written;
1477 if (desc.error) {
1478 retval = retval ?: desc.error;
1479 break;
1481 if (desc.count > 0)
1482 break;
1484 out:
1485 return retval;
1487 EXPORT_SYMBOL(generic_file_aio_read);
1489 static ssize_t
1490 do_readahead(struct address_space *mapping, struct file *filp,
1491 pgoff_t index, unsigned long nr)
1493 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1494 return -EINVAL;
1496 force_page_cache_readahead(mapping, filp, index, nr);
1497 return 0;
1500 SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
1502 ssize_t ret;
1503 struct file *file;
1505 ret = -EBADF;
1506 file = fget(fd);
1507 if (file) {
1508 if (file->f_mode & FMODE_READ) {
1509 struct address_space *mapping = file->f_mapping;
1510 pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1511 pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1512 unsigned long len = end - start + 1;
1513 ret = do_readahead(mapping, file, start, len);
1515 fput(file);
1517 return ret;
1519 #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
1520 asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
1522 return SYSC_readahead((int) fd, offset, (size_t) count);
1524 SYSCALL_ALIAS(sys_readahead, SyS_readahead);
1525 #endif
1527 #ifdef CONFIG_MMU
1529 * page_cache_read - adds requested page to the page cache if not already there
1530 * @file: file to read
1531 * @offset: page index
1533 * This adds the requested page to the page cache if it isn't already there,
1534 * and schedules an I/O to read in its contents from disk.
1536 static int page_cache_read(struct file *file, pgoff_t offset)
1538 struct address_space *mapping = file->f_mapping;
1539 struct page *page;
1540 int ret;
1542 do {
1543 page = page_cache_alloc_cold(mapping);
1544 if (!page)
1545 return -ENOMEM;
1547 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1548 if (ret == 0)
1549 ret = mapping->a_ops->readpage(file, page);
1550 else if (ret == -EEXIST)
1551 ret = 0; /* losing race to add is OK */
1553 page_cache_release(page);
1555 } while (ret == AOP_TRUNCATED_PAGE);
1557 return ret;
1560 #define MMAP_LOTSAMISS (100)
1563 * Synchronous readahead happens when we don't even find
1564 * a page in the page cache at all.
1566 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
1567 struct file_ra_state *ra,
1568 struct file *file,
1569 pgoff_t offset)
1571 unsigned long ra_pages;
1572 struct address_space *mapping = file->f_mapping;
1574 /* If we don't want any read-ahead, don't bother */
1575 if (VM_RandomReadHint(vma))
1576 return;
1577 if (!ra->ra_pages)
1578 return;
1580 if (VM_SequentialReadHint(vma)) {
1581 page_cache_sync_readahead(mapping, ra, file, offset,
1582 ra->ra_pages);
1583 return;
1586 /* Avoid banging the cache line if not needed */
1587 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
1588 ra->mmap_miss++;
1591 * Do we miss much more than hit in this file? If so,
1592 * stop bothering with read-ahead. It will only hurt.
1594 if (ra->mmap_miss > MMAP_LOTSAMISS)
1595 return;
1598 * mmap read-around
1600 ra_pages = max_sane_readahead(ra->ra_pages);
1601 ra->start = max_t(long, 0, offset - ra_pages / 2);
1602 ra->size = ra_pages;
1603 ra->async_size = ra_pages / 4;
1604 ra_submit(ra, mapping, file);
1608 * Asynchronous readahead happens when we find the page and PG_readahead,
1609 * so we want to possibly extend the readahead further..
1611 static void do_async_mmap_readahead(struct vm_area_struct *vma,
1612 struct file_ra_state *ra,
1613 struct file *file,
1614 struct page *page,
1615 pgoff_t offset)
1617 struct address_space *mapping = file->f_mapping;
1619 /* If we don't want any read-ahead, don't bother */
1620 if (VM_RandomReadHint(vma))
1621 return;
1622 if (ra->mmap_miss > 0)
1623 ra->mmap_miss--;
1624 if (PageReadahead(page))
1625 page_cache_async_readahead(mapping, ra, file,
1626 page, offset, ra->ra_pages);
1630 * filemap_fault - read in file data for page fault handling
1631 * @vma: vma in which the fault was taken
1632 * @vmf: struct vm_fault containing details of the fault
1634 * filemap_fault() is invoked via the vma operations vector for a
1635 * mapped memory region to read in file data during a page fault.
1637 * The goto's are kind of ugly, but this streamlines the normal case of having
1638 * it in the page cache, and handles the special cases reasonably without
1639 * having a lot of duplicated code.
1641 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1643 int error;
1644 struct file *file = vma->vm_file;
1645 struct address_space *mapping = file->f_mapping;
1646 struct file_ra_state *ra = &file->f_ra;
1647 struct inode *inode = mapping->host;
1648 pgoff_t offset = vmf->pgoff;
1649 struct page *page;
1650 pgoff_t size;
1651 int ret = 0;
1653 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1654 if (offset >= size)
1655 return VM_FAULT_SIGBUS;
1658 * Do we have something in the page cache already?
1660 page = find_get_page(mapping, offset);
1661 if (likely(page)) {
1663 * We found the page, so try async readahead before
1664 * waiting for the lock.
1666 do_async_mmap_readahead(vma, ra, file, page, offset);
1667 } else {
1668 /* No page in the page cache at all */
1669 do_sync_mmap_readahead(vma, ra, file, offset);
1670 count_vm_event(PGMAJFAULT);
1671 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
1672 ret = VM_FAULT_MAJOR;
1673 retry_find:
1674 page = find_get_page(mapping, offset);
1675 if (!page)
1676 goto no_cached_page;
1679 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
1680 page_cache_release(page);
1681 return ret | VM_FAULT_RETRY;
1684 /* Did it get truncated? */
1685 if (unlikely(page->mapping != mapping)) {
1686 unlock_page(page);
1687 put_page(page);
1688 goto retry_find;
1690 VM_BUG_ON(page->index != offset);
1693 * We have a locked page in the page cache, now we need to check
1694 * that it's up-to-date. If not, it is going to be due to an error.
1696 if (unlikely(!PageUptodate(page)))
1697 goto page_not_uptodate;
1700 * Found the page and have a reference on it.
1701 * We must recheck i_size under page lock.
1703 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1704 if (unlikely(offset >= size)) {
1705 unlock_page(page);
1706 page_cache_release(page);
1707 return VM_FAULT_SIGBUS;
1710 vmf->page = page;
1711 return ret | VM_FAULT_LOCKED;
1713 no_cached_page:
1715 * We're only likely to ever get here if MADV_RANDOM is in
1716 * effect.
1718 error = page_cache_read(file, offset);
1721 * The page we want has now been added to the page cache.
1722 * In the unlikely event that someone removed it in the
1723 * meantime, we'll just come back here and read it again.
1725 if (error >= 0)
1726 goto retry_find;
1729 * An error return from page_cache_read can result if the
1730 * system is low on memory, or a problem occurs while trying
1731 * to schedule I/O.
1733 if (error == -ENOMEM)
1734 return VM_FAULT_OOM;
1735 return VM_FAULT_SIGBUS;
1737 page_not_uptodate:
1739 * Umm, take care of errors if the page isn't up-to-date.
1740 * Try to re-read it _once_. We do this synchronously,
1741 * because there really aren't any performance issues here
1742 * and we need to check for errors.
1744 ClearPageError(page);
1745 error = mapping->a_ops->readpage(file, page);
1746 if (!error) {
1747 wait_on_page_locked(page);
1748 if (!PageUptodate(page))
1749 error = -EIO;
1751 page_cache_release(page);
1753 if (!error || error == AOP_TRUNCATED_PAGE)
1754 goto retry_find;
1756 /* Things didn't work out. Return zero to tell the mm layer so. */
1757 shrink_readahead_size_eio(file, ra);
1758 return VM_FAULT_SIGBUS;
1760 EXPORT_SYMBOL(filemap_fault);
1762 const struct vm_operations_struct generic_file_vm_ops = {
1763 .fault = filemap_fault,
1766 /* This is used for a general mmap of a disk file */
1768 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1770 struct address_space *mapping = file->f_mapping;
1772 if (!mapping->a_ops->readpage)
1773 return -ENOEXEC;
1774 file_accessed(file);
1775 vma->vm_ops = &generic_file_vm_ops;
1776 vma->vm_flags |= VM_CAN_NONLINEAR;
1777 return 0;
1781 * This is for filesystems which do not implement ->writepage.
1783 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1785 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1786 return -EINVAL;
1787 return generic_file_mmap(file, vma);
1789 #else
1790 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1792 return -ENOSYS;
1794 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1796 return -ENOSYS;
1798 #endif /* CONFIG_MMU */
1800 EXPORT_SYMBOL(generic_file_mmap);
1801 EXPORT_SYMBOL(generic_file_readonly_mmap);
1803 static struct page *__read_cache_page(struct address_space *mapping,
1804 pgoff_t index,
1805 int (*filler)(void *, struct page *),
1806 void *data,
1807 gfp_t gfp)
1809 struct page *page;
1810 int err;
1811 repeat:
1812 page = find_get_page(mapping, index);
1813 if (!page) {
1814 page = __page_cache_alloc(gfp | __GFP_COLD);
1815 if (!page)
1816 return ERR_PTR(-ENOMEM);
1817 err = add_to_page_cache_lru(page, mapping, index, gfp);
1818 if (unlikely(err)) {
1819 page_cache_release(page);
1820 if (err == -EEXIST)
1821 goto repeat;
1822 /* Presumably ENOMEM for radix tree node */
1823 return ERR_PTR(err);
1825 err = filler(data, page);
1826 if (err < 0) {
1827 page_cache_release(page);
1828 page = ERR_PTR(err);
1831 return page;
1834 static struct page *do_read_cache_page(struct address_space *mapping,
1835 pgoff_t index,
1836 int (*filler)(void *, struct page *),
1837 void *data,
1838 gfp_t gfp)
1841 struct page *page;
1842 int err;
1844 retry:
1845 page = __read_cache_page(mapping, index, filler, data, gfp);
1846 if (IS_ERR(page))
1847 return page;
1848 if (PageUptodate(page))
1849 goto out;
1851 lock_page(page);
1852 if (!page->mapping) {
1853 unlock_page(page);
1854 page_cache_release(page);
1855 goto retry;
1857 if (PageUptodate(page)) {
1858 unlock_page(page);
1859 goto out;
1861 err = filler(data, page);
1862 if (err < 0) {
1863 page_cache_release(page);
1864 return ERR_PTR(err);
1866 out:
1867 mark_page_accessed(page);
1868 return page;
1872 * read_cache_page_async - read into page cache, fill it if needed
1873 * @mapping: the page's address_space
1874 * @index: the page index
1875 * @filler: function to perform the read
1876 * @data: first arg to filler(data, page) function, often left as NULL
1878 * Same as read_cache_page, but don't wait for page to become unlocked
1879 * after submitting it to the filler.
1881 * Read into the page cache. If a page already exists, and PageUptodate() is
1882 * not set, try to fill the page but don't wait for it to become unlocked.
1884 * If the page does not get brought uptodate, return -EIO.
1886 struct page *read_cache_page_async(struct address_space *mapping,
1887 pgoff_t index,
1888 int (*filler)(void *, struct page *),
1889 void *data)
1891 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
1893 EXPORT_SYMBOL(read_cache_page_async);
1895 static struct page *wait_on_page_read(struct page *page)
1897 if (!IS_ERR(page)) {
1898 wait_on_page_locked(page);
1899 if (!PageUptodate(page)) {
1900 page_cache_release(page);
1901 page = ERR_PTR(-EIO);
1904 return page;
1908 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
1909 * @mapping: the page's address_space
1910 * @index: the page index
1911 * @gfp: the page allocator flags to use if allocating
1913 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
1914 * any new page allocations done using the specified allocation flags.
1916 * If the page does not get brought uptodate, return -EIO.
1918 struct page *read_cache_page_gfp(struct address_space *mapping,
1919 pgoff_t index,
1920 gfp_t gfp)
1922 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
1924 return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp));
1926 EXPORT_SYMBOL(read_cache_page_gfp);
1929 * read_cache_page - read into page cache, fill it if needed
1930 * @mapping: the page's address_space
1931 * @index: the page index
1932 * @filler: function to perform the read
1933 * @data: first arg to filler(data, page) function, often left as NULL
1935 * Read into the page cache. If a page already exists, and PageUptodate() is
1936 * not set, try to fill the page then wait for it to become unlocked.
1938 * If the page does not get brought uptodate, return -EIO.
1940 struct page *read_cache_page(struct address_space *mapping,
1941 pgoff_t index,
1942 int (*filler)(void *, struct page *),
1943 void *data)
1945 return wait_on_page_read(read_cache_page_async(mapping, index, filler, data));
1947 EXPORT_SYMBOL(read_cache_page);
1950 * The logic we want is
1952 * if suid or (sgid and xgrp)
1953 * remove privs
1955 int should_remove_suid(struct dentry *dentry)
1957 umode_t mode = dentry->d_inode->i_mode;
1958 int kill = 0;
1960 /* suid always must be killed */
1961 if (unlikely(mode & S_ISUID))
1962 kill = ATTR_KILL_SUID;
1965 * sgid without any exec bits is just a mandatory locking mark; leave
1966 * it alone. If some exec bits are set, it's a real sgid; kill it.
1968 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1969 kill |= ATTR_KILL_SGID;
1971 if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
1972 return kill;
1974 return 0;
1976 EXPORT_SYMBOL(should_remove_suid);
1978 static int __remove_suid(struct dentry *dentry, int kill)
1980 struct iattr newattrs;
1982 newattrs.ia_valid = ATTR_FORCE | kill;
1983 return notify_change(dentry, &newattrs);
1986 int file_remove_suid(struct file *file)
1988 struct dentry *dentry = file->f_path.dentry;
1989 struct inode *inode = dentry->d_inode;
1990 int killsuid;
1991 int killpriv;
1992 int error = 0;
1994 /* Fast path for nothing security related */
1995 if (IS_NOSEC(inode))
1996 return 0;
1998 killsuid = should_remove_suid(dentry);
1999 killpriv = security_inode_need_killpriv(dentry);
2001 if (killpriv < 0)
2002 return killpriv;
2003 if (killpriv)
2004 error = security_inode_killpriv(dentry);
2005 if (!error && killsuid)
2006 error = __remove_suid(dentry, killsuid);
2007 if (!error && (inode->i_sb->s_flags & MS_NOSEC))
2008 inode->i_flags |= S_NOSEC;
2010 return error;
2012 EXPORT_SYMBOL(file_remove_suid);
2014 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
2015 const struct iovec *iov, size_t base, size_t bytes)
2017 size_t copied = 0, left = 0;
2019 while (bytes) {
2020 char __user *buf = iov->iov_base + base;
2021 int copy = min(bytes, iov->iov_len - base);
2023 base = 0;
2024 left = __copy_from_user_inatomic(vaddr, buf, copy);
2025 copied += copy;
2026 bytes -= copy;
2027 vaddr += copy;
2028 iov++;
2030 if (unlikely(left))
2031 break;
2033 return copied - left;
2037 * Copy as much as we can into the page and return the number of bytes which
2038 * were successfully copied. If a fault is encountered then return the number of
2039 * bytes which were copied.
2041 size_t iov_iter_copy_from_user_atomic(struct page *page,
2042 struct iov_iter *i, unsigned long offset, size_t bytes)
2044 char *kaddr;
2045 size_t copied;
2047 BUG_ON(!in_atomic());
2048 kaddr = kmap_atomic(page, KM_USER0);
2049 if (likely(i->nr_segs == 1)) {
2050 int left;
2051 char __user *buf = i->iov->iov_base + i->iov_offset;
2052 left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
2053 copied = bytes - left;
2054 } else {
2055 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2056 i->iov, i->iov_offset, bytes);
2058 kunmap_atomic(kaddr, KM_USER0);
2060 return copied;
2062 EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
2065 * This has the same sideeffects and return value as
2066 * iov_iter_copy_from_user_atomic().
2067 * The difference is that it attempts to resolve faults.
2068 * Page must not be locked.
2070 size_t iov_iter_copy_from_user(struct page *page,
2071 struct iov_iter *i, unsigned long offset, size_t bytes)
2073 char *kaddr;
2074 size_t copied;
2076 kaddr = kmap(page);
2077 if (likely(i->nr_segs == 1)) {
2078 int left;
2079 char __user *buf = i->iov->iov_base + i->iov_offset;
2080 left = __copy_from_user(kaddr + offset, buf, bytes);
2081 copied = bytes - left;
2082 } else {
2083 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
2084 i->iov, i->iov_offset, bytes);
2086 kunmap(page);
2087 return copied;
2089 EXPORT_SYMBOL(iov_iter_copy_from_user);
2091 void iov_iter_advance(struct iov_iter *i, size_t bytes)
2093 BUG_ON(i->count < bytes);
2095 if (likely(i->nr_segs == 1)) {
2096 i->iov_offset += bytes;
2097 i->count -= bytes;
2098 } else {
2099 const struct iovec *iov = i->iov;
2100 size_t base = i->iov_offset;
2101 unsigned long nr_segs = i->nr_segs;
2104 * The !iov->iov_len check ensures we skip over unlikely
2105 * zero-length segments (without overruning the iovec).
2107 while (bytes || unlikely(i->count && !iov->iov_len)) {
2108 int copy;
2110 copy = min(bytes, iov->iov_len - base);
2111 BUG_ON(!i->count || i->count < copy);
2112 i->count -= copy;
2113 bytes -= copy;
2114 base += copy;
2115 if (iov->iov_len == base) {
2116 iov++;
2117 nr_segs--;
2118 base = 0;
2121 i->iov = iov;
2122 i->iov_offset = base;
2123 i->nr_segs = nr_segs;
2126 EXPORT_SYMBOL(iov_iter_advance);
2129 * Fault in the first iovec of the given iov_iter, to a maximum length
2130 * of bytes. Returns 0 on success, or non-zero if the memory could not be
2131 * accessed (ie. because it is an invalid address).
2133 * writev-intensive code may want this to prefault several iovecs -- that
2134 * would be possible (callers must not rely on the fact that _only_ the
2135 * first iovec will be faulted with the current implementation).
2137 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
2139 char __user *buf = i->iov->iov_base + i->iov_offset;
2140 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
2141 return fault_in_pages_readable(buf, bytes);
2143 EXPORT_SYMBOL(iov_iter_fault_in_readable);
2146 * Return the count of just the current iov_iter segment.
2148 size_t iov_iter_single_seg_count(struct iov_iter *i)
2150 const struct iovec *iov = i->iov;
2151 if (i->nr_segs == 1)
2152 return i->count;
2153 else
2154 return min(i->count, iov->iov_len - i->iov_offset);
2156 EXPORT_SYMBOL(iov_iter_single_seg_count);
2159 * Performs necessary checks before doing a write
2161 * Can adjust writing position or amount of bytes to write.
2162 * Returns appropriate error code that caller should return or
2163 * zero in case that write should be allowed.
2165 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
2167 struct inode *inode = file->f_mapping->host;
2168 unsigned long limit = rlimit(RLIMIT_FSIZE);
2170 if (unlikely(*pos < 0))
2171 return -EINVAL;
2173 if (!isblk) {
2174 /* FIXME: this is for backwards compatibility with 2.4 */
2175 if (file->f_flags & O_APPEND)
2176 *pos = i_size_read(inode);
2178 if (limit != RLIM_INFINITY) {
2179 if (*pos >= limit) {
2180 send_sig(SIGXFSZ, current, 0);
2181 return -EFBIG;
2183 if (*count > limit - (typeof(limit))*pos) {
2184 *count = limit - (typeof(limit))*pos;
2190 * LFS rule
2192 if (unlikely(*pos + *count > MAX_NON_LFS &&
2193 !(file->f_flags & O_LARGEFILE))) {
2194 if (*pos >= MAX_NON_LFS) {
2195 return -EFBIG;
2197 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
2198 *count = MAX_NON_LFS - (unsigned long)*pos;
2203 * Are we about to exceed the fs block limit ?
2205 * If we have written data it becomes a short write. If we have
2206 * exceeded without writing data we send a signal and return EFBIG.
2207 * Linus frestrict idea will clean these up nicely..
2209 if (likely(!isblk)) {
2210 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
2211 if (*count || *pos > inode->i_sb->s_maxbytes) {
2212 return -EFBIG;
2214 /* zero-length writes at ->s_maxbytes are OK */
2217 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
2218 *count = inode->i_sb->s_maxbytes - *pos;
2219 } else {
2220 #ifdef CONFIG_BLOCK
2221 loff_t isize;
2222 if (bdev_read_only(I_BDEV(inode)))
2223 return -EPERM;
2224 isize = i_size_read(inode);
2225 if (*pos >= isize) {
2226 if (*count || *pos > isize)
2227 return -ENOSPC;
2230 if (*pos + *count > isize)
2231 *count = isize - *pos;
2232 #else
2233 return -EPERM;
2234 #endif
2236 return 0;
2238 EXPORT_SYMBOL(generic_write_checks);
2240 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2241 loff_t pos, unsigned len, unsigned flags,
2242 struct page **pagep, void **fsdata)
2244 const struct address_space_operations *aops = mapping->a_ops;
2246 return aops->write_begin(file, mapping, pos, len, flags,
2247 pagep, fsdata);
2249 EXPORT_SYMBOL(pagecache_write_begin);
2251 int pagecache_write_end(struct file *file, struct address_space *mapping,
2252 loff_t pos, unsigned len, unsigned copied,
2253 struct page *page, void *fsdata)
2255 const struct address_space_operations *aops = mapping->a_ops;
2257 mark_page_accessed(page);
2258 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2260 EXPORT_SYMBOL(pagecache_write_end);
2262 ssize_t
2263 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
2264 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
2265 size_t count, size_t ocount)
2267 struct file *file = iocb->ki_filp;
2268 struct address_space *mapping = file->f_mapping;
2269 struct inode *inode = mapping->host;
2270 ssize_t written;
2271 size_t write_len;
2272 pgoff_t end;
2274 if (count != ocount)
2275 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
2277 write_len = iov_length(iov, *nr_segs);
2278 end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
2280 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2281 if (written)
2282 goto out;
2285 * After a write we want buffered reads to be sure to go to disk to get
2286 * the new data. We invalidate clean cached page from the region we're
2287 * about to write. We do this *before* the write so that we can return
2288 * without clobbering -EIOCBQUEUED from ->direct_IO().
2290 if (mapping->nrpages) {
2291 written = invalidate_inode_pages2_range(mapping,
2292 pos >> PAGE_CACHE_SHIFT, end);
2294 * If a page can not be invalidated, return 0 to fall back
2295 * to buffered write.
2297 if (written) {
2298 if (written == -EBUSY)
2299 return 0;
2300 goto out;
2304 written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
2307 * Finally, try again to invalidate clean pages which might have been
2308 * cached by non-direct readahead, or faulted in by get_user_pages()
2309 * if the source of the write was an mmap'ed region of the file
2310 * we're writing. Either one is a pretty crazy thing to do,
2311 * so we don't support it 100%. If this invalidation
2312 * fails, tough, the write still worked...
2314 if (mapping->nrpages) {
2315 invalidate_inode_pages2_range(mapping,
2316 pos >> PAGE_CACHE_SHIFT, end);
2319 if (written > 0) {
2320 pos += written;
2321 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2322 i_size_write(inode, pos);
2323 mark_inode_dirty(inode);
2325 *ppos = pos;
2327 out:
2328 return written;
2330 EXPORT_SYMBOL(generic_file_direct_write);
2333 * Find or create a page at the given pagecache position. Return the locked
2334 * page. This function is specifically for buffered writes.
2336 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2337 pgoff_t index, unsigned flags)
2339 int status;
2340 gfp_t gfp_mask;
2341 struct page *page;
2342 gfp_t gfp_notmask = 0;
2344 gfp_mask = mapping_gfp_mask(mapping) | __GFP_WRITE;
2345 if (flags & AOP_FLAG_NOFS)
2346 gfp_notmask = __GFP_FS;
2347 repeat:
2348 page = find_lock_page(mapping, index);
2349 if (page)
2350 goto found;
2352 page = __page_cache_alloc(gfp_mask & ~gfp_notmask);
2353 if (!page)
2354 return NULL;
2355 status = add_to_page_cache_lru(page, mapping, index,
2356 GFP_KERNEL & ~gfp_notmask);
2357 if (unlikely(status)) {
2358 page_cache_release(page);
2359 if (status == -EEXIST)
2360 goto repeat;
2361 return NULL;
2363 found:
2364 wait_on_page_writeback(page);
2365 return page;
2367 EXPORT_SYMBOL(grab_cache_page_write_begin);
2369 static ssize_t generic_perform_write(struct file *file,
2370 struct iov_iter *i, loff_t pos)
2372 struct address_space *mapping = file->f_mapping;
2373 const struct address_space_operations *a_ops = mapping->a_ops;
2374 long status = 0;
2375 ssize_t written = 0;
2376 unsigned int flags = 0;
2379 * Copies from kernel address space cannot fail (NFSD is a big user).
2381 if (segment_eq(get_fs(), KERNEL_DS))
2382 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2384 do {
2385 struct page *page;
2386 unsigned long offset; /* Offset into pagecache page */
2387 unsigned long bytes; /* Bytes to write to page */
2388 size_t copied; /* Bytes copied from user */
2389 void *fsdata;
2391 offset = (pos & (PAGE_CACHE_SIZE - 1));
2392 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2393 iov_iter_count(i));
2395 again:
2397 * Bring in the user page that we will copy from _first_.
2398 * Otherwise there's a nasty deadlock on copying from the
2399 * same page as we're writing to, without it being marked
2400 * up-to-date.
2402 * Not only is this an optimisation, but it is also required
2403 * to check that the address is actually valid, when atomic
2404 * usercopies are used, below.
2406 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2407 status = -EFAULT;
2408 break;
2411 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2412 &page, &fsdata);
2413 if (unlikely(status))
2414 break;
2416 if (mapping_writably_mapped(mapping))
2417 flush_dcache_page(page);
2419 pagefault_disable();
2420 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2421 pagefault_enable();
2422 flush_dcache_page(page);
2424 mark_page_accessed(page);
2425 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2426 page, fsdata);
2427 if (unlikely(status < 0))
2428 break;
2429 copied = status;
2431 cond_resched();
2433 iov_iter_advance(i, copied);
2434 if (unlikely(copied == 0)) {
2436 * If we were unable to copy any data at all, we must
2437 * fall back to a single segment length write.
2439 * If we didn't fallback here, we could livelock
2440 * because not all segments in the iov can be copied at
2441 * once without a pagefault.
2443 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2444 iov_iter_single_seg_count(i));
2445 goto again;
2447 pos += copied;
2448 written += copied;
2450 balance_dirty_pages_ratelimited(mapping);
2451 if (fatal_signal_pending(current)) {
2452 status = -EINTR;
2453 break;
2455 } while (iov_iter_count(i));
2457 return written ? written : status;
2460 ssize_t
2461 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2462 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2463 size_t count, ssize_t written)
2465 struct file *file = iocb->ki_filp;
2466 ssize_t status;
2467 struct iov_iter i;
2469 iov_iter_init(&i, iov, nr_segs, count, written);
2470 status = generic_perform_write(file, &i, pos);
2472 if (likely(status >= 0)) {
2473 written += status;
2474 *ppos = pos + status;
2477 return written ? written : status;
2479 EXPORT_SYMBOL(generic_file_buffered_write);
2482 * __generic_file_aio_write - write data to a file
2483 * @iocb: IO state structure (file, offset, etc.)
2484 * @iov: vector with data to write
2485 * @nr_segs: number of segments in the vector
2486 * @ppos: position where to write
2488 * This function does all the work needed for actually writing data to a
2489 * file. It does all basic checks, removes SUID from the file, updates
2490 * modification times and calls proper subroutines depending on whether we
2491 * do direct IO or a standard buffered write.
2493 * It expects i_mutex to be grabbed unless we work on a block device or similar
2494 * object which does not need locking at all.
2496 * This function does *not* take care of syncing data in case of O_SYNC write.
2497 * A caller has to handle it. This is mainly due to the fact that we want to
2498 * avoid syncing under i_mutex.
2500 ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2501 unsigned long nr_segs, loff_t *ppos)
2503 struct file *file = iocb->ki_filp;
2504 struct address_space * mapping = file->f_mapping;
2505 size_t ocount; /* original count */
2506 size_t count; /* after file limit checks */
2507 struct inode *inode = mapping->host;
2508 loff_t pos;
2509 ssize_t written;
2510 ssize_t err;
2512 ocount = 0;
2513 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2514 if (err)
2515 return err;
2517 count = ocount;
2518 pos = *ppos;
2520 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2522 /* We can write back this queue in page reclaim */
2523 current->backing_dev_info = mapping->backing_dev_info;
2524 written = 0;
2526 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2527 if (err)
2528 goto out;
2530 if (count == 0)
2531 goto out;
2533 err = file_remove_suid(file);
2534 if (err)
2535 goto out;
2537 file_update_time(file);
2539 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2540 if (unlikely(file->f_flags & O_DIRECT)) {
2541 loff_t endbyte;
2542 ssize_t written_buffered;
2544 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2545 ppos, count, ocount);
2546 if (written < 0 || written == count)
2547 goto out;
2549 * direct-io write to a hole: fall through to buffered I/O
2550 * for completing the rest of the request.
2552 pos += written;
2553 count -= written;
2554 written_buffered = generic_file_buffered_write(iocb, iov,
2555 nr_segs, pos, ppos, count,
2556 written);
2558 * If generic_file_buffered_write() retuned a synchronous error
2559 * then we want to return the number of bytes which were
2560 * direct-written, or the error code if that was zero. Note
2561 * that this differs from normal direct-io semantics, which
2562 * will return -EFOO even if some bytes were written.
2564 if (written_buffered < 0) {
2565 err = written_buffered;
2566 goto out;
2570 * We need to ensure that the page cache pages are written to
2571 * disk and invalidated to preserve the expected O_DIRECT
2572 * semantics.
2574 endbyte = pos + written_buffered - written - 1;
2575 err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
2576 if (err == 0) {
2577 written = written_buffered;
2578 invalidate_mapping_pages(mapping,
2579 pos >> PAGE_CACHE_SHIFT,
2580 endbyte >> PAGE_CACHE_SHIFT);
2581 } else {
2583 * We don't know how much we wrote, so just return
2584 * the number of bytes which were direct-written
2587 } else {
2588 written = generic_file_buffered_write(iocb, iov, nr_segs,
2589 pos, ppos, count, written);
2591 out:
2592 current->backing_dev_info = NULL;
2593 return written ? written : err;
2595 EXPORT_SYMBOL(__generic_file_aio_write);
2598 * generic_file_aio_write - write data to a file
2599 * @iocb: IO state structure
2600 * @iov: vector with data to write
2601 * @nr_segs: number of segments in the vector
2602 * @pos: position in file where to write
2604 * This is a wrapper around __generic_file_aio_write() to be used by most
2605 * filesystems. It takes care of syncing the file in case of O_SYNC file
2606 * and acquires i_mutex as needed.
2608 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2609 unsigned long nr_segs, loff_t pos)
2611 struct file *file = iocb->ki_filp;
2612 struct inode *inode = file->f_mapping->host;
2613 struct blk_plug plug;
2614 ssize_t ret;
2616 BUG_ON(iocb->ki_pos != pos);
2618 mutex_lock(&inode->i_mutex);
2619 blk_start_plug(&plug);
2620 ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
2621 mutex_unlock(&inode->i_mutex);
2623 if (ret > 0 || ret == -EIOCBQUEUED) {
2624 ssize_t err;
2626 err = generic_write_sync(file, pos, ret);
2627 if (err < 0 && ret > 0)
2628 ret = err;
2630 blk_finish_plug(&plug);
2631 return ret;
2633 EXPORT_SYMBOL(generic_file_aio_write);
2636 * try_to_release_page() - release old fs-specific metadata on a page
2638 * @page: the page which the kernel is trying to free
2639 * @gfp_mask: memory allocation flags (and I/O mode)
2641 * The address_space is to try to release any data against the page
2642 * (presumably at page->private). If the release was successful, return `1'.
2643 * Otherwise return zero.
2645 * This may also be called if PG_fscache is set on a page, indicating that the
2646 * page is known to the local caching routines.
2648 * The @gfp_mask argument specifies whether I/O may be performed to release
2649 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
2652 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2654 struct address_space * const mapping = page->mapping;
2656 BUG_ON(!PageLocked(page));
2657 if (PageWriteback(page))
2658 return 0;
2660 if (mapping && mapping->a_ops->releasepage)
2661 return mapping->a_ops->releasepage(page, gfp_mask);
2662 return try_to_free_buffers(page);
2665 EXPORT_SYMBOL(try_to_release_page);