MOXA linux-2.6.x / linux-2.6.9-uc0 from sdlinux-moxaart.tgz
[linux-2.6.9-moxart.git] / mm / filemap.c
blob272c3e0a6fed2b8cf934aad6a2dabd7c5ce71daa
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/config.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <linux/compiler.h>
16 #include <linux/fs.h>
17 #include <linux/aio.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/mman.h>
22 #include <linux/pagemap.h>
23 #include <linux/file.h>
24 #include <linux/uio.h>
25 #include <linux/hash.h>
26 #include <linux/writeback.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/security.h>
31 * This is needed for the following functions:
32 * - try_to_release_page
33 * - block_invalidatepage
34 * - generic_osync_inode
36 * FIXME: remove all knowledge of the buffer layer from the core VM
38 #include <linux/buffer_head.h> /* for generic_osync_inode */
40 #include <asm/uaccess.h>
41 #include <asm/mman.h>
44 * Shared mappings implemented 30.11.1994. It's not fully working yet,
45 * though.
47 * Shared mappings now work. 15.8.1995 Bruno.
49 * finished 'unifying' the page and buffer cache and SMP-threaded the
50 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
52 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
56 * Lock ordering:
58 * ->i_mmap_lock (vmtruncate)
59 * ->private_lock (__free_pte->__set_page_dirty_buffers)
60 * ->swap_list_lock
61 * ->swap_device_lock (exclusive_swap_page, others)
62 * ->mapping->tree_lock
64 * ->i_sem
65 * ->i_mmap_lock (truncate->unmap_mapping_range)
67 * ->mmap_sem
68 * ->i_mmap_lock
69 * ->page_table_lock (various places, mainly in mmap.c)
70 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
72 * ->mmap_sem
73 * ->lock_page (access_process_vm)
75 * ->mmap_sem
76 * ->i_sem (msync)
78 * ->i_sem
79 * ->i_alloc_sem (various)
81 * ->inode_lock
82 * ->sb_lock (fs/fs-writeback.c)
83 * ->mapping->tree_lock (__sync_single_inode)
85 * ->i_mmap_lock
86 * ->anon_vma.lock (vma_adjust)
88 * ->anon_vma.lock
89 * ->page_table_lock (anon_vma_prepare and various)
91 * ->page_table_lock
92 * ->swap_device_lock (try_to_unmap_one)
93 * ->private_lock (try_to_unmap_one)
94 * ->tree_lock (try_to_unmap_one)
95 * ->zone.lru_lock (follow_page->mark_page_accessed)
96 * ->private_lock (page_remove_rmap->set_page_dirty)
97 * ->tree_lock (page_remove_rmap->set_page_dirty)
98 * ->inode_lock (page_remove_rmap->set_page_dirty)
99 * ->inode_lock (zap_pte_range->set_page_dirty)
100 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
102 * ->task->proc_lock
103 * ->dcache_lock (proc_pid_lookup)
107 * Remove a page from the page cache and free it. Caller has to make
108 * sure the page is locked and that nobody else uses it - or that usage
109 * is safe. The caller must hold a write_lock on the mapping's tree_lock.
111 void __remove_from_page_cache(struct page *page)
113 struct address_space *mapping = page->mapping;
115 radix_tree_delete(&mapping->page_tree, page->index);
116 page->mapping = NULL;
117 mapping->nrpages--;
118 pagecache_acct(-1);
121 void remove_from_page_cache(struct page *page)
123 struct address_space *mapping = page->mapping;
125 if (unlikely(!PageLocked(page)))
126 PAGE_BUG(page);
128 spin_lock_irq(&mapping->tree_lock);
129 __remove_from_page_cache(page);
130 spin_unlock_irq(&mapping->tree_lock);
133 static inline int sync_page(struct page *page)
135 struct address_space *mapping;
138 * FIXME, fercrissake. What is this barrier here for?
140 smp_mb();
141 mapping = page_mapping(page);
142 if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
143 return mapping->a_ops->sync_page(page);
144 return 0;
148 * filemap_fdatawrite_range - start writeback against all of a mapping's
149 * dirty pages that lie within the byte offsets <start, end>
150 * @mapping: address space structure to write
151 * @start: offset in bytes where the range starts
152 * @end : offset in bytes where the range ends
154 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
155 * opposed to a regular memory * cleansing writeback. The difference between
156 * these two operations is that if a dirty page/buffer is encountered, it must
157 * be waited upon, and not just skipped over.
159 static int __filemap_fdatawrite_range(struct address_space *mapping,
160 loff_t start, loff_t end, int sync_mode)
162 int ret;
163 struct writeback_control wbc = {
164 .sync_mode = sync_mode,
165 .nr_to_write = mapping->nrpages * 2,
166 .start = start,
167 .end = end,
170 if (mapping->backing_dev_info->memory_backed)
171 return 0;
173 ret = do_writepages(mapping, &wbc);
174 return ret;
177 static inline int __filemap_fdatawrite(struct address_space *mapping,
178 int sync_mode)
180 return __filemap_fdatawrite_range(mapping, 0, 0, sync_mode);
183 int filemap_fdatawrite(struct address_space *mapping)
185 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
187 EXPORT_SYMBOL(filemap_fdatawrite);
189 int filemap_fdatawrite_range(struct address_space *mapping,
190 loff_t start, loff_t end)
192 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
194 EXPORT_SYMBOL(filemap_fdatawrite_range);
197 * This is a mostly non-blocking flush. Not suitable for data-integrity
198 * purposes - I/O may not be started against all dirty pages.
200 int filemap_flush(struct address_space *mapping)
202 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
204 EXPORT_SYMBOL(filemap_flush);
207 * Wait for writeback to complete against pages indexed by start->end
208 * inclusive
210 static int wait_on_page_writeback_range(struct address_space *mapping,
211 pgoff_t start, pgoff_t end)
213 struct pagevec pvec;
214 int nr_pages;
215 int ret = 0;
216 pgoff_t index;
218 if (end < start)
219 return 0;
221 pagevec_init(&pvec, 0);
222 index = start;
223 while ((index <= end) &&
224 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
225 PAGECACHE_TAG_WRITEBACK,
226 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
227 unsigned i;
229 for (i = 0; i < nr_pages; i++) {
230 struct page *page = pvec.pages[i];
232 /* until radix tree lookup accepts end_index */
233 if (page->index > end)
234 continue;
236 wait_on_page_writeback(page);
237 if (PageError(page))
238 ret = -EIO;
240 pagevec_release(&pvec);
241 cond_resched();
244 /* Check for outstanding write errors */
245 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
246 ret = -ENOSPC;
247 if (test_and_clear_bit(AS_EIO, &mapping->flags))
248 ret = -EIO;
250 return ret;
254 * Write and wait upon all the pages in the passed range. This is a "data
255 * integrity" operation. It waits upon in-flight writeout before starting and
256 * waiting upon new writeout. If there was an IO error, return it.
258 * We need to re-take i_sem during the generic_osync_inode list walk because
259 * it is otherwise livelockable.
261 int sync_page_range(struct inode *inode, struct address_space *mapping,
262 loff_t pos, size_t count)
264 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
265 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
266 int ret;
268 if (mapping->backing_dev_info->memory_backed || !count)
269 return 0;
270 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
271 if (ret == 0) {
272 down(&inode->i_sem);
273 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
274 up(&inode->i_sem);
276 if (ret == 0)
277 ret = wait_on_page_writeback_range(mapping, start, end);
278 return ret;
280 EXPORT_SYMBOL(sync_page_range);
283 * filemap_fdatawait - walk the list of under-writeback pages of the given
284 * address space and wait for all of them.
286 * @mapping: address space structure to wait for
288 int filemap_fdatawait(struct address_space *mapping)
290 loff_t i_size = i_size_read(mapping->host);
292 if (i_size == 0)
293 return 0;
295 return wait_on_page_writeback_range(mapping, 0,
296 (i_size - 1) >> PAGE_CACHE_SHIFT);
298 EXPORT_SYMBOL(filemap_fdatawait);
300 int filemap_write_and_wait(struct address_space *mapping)
302 int retval = 0;
304 if (mapping->nrpages) {
305 retval = filemap_fdatawrite(mapping);
306 if (retval == 0)
307 retval = filemap_fdatawait(mapping);
309 return retval;
313 * This function is used to add newly allocated pagecache pages:
314 * the page is new, so we can just run SetPageLocked() against it.
315 * The other page state flags were set by rmqueue().
317 * This function does not add the page to the LRU. The caller must do that.
319 int add_to_page_cache(struct page *page, struct address_space *mapping,
320 pgoff_t offset, int gfp_mask)
322 int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
324 if (error == 0) {
325 spin_lock_irq(&mapping->tree_lock);
326 error = radix_tree_insert(&mapping->page_tree, offset, page);
327 if (!error) {
328 page_cache_get(page);
329 SetPageLocked(page);
330 page->mapping = mapping;
331 page->index = offset;
332 mapping->nrpages++;
333 pagecache_acct(1);
335 spin_unlock_irq(&mapping->tree_lock);
336 radix_tree_preload_end();
338 return error;
341 EXPORT_SYMBOL(add_to_page_cache);
343 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
344 pgoff_t offset, int gfp_mask)
346 int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
347 if (ret == 0)
348 lru_cache_add(page);
349 return ret;
353 * In order to wait for pages to become available there must be
354 * waitqueues associated with pages. By using a hash table of
355 * waitqueues where the bucket discipline is to maintain all
356 * waiters on the same queue and wake all when any of the pages
357 * become available, and for the woken contexts to check to be
358 * sure the appropriate page became available, this saves space
359 * at a cost of "thundering herd" phenomena during rare hash
360 * collisions.
362 struct page_wait_queue {
363 struct page *page;
364 int bit;
365 wait_queue_t wait;
368 static int page_wake_function(wait_queue_t *wait, unsigned mode, int sync, void *key)
370 struct page *page = key;
371 struct page_wait_queue *wq;
373 wq = container_of(wait, struct page_wait_queue, wait);
374 if (wq->page != page || test_bit(wq->bit, &page->flags))
375 return 0;
376 else
377 return autoremove_wake_function(wait, mode, sync, NULL);
380 #define __DEFINE_PAGE_WAIT(name, p, b, f) \
381 struct page_wait_queue name = { \
382 .page = p, \
383 .bit = b, \
384 .wait = { \
385 .task = current, \
386 .func = page_wake_function, \
387 .flags = f, \
388 .task_list = LIST_HEAD_INIT(name.wait.task_list),\
389 }, \
392 #define DEFINE_PAGE_WAIT(name, p, b) __DEFINE_PAGE_WAIT(name, p, b, 0)
393 #define DEFINE_PAGE_WAIT_EXCLUSIVE(name, p, b) \
394 __DEFINE_PAGE_WAIT(name, p, b, WQ_FLAG_EXCLUSIVE)
396 static wait_queue_head_t *page_waitqueue(struct page *page)
398 const struct zone *zone = page_zone(page);
400 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
403 static void wake_up_page(struct page *page)
405 const unsigned int mode = TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE;
406 wait_queue_head_t *waitqueue = page_waitqueue(page);
408 if (waitqueue_active(waitqueue))
409 __wake_up(waitqueue, mode, 1, page);
412 void fastcall wait_on_page_bit(struct page *page, int bit_nr)
414 wait_queue_head_t *waitqueue = page_waitqueue(page);
415 DEFINE_PAGE_WAIT(wait, page, bit_nr);
417 do {
418 prepare_to_wait(waitqueue, &wait.wait, TASK_UNINTERRUPTIBLE);
419 if (test_bit(bit_nr, &page->flags)) {
420 sync_page(page);
421 io_schedule();
423 } while (test_bit(bit_nr, &page->flags));
424 finish_wait(waitqueue, &wait.wait);
427 EXPORT_SYMBOL(wait_on_page_bit);
430 * unlock_page() - unlock a locked page
432 * @page: the page
434 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
435 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
436 * mechananism between PageLocked pages and PageWriteback pages is shared.
437 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
439 * The first mb is necessary to safely close the critical section opened by the
440 * TestSetPageLocked(), the second mb is necessary to enforce ordering between
441 * the clear_bit and the read of the waitqueue (to avoid SMP races with a
442 * parallel wait_on_page_locked()).
444 void fastcall unlock_page(struct page *page)
446 smp_mb__before_clear_bit();
447 if (!TestClearPageLocked(page))
448 BUG();
449 smp_mb__after_clear_bit();
450 wake_up_page(page);
453 EXPORT_SYMBOL(unlock_page);
454 EXPORT_SYMBOL(lock_page);
457 * End writeback against a page.
459 void end_page_writeback(struct page *page)
461 if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
462 if (!test_clear_page_writeback(page))
463 BUG();
464 smp_mb__after_clear_bit();
466 wake_up_page(page);
469 EXPORT_SYMBOL(end_page_writeback);
472 * Get a lock on the page, assuming we need to sleep to get it.
474 * Ugly: running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
475 * random driver's requestfn sets TASK_RUNNING, we could busywait. However
476 * chances are that on the second loop, the block layer's plug list is empty,
477 * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
479 void fastcall __lock_page(struct page *page)
481 wait_queue_head_t *wqh = page_waitqueue(page);
482 DEFINE_PAGE_WAIT_EXCLUSIVE(wait, page, PG_locked);
484 while (TestSetPageLocked(page)) {
485 prepare_to_wait_exclusive(wqh, &wait.wait, TASK_UNINTERRUPTIBLE);
486 if (PageLocked(page)) {
487 sync_page(page);
488 io_schedule();
491 finish_wait(wqh, &wait.wait);
494 EXPORT_SYMBOL(__lock_page);
497 * a rather lightweight function, finding and getting a reference to a
498 * hashed page atomically.
500 struct page * find_get_page(struct address_space *mapping, unsigned long offset)
502 struct page *page;
504 spin_lock_irq(&mapping->tree_lock);
505 page = radix_tree_lookup(&mapping->page_tree, offset);
506 if (page)
507 page_cache_get(page);
508 spin_unlock_irq(&mapping->tree_lock);
509 return page;
512 EXPORT_SYMBOL(find_get_page);
515 * Same as above, but trylock it instead of incrementing the count.
517 struct page *find_trylock_page(struct address_space *mapping, unsigned long offset)
519 struct page *page;
521 spin_lock_irq(&mapping->tree_lock);
522 page = radix_tree_lookup(&mapping->page_tree, offset);
523 if (page && TestSetPageLocked(page))
524 page = NULL;
525 spin_unlock_irq(&mapping->tree_lock);
526 return page;
529 EXPORT_SYMBOL(find_trylock_page);
532 * find_lock_page - locate, pin and lock a pagecache page
534 * @mapping - the address_space to search
535 * @offset - the page index
537 * Locates the desired pagecache page, locks it, increments its reference
538 * count and returns its address.
540 * Returns zero if the page was not present. find_lock_page() may sleep.
542 struct page *find_lock_page(struct address_space *mapping,
543 unsigned long offset)
545 struct page *page;
547 spin_lock_irq(&mapping->tree_lock);
548 repeat:
549 page = radix_tree_lookup(&mapping->page_tree, offset);
550 if (page) {
551 page_cache_get(page);
552 if (TestSetPageLocked(page)) {
553 spin_unlock_irq(&mapping->tree_lock);
554 lock_page(page);
555 spin_lock_irq(&mapping->tree_lock);
557 /* Has the page been truncated while we slept? */
558 if (page->mapping != mapping || page->index != offset) {
559 unlock_page(page);
560 page_cache_release(page);
561 goto repeat;
565 spin_unlock_irq(&mapping->tree_lock);
566 return page;
569 EXPORT_SYMBOL(find_lock_page);
572 * find_or_create_page - locate or add a pagecache page
574 * @mapping - the page's address_space
575 * @index - the page's index into the mapping
576 * @gfp_mask - page allocation mode
578 * Locates a page in the pagecache. If the page is not present, a new page
579 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
580 * LRU list. The returned page is locked and has its reference count
581 * incremented.
583 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
584 * allocation!
586 * find_or_create_page() returns the desired page's address, or zero on
587 * memory exhaustion.
589 struct page *find_or_create_page(struct address_space *mapping,
590 unsigned long index, unsigned int gfp_mask)
592 struct page *page, *cached_page = NULL;
593 int err;
594 repeat:
595 page = find_lock_page(mapping, index);
596 if (!page) {
597 if (!cached_page) {
598 cached_page = alloc_page(gfp_mask);
599 if (!cached_page)
600 return NULL;
602 err = add_to_page_cache_lru(cached_page, mapping,
603 index, gfp_mask);
604 if (!err) {
605 page = cached_page;
606 cached_page = NULL;
607 } else if (err == -EEXIST)
608 goto repeat;
610 if (cached_page)
611 page_cache_release(cached_page);
612 return page;
615 EXPORT_SYMBOL(find_or_create_page);
618 * find_get_pages - gang pagecache lookup
619 * @mapping: The address_space to search
620 * @start: The starting page index
621 * @nr_pages: The maximum number of pages
622 * @pages: Where the resulting pages are placed
624 * find_get_pages() will search for and return a group of up to
625 * @nr_pages pages in the mapping. The pages are placed at @pages.
626 * find_get_pages() takes a reference against the returned pages.
628 * The search returns a group of mapping-contiguous pages with ascending
629 * indexes. There may be holes in the indices due to not-present pages.
631 * find_get_pages() returns the number of pages which were found.
633 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
634 unsigned int nr_pages, struct page **pages)
636 unsigned int i;
637 unsigned int ret;
639 spin_lock_irq(&mapping->tree_lock);
640 ret = radix_tree_gang_lookup(&mapping->page_tree,
641 (void **)pages, start, nr_pages);
642 for (i = 0; i < ret; i++)
643 page_cache_get(pages[i]);
644 spin_unlock_irq(&mapping->tree_lock);
645 return ret;
649 * Like find_get_pages, except we only return pages which are tagged with
650 * `tag'. We update *index to index the next page for the traversal.
652 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
653 int tag, unsigned int nr_pages, struct page **pages)
655 unsigned int i;
656 unsigned int ret;
658 spin_lock_irq(&mapping->tree_lock);
659 ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
660 (void **)pages, *index, nr_pages, tag);
661 for (i = 0; i < ret; i++)
662 page_cache_get(pages[i]);
663 if (ret)
664 *index = pages[ret - 1]->index + 1;
665 spin_unlock_irq(&mapping->tree_lock);
666 return ret;
670 * Same as grab_cache_page, but do not wait if the page is unavailable.
671 * This is intended for speculative data generators, where the data can
672 * be regenerated if the page couldn't be grabbed. This routine should
673 * be safe to call while holding the lock for another page.
675 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
676 * and deadlock against the caller's locked page.
678 struct page *
679 grab_cache_page_nowait(struct address_space *mapping, unsigned long index)
681 struct page *page = find_get_page(mapping, index);
682 int gfp_mask;
684 if (page) {
685 if (!TestSetPageLocked(page))
686 return page;
687 page_cache_release(page);
688 return NULL;
690 gfp_mask = mapping_gfp_mask(mapping) & ~__GFP_FS;
691 page = alloc_pages(gfp_mask, 0);
692 if (page && add_to_page_cache_lru(page, mapping, index, gfp_mask)) {
693 page_cache_release(page);
694 page = NULL;
696 return page;
699 EXPORT_SYMBOL(grab_cache_page_nowait);
702 * This is a generic file read routine, and uses the
703 * mapping->a_ops->readpage() function for the actual low-level
704 * stuff.
706 * This is really ugly. But the goto's actually try to clarify some
707 * of the logic when it comes to error handling etc.
709 * Note the struct file* is only passed for the use of readpage. It may be
710 * NULL.
712 void do_generic_mapping_read(struct address_space *mapping,
713 struct file_ra_state *_ra,
714 struct file *filp,
715 loff_t *ppos,
716 read_descriptor_t *desc,
717 read_actor_t actor)
719 struct inode *inode = mapping->host;
720 unsigned long index, end_index, offset;
721 loff_t isize;
722 struct page *cached_page;
723 int error;
724 struct file_ra_state ra = *_ra;
726 cached_page = NULL;
727 index = *ppos >> PAGE_CACHE_SHIFT;
728 offset = *ppos & ~PAGE_CACHE_MASK;
730 isize = i_size_read(inode);
731 if (!isize)
732 goto out;
734 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
735 for (;;) {
736 struct page *page;
737 unsigned long nr, ret;
739 /* nr is the maximum number of bytes to copy from this page */
740 nr = PAGE_CACHE_SIZE;
741 if (index >= end_index) {
742 if (index > end_index)
743 goto out;
744 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
745 if (nr <= offset) {
746 goto out;
749 nr = nr - offset;
751 cond_resched();
752 page_cache_readahead(mapping, &ra, filp, index);
754 find_page:
755 page = find_get_page(mapping, index);
756 if (unlikely(page == NULL)) {
757 handle_ra_miss(mapping, &ra, index);
758 goto no_cached_page;
760 if (!PageUptodate(page))
761 goto page_not_up_to_date;
762 page_ok:
764 /* If users can be writing to this page using arbitrary
765 * virtual addresses, take care about potential aliasing
766 * before reading the page on the kernel side.
768 if (mapping_writably_mapped(mapping))
769 flush_dcache_page(page);
772 * Mark the page accessed if we read the beginning.
774 if (!offset)
775 mark_page_accessed(page);
778 * Ok, we have the page, and it's up-to-date, so
779 * now we can copy it to user space...
781 * The actor routine returns how many bytes were actually used..
782 * NOTE! This may not be the same as how much of a user buffer
783 * we filled up (we may be padding etc), so we can only update
784 * "pos" here (the actor routine has to update the user buffer
785 * pointers and the remaining count).
787 ret = actor(desc, page, offset, nr);
788 offset += ret;
789 index += offset >> PAGE_CACHE_SHIFT;
790 offset &= ~PAGE_CACHE_MASK;
792 page_cache_release(page);
793 if (ret == nr && desc->count)
794 continue;
795 goto out;
797 page_not_up_to_date:
798 /* Get exclusive access to the page ... */
799 lock_page(page);
801 /* Did it get unhashed before we got the lock? */
802 if (!page->mapping) {
803 unlock_page(page);
804 page_cache_release(page);
805 continue;
808 /* Did somebody else fill it already? */
809 if (PageUptodate(page)) {
810 unlock_page(page);
811 goto page_ok;
814 readpage:
815 /* Start the actual read. The read will unlock the page. */
816 error = mapping->a_ops->readpage(filp, page);
818 if (unlikely(error))
819 goto readpage_error;
821 if (!PageUptodate(page)) {
822 wait_on_page_locked(page);
823 if (!PageUptodate(page)) {
824 error = -EIO;
825 goto readpage_error;
830 * i_size must be checked after we have done ->readpage.
832 * Checking i_size after the readpage allows us to calculate
833 * the correct value for "nr", which means the zero-filled
834 * part of the page is not copied back to userspace (unless
835 * another truncate extends the file - this is desired though).
837 isize = i_size_read(inode);
838 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
839 if (unlikely(!isize || index > end_index)) {
840 page_cache_release(page);
841 goto out;
844 /* nr is the maximum number of bytes to copy from this page */
845 nr = PAGE_CACHE_SIZE;
846 if (index == end_index) {
847 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
848 if (nr <= offset) {
849 page_cache_release(page);
850 goto out;
853 nr = nr - offset;
854 goto page_ok;
856 readpage_error:
857 /* UHHUH! A synchronous read error occurred. Report it */
858 desc->error = error;
859 page_cache_release(page);
860 goto out;
862 no_cached_page:
864 * Ok, it wasn't cached, so we need to create a new
865 * page..
867 if (!cached_page) {
868 cached_page = page_cache_alloc_cold(mapping);
869 if (!cached_page) {
870 desc->error = -ENOMEM;
871 goto out;
874 error = add_to_page_cache_lru(cached_page, mapping,
875 index, GFP_KERNEL);
876 if (error) {
877 if (error == -EEXIST)
878 goto find_page;
879 desc->error = error;
880 goto out;
882 page = cached_page;
883 cached_page = NULL;
884 goto readpage;
887 out:
888 *_ra = ra;
890 *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
891 if (cached_page)
892 page_cache_release(cached_page);
893 if (filp)
894 file_accessed(filp);
897 EXPORT_SYMBOL(do_generic_mapping_read);
899 int file_read_actor(read_descriptor_t *desc, struct page *page,
900 unsigned long offset, unsigned long size)
902 char *kaddr;
903 unsigned long left, count = desc->count;
905 if (size > count)
906 size = count;
909 * Faults on the destination of a read are common, so do it before
910 * taking the kmap.
912 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
913 kaddr = kmap_atomic(page, KM_USER0);
914 left = __copy_to_user_inatomic(desc->arg.buf,
915 kaddr + offset, size);
916 kunmap_atomic(kaddr, KM_USER0);
917 if (left == 0)
918 goto success;
921 /* Do it the slow way */
922 kaddr = kmap(page);
923 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
924 kunmap(page);
926 if (left) {
927 size -= left;
928 desc->error = -EFAULT;
930 success:
931 desc->count = count - size;
932 desc->written += size;
933 desc->arg.buf += size;
934 return size;
938 * This is the "read()" routine for all filesystems
939 * that can use the page cache directly.
941 ssize_t
942 __generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
943 unsigned long nr_segs, loff_t *ppos)
945 struct file *filp = iocb->ki_filp;
946 ssize_t retval;
947 unsigned long seg;
948 size_t count;
950 count = 0;
951 for (seg = 0; seg < nr_segs; seg++) {
952 const struct iovec *iv = &iov[seg];
955 * If any segment has a negative length, or the cumulative
956 * length ever wraps negative then return -EINVAL.
958 count += iv->iov_len;
959 if (unlikely((ssize_t)(count|iv->iov_len) < 0))
960 return -EINVAL;
961 if (access_ok(VERIFY_WRITE, iv->iov_base, iv->iov_len))
962 continue;
963 if (seg == 0)
964 return -EFAULT;
965 nr_segs = seg;
966 count -= iv->iov_len; /* This segment is no good */
967 break;
970 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
971 if (filp->f_flags & O_DIRECT) {
972 loff_t pos = *ppos, size;
973 struct address_space *mapping;
974 struct inode *inode;
976 mapping = filp->f_mapping;
977 inode = mapping->host;
978 retval = 0;
979 if (!count)
980 goto out; /* skip atime */
981 size = i_size_read(inode);
982 if (pos < size) {
983 retval = generic_file_direct_IO(READ, iocb,
984 iov, pos, nr_segs);
985 if (retval >= 0 && !is_sync_kiocb(iocb))
986 retval = -EIOCBQUEUED;
987 if (retval > 0)
988 *ppos = pos + retval;
990 file_accessed(filp);
991 goto out;
994 retval = 0;
995 if (count) {
996 for (seg = 0; seg < nr_segs; seg++) {
997 read_descriptor_t desc;
999 desc.written = 0;
1000 desc.arg.buf = iov[seg].iov_base;
1001 desc.count = iov[seg].iov_len;
1002 if (desc.count == 0)
1003 continue;
1004 desc.error = 0;
1005 do_generic_file_read(filp,ppos,&desc,file_read_actor);
1006 retval += desc.written;
1007 if (!retval) {
1008 retval = desc.error;
1009 break;
1013 out:
1014 return retval;
1017 EXPORT_SYMBOL(__generic_file_aio_read);
1019 ssize_t
1020 generic_file_aio_read(struct kiocb *iocb, char __user *buf, size_t count, loff_t pos)
1022 struct iovec local_iov = { .iov_base = buf, .iov_len = count };
1024 BUG_ON(iocb->ki_pos != pos);
1025 return __generic_file_aio_read(iocb, &local_iov, 1, &iocb->ki_pos);
1028 EXPORT_SYMBOL(generic_file_aio_read);
1030 ssize_t
1031 generic_file_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
1033 struct iovec local_iov = { .iov_base = buf, .iov_len = count };
1034 struct kiocb kiocb;
1035 ssize_t ret;
1037 init_sync_kiocb(&kiocb, filp);
1038 ret = __generic_file_aio_read(&kiocb, &local_iov, 1, ppos);
1039 if (-EIOCBQUEUED == ret)
1040 ret = wait_on_sync_kiocb(&kiocb);
1041 return ret;
1044 EXPORT_SYMBOL(generic_file_read);
1046 int file_send_actor(read_descriptor_t * desc, struct page *page, unsigned long offset, unsigned long size)
1048 ssize_t written;
1049 unsigned long count = desc->count;
1050 struct file *file = desc->arg.data;
1052 if (size > count)
1053 size = count;
1055 written = file->f_op->sendpage(file, page, offset,
1056 size, &file->f_pos, size<count);
1057 if (written < 0) {
1058 desc->error = written;
1059 written = 0;
1061 desc->count = count - written;
1062 desc->written += written;
1063 return written;
1066 ssize_t generic_file_sendfile(struct file *in_file, loff_t *ppos,
1067 size_t count, read_actor_t actor, void *target)
1069 read_descriptor_t desc;
1071 if (!count)
1072 return 0;
1074 desc.written = 0;
1075 desc.count = count;
1076 desc.arg.data = target;
1077 desc.error = 0;
1079 do_generic_file_read(in_file, ppos, &desc, actor);
1080 if (desc.written)
1081 return desc.written;
1082 return desc.error;
1085 EXPORT_SYMBOL(generic_file_sendfile);
1087 static ssize_t
1088 do_readahead(struct address_space *mapping, struct file *filp,
1089 unsigned long index, unsigned long nr)
1091 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1092 return -EINVAL;
1094 force_page_cache_readahead(mapping, filp, index,
1095 max_sane_readahead(nr));
1096 return 0;
1099 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1101 ssize_t ret;
1102 struct file *file;
1104 ret = -EBADF;
1105 file = fget(fd);
1106 if (file) {
1107 if (file->f_mode & FMODE_READ) {
1108 struct address_space *mapping = file->f_mapping;
1109 unsigned long start = offset >> PAGE_CACHE_SHIFT;
1110 unsigned long end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1111 unsigned long len = end - start + 1;
1112 ret = do_readahead(mapping, file, start, len);
1114 fput(file);
1116 return ret;
1119 #ifdef CONFIG_MMU
1121 * This adds the requested page to the page cache if it isn't already there,
1122 * and schedules an I/O to read in its contents from disk.
1124 static int FASTCALL(page_cache_read(struct file * file, unsigned long offset));
1125 static int fastcall page_cache_read(struct file * file, unsigned long offset)
1127 struct address_space *mapping = file->f_mapping;
1128 struct page *page;
1129 int error;
1131 page = page_cache_alloc_cold(mapping);
1132 if (!page)
1133 return -ENOMEM;
1135 error = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1136 if (!error) {
1137 error = mapping->a_ops->readpage(file, page);
1138 page_cache_release(page);
1139 return error;
1143 * We arrive here in the unlikely event that someone
1144 * raced with us and added our page to the cache first
1145 * or we are out of memory for radix-tree nodes.
1147 page_cache_release(page);
1148 return error == -EEXIST ? 0 : error;
1151 #define MMAP_LOTSAMISS (100)
1154 * filemap_nopage() is invoked via the vma operations vector for a
1155 * mapped memory region to read in file data during a page fault.
1157 * The goto's are kind of ugly, but this streamlines the normal case of having
1158 * it in the page cache, and handles the special cases reasonably without
1159 * having a lot of duplicated code.
1161 struct page * filemap_nopage(struct vm_area_struct * area, unsigned long address, int *type)
1163 int error;
1164 struct file *file = area->vm_file;
1165 struct address_space *mapping = file->f_mapping;
1166 struct file_ra_state *ra = &file->f_ra;
1167 struct inode *inode = mapping->host;
1168 struct page *page;
1169 unsigned long size, pgoff, endoff;
1170 int did_readaround = 0, majmin = VM_FAULT_MINOR;
1172 pgoff = ((address - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1173 endoff = ((area->vm_end - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1175 retry_all:
1176 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1177 if (pgoff >= size)
1178 goto outside_data_content;
1180 /* If we don't want any read-ahead, don't bother */
1181 if (VM_RandomReadHint(area))
1182 goto no_cached_page;
1185 * The "size" of the file, as far as mmap is concerned, isn't bigger
1186 * than the mapping
1188 if (size > endoff)
1189 size = endoff;
1192 * The readahead code wants to be told about each and every page
1193 * so it can build and shrink its windows appropriately
1195 * For sequential accesses, we use the generic readahead logic.
1197 if (VM_SequentialReadHint(area))
1198 page_cache_readahead(mapping, ra, file, pgoff);
1201 * Do we have something in the page cache already?
1203 retry_find:
1204 page = find_get_page(mapping, pgoff);
1205 if (!page) {
1206 unsigned long ra_pages;
1208 if (VM_SequentialReadHint(area)) {
1209 handle_ra_miss(mapping, ra, pgoff);
1210 goto no_cached_page;
1212 ra->mmap_miss++;
1215 * Do we miss much more than hit in this file? If so,
1216 * stop bothering with read-ahead. It will only hurt.
1218 if (ra->mmap_miss > ra->mmap_hit + MMAP_LOTSAMISS)
1219 goto no_cached_page;
1222 * To keep the pgmajfault counter straight, we need to
1223 * check did_readaround, as this is an inner loop.
1225 if (!did_readaround) {
1226 majmin = VM_FAULT_MAJOR;
1227 inc_page_state(pgmajfault);
1229 did_readaround = 1;
1230 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1231 if (ra_pages) {
1232 pgoff_t start = 0;
1234 if (pgoff > ra_pages / 2)
1235 start = pgoff - ra_pages / 2;
1236 do_page_cache_readahead(mapping, file, start, ra_pages);
1238 page = find_get_page(mapping, pgoff);
1239 if (!page)
1240 goto no_cached_page;
1243 if (!did_readaround)
1244 ra->mmap_hit++;
1247 * Ok, found a page in the page cache, now we need to check
1248 * that it's up-to-date.
1250 if (!PageUptodate(page))
1251 goto page_not_uptodate;
1253 success:
1255 * Found the page and have a reference on it.
1257 mark_page_accessed(page);
1258 if (type)
1259 *type = majmin;
1260 return page;
1262 outside_data_content:
1264 * An external ptracer can access pages that normally aren't
1265 * accessible..
1267 if (area->vm_mm == current->mm)
1268 return NULL;
1269 /* Fall through to the non-read-ahead case */
1270 no_cached_page:
1272 * We're only likely to ever get here if MADV_RANDOM is in
1273 * effect.
1275 error = page_cache_read(file, pgoff);
1276 grab_swap_token();
1279 * The page we want has now been added to the page cache.
1280 * In the unlikely event that someone removed it in the
1281 * meantime, we'll just come back here and read it again.
1283 if (error >= 0)
1284 goto retry_find;
1287 * An error return from page_cache_read can result if the
1288 * system is low on memory, or a problem occurs while trying
1289 * to schedule I/O.
1291 if (error == -ENOMEM)
1292 return NOPAGE_OOM;
1293 return NULL;
1295 page_not_uptodate:
1296 if (!did_readaround) {
1297 majmin = VM_FAULT_MAJOR;
1298 inc_page_state(pgmajfault);
1300 lock_page(page);
1302 /* Did it get unhashed while we waited for it? */
1303 if (!page->mapping) {
1304 unlock_page(page);
1305 page_cache_release(page);
1306 goto retry_all;
1309 /* Did somebody else get it up-to-date? */
1310 if (PageUptodate(page)) {
1311 unlock_page(page);
1312 goto success;
1315 if (!mapping->a_ops->readpage(file, page)) {
1316 wait_on_page_locked(page);
1317 if (PageUptodate(page))
1318 goto success;
1322 * Umm, take care of errors if the page isn't up-to-date.
1323 * Try to re-read it _once_. We do this synchronously,
1324 * because there really aren't any performance issues here
1325 * and we need to check for errors.
1327 lock_page(page);
1329 /* Somebody truncated the page on us? */
1330 if (!page->mapping) {
1331 unlock_page(page);
1332 page_cache_release(page);
1333 goto retry_all;
1336 /* Somebody else successfully read it in? */
1337 if (PageUptodate(page)) {
1338 unlock_page(page);
1339 goto success;
1341 ClearPageError(page);
1342 if (!mapping->a_ops->readpage(file, page)) {
1343 wait_on_page_locked(page);
1344 if (PageUptodate(page))
1345 goto success;
1349 * Things didn't work out. Return zero to tell the
1350 * mm layer so, possibly freeing the page cache page first.
1352 page_cache_release(page);
1353 return NULL;
1356 EXPORT_SYMBOL(filemap_nopage);
1358 static struct page * filemap_getpage(struct file *file, unsigned long pgoff,
1359 int nonblock)
1361 struct address_space *mapping = file->f_mapping;
1362 struct page *page;
1363 int error;
1366 * Do we have something in the page cache already?
1368 retry_find:
1369 page = find_get_page(mapping, pgoff);
1370 if (!page) {
1371 if (nonblock)
1372 return NULL;
1373 goto no_cached_page;
1377 * Ok, found a page in the page cache, now we need to check
1378 * that it's up-to-date.
1380 if (!PageUptodate(page))
1381 goto page_not_uptodate;
1383 success:
1385 * Found the page and have a reference on it.
1387 mark_page_accessed(page);
1388 return page;
1390 no_cached_page:
1391 error = page_cache_read(file, pgoff);
1394 * The page we want has now been added to the page cache.
1395 * In the unlikely event that someone removed it in the
1396 * meantime, we'll just come back here and read it again.
1398 if (error >= 0)
1399 goto retry_find;
1402 * An error return from page_cache_read can result if the
1403 * system is low on memory, or a problem occurs while trying
1404 * to schedule I/O.
1406 return NULL;
1408 page_not_uptodate:
1409 lock_page(page);
1411 /* Did it get unhashed while we waited for it? */
1412 if (!page->mapping) {
1413 unlock_page(page);
1414 goto err;
1417 /* Did somebody else get it up-to-date? */
1418 if (PageUptodate(page)) {
1419 unlock_page(page);
1420 goto success;
1423 if (!mapping->a_ops->readpage(file, page)) {
1424 wait_on_page_locked(page);
1425 if (PageUptodate(page))
1426 goto success;
1430 * Umm, take care of errors if the page isn't up-to-date.
1431 * Try to re-read it _once_. We do this synchronously,
1432 * because there really aren't any performance issues here
1433 * and we need to check for errors.
1435 lock_page(page);
1437 /* Somebody truncated the page on us? */
1438 if (!page->mapping) {
1439 unlock_page(page);
1440 goto err;
1442 /* Somebody else successfully read it in? */
1443 if (PageUptodate(page)) {
1444 unlock_page(page);
1445 goto success;
1448 ClearPageError(page);
1449 if (!mapping->a_ops->readpage(file, page)) {
1450 wait_on_page_locked(page);
1451 if (PageUptodate(page))
1452 goto success;
1456 * Things didn't work out. Return zero to tell the
1457 * mm layer so, possibly freeing the page cache page first.
1459 err:
1460 page_cache_release(page);
1462 return NULL;
1465 static int filemap_populate(struct vm_area_struct *vma,
1466 unsigned long addr,
1467 unsigned long len,
1468 pgprot_t prot,
1469 unsigned long pgoff,
1470 int nonblock)
1472 struct file *file = vma->vm_file;
1473 struct address_space *mapping = file->f_mapping;
1474 struct inode *inode = mapping->host;
1475 unsigned long size;
1476 struct mm_struct *mm = vma->vm_mm;
1477 struct page *page;
1478 int err;
1480 if (!nonblock)
1481 force_page_cache_readahead(mapping, vma->vm_file,
1482 pgoff, len >> PAGE_CACHE_SHIFT);
1484 repeat:
1485 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1486 if (pgoff + (len >> PAGE_CACHE_SHIFT) > size)
1487 return -EINVAL;
1489 page = filemap_getpage(file, pgoff, nonblock);
1490 if (!page && !nonblock)
1491 return -ENOMEM;
1492 if (page) {
1493 err = install_page(mm, vma, addr, page, prot);
1494 if (err) {
1495 page_cache_release(page);
1496 return err;
1498 } else {
1499 err = install_file_pte(mm, vma, addr, pgoff, prot);
1500 if (err)
1501 return err;
1504 len -= PAGE_SIZE;
1505 addr += PAGE_SIZE;
1506 pgoff++;
1507 if (len)
1508 goto repeat;
1510 return 0;
1513 struct vm_operations_struct generic_file_vm_ops = {
1514 .nopage = filemap_nopage,
1515 .populate = filemap_populate,
1518 /* This is used for a general mmap of a disk file */
1520 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1522 struct address_space *mapping = file->f_mapping;
1524 if (!mapping->a_ops->readpage)
1525 return -ENOEXEC;
1526 file_accessed(file);
1527 vma->vm_ops = &generic_file_vm_ops;
1528 return 0;
1532 * This is for filesystems which do not implement ->writepage.
1534 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1536 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1537 return -EINVAL;
1538 return generic_file_mmap(file, vma);
1540 #else
1541 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1543 return -ENOSYS;
1545 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1547 return -ENOSYS;
1549 #endif /* CONFIG_MMU */
1551 EXPORT_SYMBOL(generic_file_mmap);
1552 EXPORT_SYMBOL(generic_file_readonly_mmap);
1554 static inline struct page *__read_cache_page(struct address_space *mapping,
1555 unsigned long index,
1556 int (*filler)(void *,struct page*),
1557 void *data)
1559 struct page *page, *cached_page = NULL;
1560 int err;
1561 repeat:
1562 page = find_get_page(mapping, index);
1563 if (!page) {
1564 if (!cached_page) {
1565 cached_page = page_cache_alloc_cold(mapping);
1566 if (!cached_page)
1567 return ERR_PTR(-ENOMEM);
1569 err = add_to_page_cache_lru(cached_page, mapping,
1570 index, GFP_KERNEL);
1571 if (err == -EEXIST)
1572 goto repeat;
1573 if (err < 0) {
1574 /* Presumably ENOMEM for radix tree node */
1575 page_cache_release(cached_page);
1576 return ERR_PTR(err);
1578 page = cached_page;
1579 cached_page = NULL;
1580 err = filler(data, page);
1581 if (err < 0) {
1582 page_cache_release(page);
1583 page = ERR_PTR(err);
1586 if (cached_page)
1587 page_cache_release(cached_page);
1588 return page;
1592 * Read into the page cache. If a page already exists,
1593 * and PageUptodate() is not set, try to fill the page.
1595 struct page *read_cache_page(struct address_space *mapping,
1596 unsigned long index,
1597 int (*filler)(void *,struct page*),
1598 void *data)
1600 struct page *page;
1601 int err;
1603 retry:
1604 page = __read_cache_page(mapping, index, filler, data);
1605 if (IS_ERR(page))
1606 goto out;
1607 mark_page_accessed(page);
1608 if (PageUptodate(page))
1609 goto out;
1611 lock_page(page);
1612 if (!page->mapping) {
1613 unlock_page(page);
1614 page_cache_release(page);
1615 goto retry;
1617 if (PageUptodate(page)) {
1618 unlock_page(page);
1619 goto out;
1621 err = filler(data, page);
1622 if (err < 0) {
1623 page_cache_release(page);
1624 page = ERR_PTR(err);
1626 out:
1627 return page;
1630 EXPORT_SYMBOL(read_cache_page);
1633 * If the page was newly created, increment its refcount and add it to the
1634 * caller's lru-buffering pagevec. This function is specifically for
1635 * generic_file_write().
1637 static inline struct page *
1638 __grab_cache_page(struct address_space *mapping, unsigned long index,
1639 struct page **cached_page, struct pagevec *lru_pvec)
1641 int err;
1642 struct page *page;
1643 repeat:
1644 page = find_lock_page(mapping, index);
1645 if (!page) {
1646 if (!*cached_page) {
1647 *cached_page = page_cache_alloc(mapping);
1648 if (!*cached_page)
1649 return NULL;
1651 err = add_to_page_cache(*cached_page, mapping,
1652 index, GFP_KERNEL);
1653 if (err == -EEXIST)
1654 goto repeat;
1655 if (err == 0) {
1656 page = *cached_page;
1657 page_cache_get(page);
1658 if (!pagevec_add(lru_pvec, page))
1659 __pagevec_lru_add(lru_pvec);
1660 *cached_page = NULL;
1663 return page;
1667 * The logic we want is
1669 * if suid or (sgid and xgrp)
1670 * remove privs
1672 int remove_suid(struct dentry *dentry)
1674 mode_t mode = dentry->d_inode->i_mode;
1675 int kill = 0;
1676 int result = 0;
1678 /* suid always must be killed */
1679 if (unlikely(mode & S_ISUID))
1680 kill = ATTR_KILL_SUID;
1683 * sgid without any exec bits is just a mandatory locking mark; leave
1684 * it alone. If some exec bits are set, it's a real sgid; kill it.
1686 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1687 kill |= ATTR_KILL_SGID;
1689 if (unlikely(kill && !capable(CAP_FSETID))) {
1690 struct iattr newattrs;
1692 newattrs.ia_valid = ATTR_FORCE | kill;
1693 result = notify_change(dentry, &newattrs);
1695 return result;
1697 EXPORT_SYMBOL(remove_suid);
1700 * Copy as much as we can into the page and return the number of bytes which
1701 * were sucessfully copied. If a fault is encountered then clear the page
1702 * out to (offset+bytes) and return the number of bytes which were copied.
1704 static inline size_t
1705 filemap_copy_from_user(struct page *page, unsigned long offset,
1706 const char __user *buf, unsigned bytes)
1708 char *kaddr;
1709 int left;
1711 kaddr = kmap_atomic(page, KM_USER0);
1712 left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
1713 kunmap_atomic(kaddr, KM_USER0);
1715 if (left != 0) {
1716 /* Do it the slow way */
1717 kaddr = kmap(page);
1718 left = __copy_from_user(kaddr + offset, buf, bytes);
1719 kunmap(page);
1721 return bytes - left;
1724 static size_t
1725 __filemap_copy_from_user_iovec(char *vaddr,
1726 const struct iovec *iov, size_t base, size_t bytes)
1728 size_t copied = 0, left = 0;
1730 while (bytes) {
1731 char __user *buf = iov->iov_base + base;
1732 int copy = min(bytes, iov->iov_len - base);
1734 base = 0;
1735 left = __copy_from_user_inatomic(vaddr, buf, copy);
1736 copied += copy;
1737 bytes -= copy;
1738 vaddr += copy;
1739 iov++;
1741 if (unlikely(left)) {
1742 /* zero the rest of the target like __copy_from_user */
1743 if (bytes)
1744 memset(vaddr, 0, bytes);
1745 break;
1748 return copied - left;
1752 * This has the same sideeffects and return value as filemap_copy_from_user().
1753 * The difference is that on a fault we need to memset the remainder of the
1754 * page (out to offset+bytes), to emulate filemap_copy_from_user()'s
1755 * single-segment behaviour.
1757 static inline size_t
1758 filemap_copy_from_user_iovec(struct page *page, unsigned long offset,
1759 const struct iovec *iov, size_t base, size_t bytes)
1761 char *kaddr;
1762 size_t copied;
1764 kaddr = kmap_atomic(page, KM_USER0);
1765 copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1766 base, bytes);
1767 kunmap_atomic(kaddr, KM_USER0);
1768 if (copied != bytes) {
1769 kaddr = kmap(page);
1770 copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1771 base, bytes);
1772 kunmap(page);
1774 return copied;
1777 static inline void
1778 filemap_set_next_iovec(const struct iovec **iovp, size_t *basep, size_t bytes)
1780 const struct iovec *iov = *iovp;
1781 size_t base = *basep;
1783 while (bytes) {
1784 int copy = min(bytes, iov->iov_len - base);
1786 bytes -= copy;
1787 base += copy;
1788 if (iov->iov_len == base) {
1789 iov++;
1790 base = 0;
1793 *iovp = iov;
1794 *basep = base;
1798 * Performs necessary checks before doing a write
1800 * Can adjust writing position aor amount of bytes to write.
1801 * Returns appropriate error code that caller should return or
1802 * zero in case that write should be allowed.
1804 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1806 struct inode *inode = file->f_mapping->host;
1807 unsigned long limit = current->rlim[RLIMIT_FSIZE].rlim_cur;
1809 if (unlikely(*pos < 0))
1810 return -EINVAL;
1812 if (unlikely(file->f_error)) {
1813 int err = file->f_error;
1814 file->f_error = 0;
1815 return err;
1818 if (!isblk) {
1819 /* FIXME: this is for backwards compatibility with 2.4 */
1820 if (file->f_flags & O_APPEND)
1821 *pos = i_size_read(inode);
1823 if (limit != RLIM_INFINITY) {
1824 if (*pos >= limit) {
1825 send_sig(SIGXFSZ, current, 0);
1826 return -EFBIG;
1828 if (*count > limit - (typeof(limit))*pos) {
1829 *count = limit - (typeof(limit))*pos;
1835 * LFS rule
1837 if (unlikely(*pos + *count > MAX_NON_LFS &&
1838 !(file->f_flags & O_LARGEFILE))) {
1839 if (*pos >= MAX_NON_LFS) {
1840 send_sig(SIGXFSZ, current, 0);
1841 return -EFBIG;
1843 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1844 *count = MAX_NON_LFS - (unsigned long)*pos;
1849 * Are we about to exceed the fs block limit ?
1851 * If we have written data it becomes a short write. If we have
1852 * exceeded without writing data we send a signal and return EFBIG.
1853 * Linus frestrict idea will clean these up nicely..
1855 if (likely(!isblk)) {
1856 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1857 if (*count || *pos > inode->i_sb->s_maxbytes) {
1858 send_sig(SIGXFSZ, current, 0);
1859 return -EFBIG;
1861 /* zero-length writes at ->s_maxbytes are OK */
1864 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1865 *count = inode->i_sb->s_maxbytes - *pos;
1866 } else {
1867 loff_t isize;
1868 if (bdev_read_only(I_BDEV(inode)))
1869 return -EPERM;
1870 isize = i_size_read(inode);
1871 if (*pos >= isize) {
1872 if (*count || *pos > isize)
1873 return -ENOSPC;
1876 if (*pos + *count > isize)
1877 *count = isize - *pos;
1879 return 0;
1882 EXPORT_SYMBOL(generic_write_checks);
1884 ssize_t
1885 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
1886 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
1887 size_t count, size_t ocount)
1889 struct file *file = iocb->ki_filp;
1890 struct address_space *mapping = file->f_mapping;
1891 struct inode *inode = mapping->host;
1892 ssize_t written;
1894 if (count != ocount)
1895 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
1897 written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
1898 if (written > 0) {
1899 loff_t end = pos + written;
1900 if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
1901 i_size_write(inode, end);
1902 mark_inode_dirty(inode);
1904 *ppos = end;
1908 * Sync the fs metadata but not the minor inode changes and
1909 * of course not the data as we did direct DMA for the IO.
1910 * i_sem is held, which protects generic_osync_inode() from
1911 * livelocking.
1913 if (written >= 0 && file->f_flags & O_SYNC)
1914 generic_osync_inode(inode, mapping, OSYNC_METADATA);
1915 if (written == count && !is_sync_kiocb(iocb))
1916 written = -EIOCBQUEUED;
1917 return written;
1920 EXPORT_SYMBOL(generic_file_direct_write);
1922 ssize_t
1923 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
1924 unsigned long nr_segs, loff_t pos, loff_t *ppos,
1925 size_t count, ssize_t written)
1927 struct file *file = iocb->ki_filp;
1928 struct address_space * mapping = file->f_mapping;
1929 struct address_space_operations *a_ops = mapping->a_ops;
1930 struct inode *inode = mapping->host;
1931 long status = 0;
1932 struct page *page;
1933 struct page *cached_page = NULL;
1934 size_t bytes;
1935 struct pagevec lru_pvec;
1936 const struct iovec *cur_iov = iov; /* current iovec */
1937 size_t iov_base = 0; /* offset in the current iovec */
1938 char __user *buf;
1940 pagevec_init(&lru_pvec, 0);
1942 buf = iov->iov_base + written; /* handle partial DIO write */
1943 do {
1944 unsigned long index;
1945 unsigned long offset;
1946 size_t copied;
1948 offset = (pos & (PAGE_CACHE_SIZE -1)); /* Within page */
1949 index = pos >> PAGE_CACHE_SHIFT;
1950 bytes = PAGE_CACHE_SIZE - offset;
1951 if (bytes > count)
1952 bytes = count;
1955 * Bring in the user page that we will copy from _first_.
1956 * Otherwise there's a nasty deadlock on copying from the
1957 * same page as we're writing to, without it being marked
1958 * up-to-date.
1960 fault_in_pages_readable(buf, bytes);
1962 page = __grab_cache_page(mapping,index,&cached_page,&lru_pvec);
1963 if (!page) {
1964 status = -ENOMEM;
1965 break;
1968 status = a_ops->prepare_write(file, page, offset, offset+bytes);
1969 if (unlikely(status)) {
1970 loff_t isize = i_size_read(inode);
1972 * prepare_write() may have instantiated a few blocks
1973 * outside i_size. Trim these off again.
1975 unlock_page(page);
1976 page_cache_release(page);
1977 if (pos + bytes > isize)
1978 vmtruncate(inode, isize);
1979 break;
1981 if (likely(nr_segs == 1))
1982 copied = filemap_copy_from_user(page, offset,
1983 buf, bytes);
1984 else
1985 copied = filemap_copy_from_user_iovec(page, offset,
1986 cur_iov, iov_base, bytes);
1987 flush_dcache_page(page);
1988 status = a_ops->commit_write(file, page, offset, offset+bytes);
1989 if (likely(copied > 0)) {
1990 if (!status)
1991 status = copied;
1993 if (status >= 0) {
1994 written += status;
1995 count -= status;
1996 pos += status;
1997 buf += status;
1998 if (unlikely(nr_segs > 1))
1999 filemap_set_next_iovec(&cur_iov,
2000 &iov_base, status);
2003 if (unlikely(copied != bytes))
2004 if (status >= 0)
2005 status = -EFAULT;
2006 unlock_page(page);
2007 mark_page_accessed(page);
2008 page_cache_release(page);
2009 if (status < 0)
2010 break;
2011 balance_dirty_pages_ratelimited(mapping);
2012 cond_resched();
2013 } while (count);
2014 *ppos = pos;
2016 if (cached_page)
2017 page_cache_release(cached_page);
2020 * For now, when the user asks for O_SYNC, we'll actually give O_DSYNC
2022 if (likely(status >= 0)) {
2023 if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2024 if (!a_ops->writepage || !is_sync_kiocb(iocb))
2025 status = generic_osync_inode(inode, mapping,
2026 OSYNC_METADATA|OSYNC_DATA);
2031 * If we get here for O_DIRECT writes then we must have fallen through
2032 * to buffered writes (block instantiation inside i_size). So we sync
2033 * the file data here, to try to honour O_DIRECT expectations.
2035 if (unlikely(file->f_flags & O_DIRECT) && written)
2036 status = filemap_write_and_wait(mapping);
2038 pagevec_lru_add(&lru_pvec);
2039 return written ? written : status;
2042 EXPORT_SYMBOL(generic_file_buffered_write);
2044 ssize_t
2045 generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2046 unsigned long nr_segs, loff_t *ppos)
2048 struct file *file = iocb->ki_filp;
2049 struct address_space * mapping = file->f_mapping;
2050 size_t ocount; /* original count */
2051 size_t count; /* after file limit checks */
2052 struct inode *inode = mapping->host;
2053 unsigned long seg;
2054 loff_t pos;
2055 ssize_t written;
2056 ssize_t err;
2058 ocount = 0;
2059 for (seg = 0; seg < nr_segs; seg++) {
2060 const struct iovec *iv = &iov[seg];
2063 * If any segment has a negative length, or the cumulative
2064 * length ever wraps negative then return -EINVAL.
2066 ocount += iv->iov_len;
2067 if (unlikely((ssize_t)(ocount|iv->iov_len) < 0))
2068 return -EINVAL;
2069 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
2070 continue;
2071 if (seg == 0)
2072 return -EFAULT;
2073 nr_segs = seg;
2074 ocount -= iv->iov_len; /* This segment is no good */
2075 break;
2078 count = ocount;
2079 pos = *ppos;
2081 /* We can write back this queue in page reclaim */
2082 current->backing_dev_info = mapping->backing_dev_info;
2083 written = 0;
2085 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2086 if (err)
2087 goto out;
2089 if (count == 0)
2090 goto out;
2092 err = remove_suid(file->f_dentry);
2093 if (err)
2094 goto out;
2096 inode_update_time(inode, 1);
2098 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2099 if (unlikely(file->f_flags & O_DIRECT)) {
2100 written = generic_file_direct_write(iocb, iov,
2101 &nr_segs, pos, ppos, count, ocount);
2102 if (written < 0 || written == count)
2103 goto out;
2105 * direct-io write to a hole: fall through to buffered I/O
2106 * for completing the rest of the request.
2108 pos += written;
2109 count -= written;
2112 written = generic_file_buffered_write(iocb, iov, nr_segs,
2113 pos, ppos, count, written);
2114 out:
2115 current->backing_dev_info = NULL;
2116 return written ? written : err;
2119 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2121 ssize_t
2122 generic_file_write_nolock(struct file *file, const struct iovec *iov,
2123 unsigned long nr_segs, loff_t *ppos)
2125 struct kiocb kiocb;
2126 ssize_t ret;
2128 init_sync_kiocb(&kiocb, file);
2129 ret = generic_file_aio_write_nolock(&kiocb, iov, nr_segs, ppos);
2130 if (-EIOCBQUEUED == ret)
2131 ret = wait_on_sync_kiocb(&kiocb);
2132 return ret;
2135 EXPORT_SYMBOL(generic_file_write_nolock);
2137 ssize_t generic_file_aio_write(struct kiocb *iocb, const char __user *buf,
2138 size_t count, loff_t pos)
2140 struct file *file = iocb->ki_filp;
2141 struct address_space *mapping = file->f_mapping;
2142 struct inode *inode = mapping->host;
2143 ssize_t ret;
2144 struct iovec local_iov = { .iov_base = (void __user *)buf,
2145 .iov_len = count };
2147 BUG_ON(iocb->ki_pos != pos);
2149 down(&inode->i_sem);
2150 ret = generic_file_aio_write_nolock(iocb, &local_iov, 1,
2151 &iocb->ki_pos);
2152 up(&inode->i_sem);
2154 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2155 ssize_t err;
2157 err = sync_page_range(inode, mapping, pos, ret);
2158 if (err < 0)
2159 ret = err;
2161 return ret;
2163 EXPORT_SYMBOL(generic_file_aio_write);
2165 ssize_t generic_file_write(struct file *file, const char __user *buf,
2166 size_t count, loff_t *ppos)
2168 struct address_space *mapping = file->f_mapping;
2169 struct inode *inode = mapping->host;
2170 ssize_t ret;
2171 struct iovec local_iov = { .iov_base = (void __user *)buf,
2172 .iov_len = count };
2174 down(&inode->i_sem);
2175 ret = generic_file_write_nolock(file, &local_iov, 1, ppos);
2176 up(&inode->i_sem);
2178 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2179 ssize_t err;
2181 err = sync_page_range(inode, mapping, *ppos - ret, ret);
2182 if (err < 0)
2183 ret = err;
2185 return ret;
2187 EXPORT_SYMBOL(generic_file_write);
2189 ssize_t generic_file_readv(struct file *filp, const struct iovec *iov,
2190 unsigned long nr_segs, loff_t *ppos)
2192 struct kiocb kiocb;
2193 ssize_t ret;
2195 init_sync_kiocb(&kiocb, filp);
2196 ret = __generic_file_aio_read(&kiocb, iov, nr_segs, ppos);
2197 if (-EIOCBQUEUED == ret)
2198 ret = wait_on_sync_kiocb(&kiocb);
2199 return ret;
2202 EXPORT_SYMBOL(generic_file_readv);
2204 ssize_t generic_file_writev(struct file *file, const struct iovec *iov,
2205 unsigned long nr_segs, loff_t *ppos)
2207 struct address_space *mapping = file->f_mapping;
2208 struct inode *inode = mapping->host;
2209 ssize_t ret;
2211 down(&inode->i_sem);
2212 ret = generic_file_write_nolock(file, iov, nr_segs, ppos);
2213 up(&inode->i_sem);
2215 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2216 int err;
2218 err = sync_page_range(inode, mapping, *ppos - ret, ret);
2219 if (err < 0)
2220 ret = err;
2222 return ret;
2225 EXPORT_SYMBOL(generic_file_writev);
2228 * Called under i_sem for writes to S_ISREG files
2230 ssize_t
2231 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2232 loff_t offset, unsigned long nr_segs)
2234 struct file *file = iocb->ki_filp;
2235 struct address_space *mapping = file->f_mapping;
2236 ssize_t retval;
2238 retval = filemap_write_and_wait(mapping);
2239 if (retval == 0) {
2240 retval = mapping->a_ops->direct_IO(rw, iocb, iov,
2241 offset, nr_segs);
2242 if (rw == WRITE && mapping->nrpages)
2243 invalidate_inode_pages2(mapping);
2245 return retval;
2248 EXPORT_SYMBOL_GPL(generic_file_direct_IO);