This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / mm / filemap.c
1 /*
2  *      linux/mm/filemap.c
3  *
4  * Copyright (C) 1994-1999  Linus Torvalds
5  */
6
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)
11  */
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>
30 /*
31  * This is needed for the following functions:
32  *  - try_to_release_page
33  *  - block_invalidatepage
34  *  - generic_osync_inode
35  *
36  * FIXME: remove all knowledge of the buffer layer from the core VM
37  */
38 #include <linux/buffer_head.h> /* for generic_osync_inode */
39
40 #include <asm/uaccess.h>
41 #include <asm/mman.h>
42
43 /*
44  * Shared mappings implemented 30.11.1994. It's not fully working yet,
45  * though.
46  *
47  * Shared mappings now work. 15.8.1995  Bruno.
48  *
49  * finished 'unifying' the page and buffer cache and SMP-threaded the
50  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
51  *
52  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
53  */
54
55 /*
56  * Lock ordering:
57  *
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
63  *    ->page_map_lock()         (try_to_unmap_file)
64  *
65  *  ->i_sem
66  *    ->i_mmap_lock             (truncate->unmap_mapping_range)
67  *
68  *  ->mmap_sem
69  *    ->i_mmap_lock
70  *      ->page_table_lock       (various places, mainly in mmap.c)
71  *        ->mapping->tree_lock  (arch-dependent flush_dcache_mmap_lock)
72  *
73  *  ->mmap_sem
74  *    ->lock_page               (access_process_vm)
75  *
76  *  ->mmap_sem
77  *    ->i_sem                   (msync)
78  *
79  *  ->i_sem
80  *    ->i_alloc_sem             (various)
81  *
82  *  ->inode_lock
83  *    ->sb_lock                 (fs/fs-writeback.c)
84  *    ->mapping->tree_lock      (__sync_single_inode)
85  *
86  *  ->page_table_lock
87  *    ->swap_device_lock        (try_to_unmap_one)
88  *    ->private_lock            (try_to_unmap_one)
89  *    ->tree_lock               (try_to_unmap_one)
90  *    ->zone.lru_lock           (follow_page->mark_page_accessed)
91  *    ->page_map_lock()         (page_add_anon_rmap)
92  *      ->tree_lock             (page_remove_rmap->set_page_dirty)
93  *      ->private_lock          (page_remove_rmap->set_page_dirty)
94  *      ->inode_lock            (page_remove_rmap->set_page_dirty)
95  *    ->anon_vma.lock           (anon_vma_prepare)
96  *    ->inode_lock              (zap_pte_range->set_page_dirty)
97  *    ->private_lock            (zap_pte_range->__set_page_dirty_buffers)
98  *
99  *  ->task->proc_lock
100  *    ->dcache_lock             (proc_pid_lookup)
101  */
102
103 /*
104  * Remove a page from the page cache and free it. Caller has to make
105  * sure the page is locked and that nobody else uses it - or that usage
106  * is safe.  The caller must hold a write_lock on the mapping's tree_lock.
107  */
108 void __remove_from_page_cache(struct page *page)
109 {
110         struct address_space *mapping = page->mapping;
111
112         radix_tree_delete(&mapping->page_tree, page->index);
113         page->mapping = NULL;
114         mapping->nrpages--;
115         pagecache_acct(-1);
116 }
117
118 void remove_from_page_cache(struct page *page)
119 {
120         struct address_space *mapping = page->mapping;
121
122         if (unlikely(!PageLocked(page)))
123                 PAGE_BUG(page);
124
125         spin_lock_irq(&mapping->tree_lock);
126         __remove_from_page_cache(page);
127         spin_unlock_irq(&mapping->tree_lock);
128 }
129
130 static inline int sync_page(struct page *page)
131 {
132         struct address_space *mapping;
133
134         /*
135          * FIXME, fercrissake.  What is this barrier here for?
136          */
137         smp_mb();
138         mapping = page_mapping(page);
139         if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
140                 return mapping->a_ops->sync_page(page);
141         return 0;
142 }
143
144 /**
145  * filemap_fdatawrite - start writeback against all of a mapping's dirty pages
146  * @mapping: address space structure to write
147  *
148  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
149  * opposed to a regular memory * cleansing writeback.  The difference between
150  * these two operations is that if a dirty page/buffer is encountered, it must
151  * be waited upon, and not just skipped over.
152  */
153 static int __filemap_fdatawrite(struct address_space *mapping, int sync_mode)
154 {
155         int ret;
156         struct writeback_control wbc = {
157                 .sync_mode = sync_mode,
158                 .nr_to_write = mapping->nrpages * 2,
159         };
160
161         if (mapping->backing_dev_info->memory_backed)
162                 return 0;
163
164         ret = do_writepages(mapping, &wbc);
165         return ret;
166 }
167
168 int filemap_fdatawrite(struct address_space *mapping)
169 {
170         return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
171 }
172 EXPORT_SYMBOL(filemap_fdatawrite);
173
174 /*
175  * This is a mostly non-blocking flush.  Not suitable for data-integrity
176  * purposes - I/O may not be started against all dirty pages.
177  */
178 int filemap_flush(struct address_space *mapping)
179 {
180         return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
181 }
182 EXPORT_SYMBOL(filemap_flush);
183
184 /*
185  * Wait for writeback to complete against pages indexed by start->end
186  * inclusive
187  */
188 static int wait_on_page_writeback_range(struct address_space *mapping,
189                                 pgoff_t start, pgoff_t end)
190 {
191         struct pagevec pvec;
192         int nr_pages;
193         int ret = 0;
194         pgoff_t index;
195
196         if (end < start)
197                 return 0;
198
199         pagevec_init(&pvec, 0);
200         index = start;
201         while ((nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
202                         PAGECACHE_TAG_WRITEBACK,
203                         min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
204                 unsigned i;
205
206                 for (i = 0; i < nr_pages; i++) {
207                         struct page *page = pvec.pages[i];
208
209                         wait_on_page_writeback(page);
210                         if (PageError(page))
211                                 ret = -EIO;
212                 }
213                 pagevec_release(&pvec);
214                 cond_resched();
215         }
216
217         /* Check for outstanding write errors */
218         if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
219                 ret = -ENOSPC;
220         if (test_and_clear_bit(AS_EIO, &mapping->flags))
221                 ret = -EIO;
222
223         return ret;
224 }
225
226 /**
227  * filemap_fdatawait - walk the list of under-writeback pages of the given
228  *     address space and wait for all of them.
229  *
230  * @mapping: address space structure to wait for
231  */
232 int filemap_fdatawait(struct address_space *mapping)
233 {
234         return wait_on_page_writeback_range(mapping, 0, -1);
235 }
236
237 EXPORT_SYMBOL(filemap_fdatawait);
238
239 int filemap_write_and_wait(struct address_space *mapping)
240 {
241         int retval = 0;
242
243         if (mapping->nrpages) {
244                 retval = filemap_fdatawrite(mapping);
245                 if (retval == 0)
246                         retval = filemap_fdatawait(mapping);
247         }
248         return retval;
249 }
250
251 /*
252  * This function is used to add newly allocated pagecache pages:
253  * the page is new, so we can just run SetPageLocked() against it.
254  * The other page state flags were set by rmqueue().
255  *
256  * This function does not add the page to the LRU.  The caller must do that.
257  */
258 int add_to_page_cache(struct page *page, struct address_space *mapping,
259                 pgoff_t offset, int gfp_mask)
260 {
261         int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
262
263         if (error == 0) {
264                 spin_lock_irq(&mapping->tree_lock);
265                 error = radix_tree_insert(&mapping->page_tree, offset, page);
266                 if (!error) {
267                         page_cache_get(page);
268                         SetPageLocked(page);
269                         page->mapping = mapping;
270                         page->index = offset;
271                         mapping->nrpages++;
272                         pagecache_acct(1);
273                 }
274                 spin_unlock_irq(&mapping->tree_lock);
275                 radix_tree_preload_end();
276         }
277         return error;
278 }
279
280 EXPORT_SYMBOL(add_to_page_cache);
281
282 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
283                                 pgoff_t offset, int gfp_mask)
284 {
285         int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
286         if (ret == 0)
287                 lru_cache_add(page);
288         return ret;
289 }
290
291 /*
292  * In order to wait for pages to become available there must be
293  * waitqueues associated with pages. By using a hash table of
294  * waitqueues where the bucket discipline is to maintain all
295  * waiters on the same queue and wake all when any of the pages
296  * become available, and for the woken contexts to check to be
297  * sure the appropriate page became available, this saves space
298  * at a cost of "thundering herd" phenomena during rare hash
299  * collisions.
300  */
301 struct page_wait_queue {
302         struct page *page;
303         int bit;
304         wait_queue_t wait;
305 };
306
307 static int page_wake_function(wait_queue_t *wait, unsigned mode, int sync, void *key)
308 {
309         struct page *page = key;
310         struct page_wait_queue *wq;
311
312         wq = container_of(wait, struct page_wait_queue, wait);
313         if (wq->page != page || test_bit(wq->bit, &page->flags))
314                 return 0;
315         else
316                 return autoremove_wake_function(wait, mode, sync, NULL);
317 }
318
319 #define __DEFINE_PAGE_WAIT(name, p, b, f)                               \
320         struct page_wait_queue name = {                                 \
321                 .page   = p,                                            \
322                 .bit    = b,                                            \
323                 .wait   = {                                             \
324                         .task   = current,                              \
325                         .func   = page_wake_function,                   \
326                         .flags  = f,                                    \
327                         .task_list = LIST_HEAD_INIT(name.wait.task_list),\
328                 },                                                      \
329         }
330
331 #define DEFINE_PAGE_WAIT(name, p, b)    __DEFINE_PAGE_WAIT(name, p, b, 0)
332 #define DEFINE_PAGE_WAIT_EXCLUSIVE(name, p, b)                          \
333                 __DEFINE_PAGE_WAIT(name, p, b, WQ_FLAG_EXCLUSIVE)
334
335 static wait_queue_head_t *page_waitqueue(struct page *page)
336 {
337         const struct zone *zone = page_zone(page);
338
339         return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
340 }
341
342 static void wake_up_page(struct page *page)
343 {
344         const unsigned int mode = TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE;
345         wait_queue_head_t *waitqueue = page_waitqueue(page);
346
347         if (waitqueue_active(waitqueue))
348                 __wake_up(waitqueue, mode, 1, page);
349 }
350
351 void fastcall wait_on_page_bit(struct page *page, int bit_nr)
352 {
353         wait_queue_head_t *waitqueue = page_waitqueue(page);
354         DEFINE_PAGE_WAIT(wait, page, bit_nr);
355
356         do {
357                 prepare_to_wait(waitqueue, &wait.wait, TASK_UNINTERRUPTIBLE);
358                 if (test_bit(bit_nr, &page->flags)) {
359                         sync_page(page);
360                         io_schedule();
361                 }
362         } while (test_bit(bit_nr, &page->flags));
363         finish_wait(waitqueue, &wait.wait);
364 }
365
366 EXPORT_SYMBOL(wait_on_page_bit);
367
368 /**
369  * unlock_page() - unlock a locked page
370  *
371  * @page: the page
372  *
373  * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
374  * Also wakes sleepers in wait_on_page_writeback() because the wakeup
375  * mechananism between PageLocked pages and PageWriteback pages is shared.
376  * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
377  *
378  * The first mb is necessary to safely close the critical section opened by the
379  * TestSetPageLocked(), the second mb is necessary to enforce ordering between
380  * the clear_bit and the read of the waitqueue (to avoid SMP races with a
381  * parallel wait_on_page_locked()).
382  */
383 void fastcall unlock_page(struct page *page)
384 {
385         smp_mb__before_clear_bit();
386         if (!TestClearPageLocked(page))
387                 BUG();
388         smp_mb__after_clear_bit(); 
389         wake_up_page(page);
390 }
391
392 EXPORT_SYMBOL(unlock_page);
393 EXPORT_SYMBOL(lock_page);
394
395 /*
396  * End writeback against a page.
397  */
398 void end_page_writeback(struct page *page)
399 {
400         if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
401                 if (!test_clear_page_writeback(page))
402                         BUG();
403                 smp_mb__after_clear_bit();
404         }
405         wake_up_page(page);
406 }
407
408 EXPORT_SYMBOL(end_page_writeback);
409
410 /*
411  * Get a lock on the page, assuming we need to sleep to get it.
412  *
413  * Ugly: running sync_page() in state TASK_UNINTERRUPTIBLE is scary.  If some
414  * random driver's requestfn sets TASK_RUNNING, we could busywait.  However
415  * chances are that on the second loop, the block layer's plug list is empty,
416  * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
417  */
418 void fastcall __lock_page(struct page *page)
419 {
420         wait_queue_head_t *wqh = page_waitqueue(page);
421         DEFINE_PAGE_WAIT_EXCLUSIVE(wait, page, PG_locked);
422
423         while (TestSetPageLocked(page)) {
424                 prepare_to_wait_exclusive(wqh, &wait.wait, TASK_UNINTERRUPTIBLE);
425                 if (PageLocked(page)) {
426                         sync_page(page);
427                         io_schedule();
428                 }
429         }
430         finish_wait(wqh, &wait.wait);
431 }
432
433 EXPORT_SYMBOL(__lock_page);
434
435 /*
436  * a rather lightweight function, finding and getting a reference to a
437  * hashed page atomically.
438  */
439 struct page * find_get_page(struct address_space *mapping, unsigned long offset)
440 {
441         struct page *page;
442
443         /*
444          * We scan the hash list read-only. Addition to and removal from
445          * the hash-list needs a held write-lock.
446          */
447         spin_lock_irq(&mapping->tree_lock);
448         page = radix_tree_lookup(&mapping->page_tree, offset);
449         if (page)
450                 page_cache_get(page);
451         spin_unlock_irq(&mapping->tree_lock);
452         return page;
453 }
454
455 EXPORT_SYMBOL(find_get_page);
456
457 /*
458  * Same as above, but trylock it instead of incrementing the count.
459  */
460 struct page *find_trylock_page(struct address_space *mapping, unsigned long offset)
461 {
462         struct page *page;
463
464         spin_lock_irq(&mapping->tree_lock);
465         page = radix_tree_lookup(&mapping->page_tree, offset);
466         if (page && TestSetPageLocked(page))
467                 page = NULL;
468         spin_unlock_irq(&mapping->tree_lock);
469         return page;
470 }
471
472 EXPORT_SYMBOL(find_trylock_page);
473
474 /**
475  * find_lock_page - locate, pin and lock a pagecache page
476  *
477  * @mapping - the address_space to search
478  * @offset - the page index
479  *
480  * Locates the desired pagecache page, locks it, increments its reference
481  * count and returns its address.
482  *
483  * Returns zero if the page was not present. find_lock_page() may sleep.
484  */
485 struct page *find_lock_page(struct address_space *mapping,
486                                 unsigned long offset)
487 {
488         struct page *page;
489
490         spin_lock_irq(&mapping->tree_lock);
491 repeat:
492         page = radix_tree_lookup(&mapping->page_tree, offset);
493         if (page) {
494                 page_cache_get(page);
495                 if (TestSetPageLocked(page)) {
496                         spin_unlock_irq(&mapping->tree_lock);
497                         lock_page(page);
498                         spin_lock_irq(&mapping->tree_lock);
499
500                         /* Has the page been truncated while we slept? */
501                         if (page->mapping != mapping || page->index != offset) {
502                                 unlock_page(page);
503                                 page_cache_release(page);
504                                 goto repeat;
505                         }
506                 }
507         }
508         spin_unlock_irq(&mapping->tree_lock);
509         return page;
510 }
511
512 EXPORT_SYMBOL(find_lock_page);
513
514 /**
515  * find_or_create_page - locate or add a pagecache page
516  *
517  * @mapping - the page's address_space
518  * @index - the page's index into the mapping
519  * @gfp_mask - page allocation mode
520  *
521  * Locates a page in the pagecache.  If the page is not present, a new page
522  * is allocated using @gfp_mask and is added to the pagecache and to the VM's
523  * LRU list.  The returned page is locked and has its reference count
524  * incremented.
525  *
526  * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
527  * allocation!
528  *
529  * find_or_create_page() returns the desired page's address, or zero on
530  * memory exhaustion.
531  */
532 struct page *find_or_create_page(struct address_space *mapping,
533                 unsigned long index, unsigned int gfp_mask)
534 {
535         struct page *page, *cached_page = NULL;
536         int err;
537 repeat:
538         page = find_lock_page(mapping, index);
539         if (!page) {
540                 if (!cached_page) {
541                         cached_page = alloc_page(gfp_mask);
542                         if (!cached_page)
543                                 return NULL;
544                 }
545                 err = add_to_page_cache_lru(cached_page, mapping,
546                                         index, gfp_mask);
547                 if (!err) {
548                         page = cached_page;
549                         cached_page = NULL;
550                 } else if (err == -EEXIST)
551                         goto repeat;
552         }
553         if (cached_page)
554                 page_cache_release(cached_page);
555         return page;
556 }
557
558 EXPORT_SYMBOL(find_or_create_page);
559
560 /**
561  * find_get_pages - gang pagecache lookup
562  * @mapping:    The address_space to search
563  * @start:      The starting page index
564  * @nr_pages:   The maximum number of pages
565  * @pages:      Where the resulting pages are placed
566  *
567  * find_get_pages() will search for and return a group of up to
568  * @nr_pages pages in the mapping.  The pages are placed at @pages.
569  * find_get_pages() takes a reference against the returned pages.
570  *
571  * The search returns a group of mapping-contiguous pages with ascending
572  * indexes.  There may be holes in the indices due to not-present pages.
573  *
574  * find_get_pages() returns the number of pages which were found.
575  */
576 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
577                             unsigned int nr_pages, struct page **pages)
578 {
579         unsigned int i;
580         unsigned int ret;
581
582         spin_lock_irq(&mapping->tree_lock);
583         ret = radix_tree_gang_lookup(&mapping->page_tree,
584                                 (void **)pages, start, nr_pages);
585         for (i = 0; i < ret; i++)
586                 page_cache_get(pages[i]);
587         spin_unlock_irq(&mapping->tree_lock);
588         return ret;
589 }
590
591 /*
592  * Like find_get_pages, except we only return pages which are tagged with
593  * `tag'.   We update *index to index the next page for the traversal.
594  */
595 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
596                         int tag, unsigned int nr_pages, struct page **pages)
597 {
598         unsigned int i;
599         unsigned int ret;
600
601         spin_lock_irq(&mapping->tree_lock);
602         ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
603                                 (void **)pages, *index, nr_pages, tag);
604         for (i = 0; i < ret; i++)
605                 page_cache_get(pages[i]);
606         if (ret)
607                 *index = pages[ret - 1]->index + 1;
608         spin_unlock_irq(&mapping->tree_lock);
609         return ret;
610 }
611
612 /*
613  * Same as grab_cache_page, but do not wait if the page is unavailable.
614  * This is intended for speculative data generators, where the data can
615  * be regenerated if the page couldn't be grabbed.  This routine should
616  * be safe to call while holding the lock for another page.
617  *
618  * Clear __GFP_FS when allocating the page to avoid recursion into the fs
619  * and deadlock against the caller's locked page.
620  */
621 struct page *
622 grab_cache_page_nowait(struct address_space *mapping, unsigned long index)
623 {
624         struct page *page = find_get_page(mapping, index);
625         int gfp_mask;
626
627         if (page) {
628                 if (!TestSetPageLocked(page))
629                         return page;
630                 page_cache_release(page);
631                 return NULL;
632         }
633         gfp_mask = mapping_gfp_mask(mapping) & ~__GFP_FS;
634         page = alloc_pages(gfp_mask, 0);
635         if (page && add_to_page_cache_lru(page, mapping, index, gfp_mask)) {
636                 page_cache_release(page);
637                 page = NULL;
638         }
639         return page;
640 }
641
642 EXPORT_SYMBOL(grab_cache_page_nowait);
643
644 /*
645  * This is a generic file read routine, and uses the
646  * mapping->a_ops->readpage() function for the actual low-level
647  * stuff.
648  *
649  * This is really ugly. But the goto's actually try to clarify some
650  * of the logic when it comes to error handling etc.
651  * - note the struct file * is only passed for the use of readpage
652  */
653 void do_generic_mapping_read(struct address_space *mapping,
654                              struct file_ra_state *_ra,
655                              struct file * filp,
656                              loff_t *ppos,
657                              read_descriptor_t * desc,
658                              read_actor_t actor)
659 {
660         struct inode *inode = mapping->host;
661         unsigned long index, end_index, offset;
662         loff_t isize;
663         struct page *cached_page;
664         int error;
665         struct file_ra_state ra = *_ra;
666
667         cached_page = NULL;
668         index = *ppos >> PAGE_CACHE_SHIFT;
669         offset = *ppos & ~PAGE_CACHE_MASK;
670
671         isize = i_size_read(inode);
672         end_index = isize >> PAGE_CACHE_SHIFT;
673         if (index > end_index)
674                 goto out;
675
676         for (;;) {
677                 struct page *page;
678                 unsigned long nr, ret;
679
680                 cond_resched();
681                 page_cache_readahead(mapping, &ra, filp, index);
682
683 find_page:
684                 page = find_get_page(mapping, index);
685                 if (unlikely(page == NULL)) {
686                         handle_ra_miss(mapping, &ra, index);
687                         goto no_cached_page;
688                 }
689                 if (!PageUptodate(page))
690                         goto page_not_up_to_date;
691 page_ok:
692                 /* nr is the maximum number of bytes to copy from this page */
693                 nr = PAGE_CACHE_SIZE;
694                 if (index == end_index) {
695                         nr = isize & ~PAGE_CACHE_MASK;
696                         if (nr <= offset) {
697                                 page_cache_release(page);
698                                 goto out;
699                         }
700                 }
701                 nr = nr - offset;
702
703                 /* If users can be writing to this page using arbitrary
704                  * virtual addresses, take care about potential aliasing
705                  * before reading the page on the kernel side.
706                  */
707                 if (mapping_writably_mapped(mapping))
708                         flush_dcache_page(page);
709
710                 /*
711                  * Mark the page accessed if we read the beginning.
712                  */
713                 if (!offset)
714                         mark_page_accessed(page);
715
716                 /*
717                  * Ok, we have the page, and it's up-to-date, so
718                  * now we can copy it to user space...
719                  *
720                  * The actor routine returns how many bytes were actually used..
721                  * NOTE! This may not be the same as how much of a user buffer
722                  * we filled up (we may be padding etc), so we can only update
723                  * "pos" here (the actor routine has to update the user buffer
724                  * pointers and the remaining count).
725                  */
726                 ret = actor(desc, page, offset, nr);
727                 offset += ret;
728                 index += offset >> PAGE_CACHE_SHIFT;
729                 offset &= ~PAGE_CACHE_MASK;
730
731                 page_cache_release(page);
732                 if (ret == nr && desc->count)
733                         continue;
734                 goto out;
735
736 page_not_up_to_date:
737                 /* Get exclusive access to the page ... */
738                 lock_page(page);
739
740                 /* Did it get unhashed before we got the lock? */
741                 if (!page->mapping) {
742                         unlock_page(page);
743                         page_cache_release(page);
744                         continue;
745                 }
746
747                 /* Did somebody else fill it already? */
748                 if (PageUptodate(page)) {
749                         unlock_page(page);
750                         goto page_ok;
751                 }
752
753 readpage:
754                 /* Start the actual read. The read will unlock the page. */
755                 error = mapping->a_ops->readpage(filp, page);
756
757                 if (unlikely(error))
758                         goto readpage_error;
759
760                 if (!PageUptodate(page)) {
761                         wait_on_page_locked(page);
762                         if (!PageUptodate(page)) {
763                                 error = -EIO;
764                                 goto readpage_error;
765                         }
766                 }
767
768                 /*
769                  * i_size must be checked after we have done ->readpage.
770                  *
771                  * Checking i_size after the readpage allows us to calculate
772                  * the correct value for "nr", which means the zero-filled
773                  * part of the page is not copied back to userspace (unless
774                  * another truncate extends the file - this is desired though).
775                  */
776                 isize = i_size_read(inode);
777                 end_index = isize >> PAGE_CACHE_SHIFT;
778                 if (index > end_index) {
779                         page_cache_release(page);
780                         goto out;
781                 }
782                 goto page_ok;
783
784 readpage_error:
785                 /* UHHUH! A synchronous read error occurred. Report it */
786                 desc->error = error;
787                 page_cache_release(page);
788                 goto out;
789
790 no_cached_page:
791                 /*
792                  * Ok, it wasn't cached, so we need to create a new
793                  * page..
794                  */
795                 if (!cached_page) {
796                         cached_page = page_cache_alloc_cold(mapping);
797                         if (!cached_page) {
798                                 desc->error = -ENOMEM;
799                                 goto out;
800                         }
801                 }
802                 error = add_to_page_cache_lru(cached_page, mapping,
803                                                 index, GFP_KERNEL);
804                 if (error) {
805                         if (error == -EEXIST)
806                                 goto find_page;
807                         desc->error = error;
808                         goto out;
809                 }
810                 page = cached_page;
811                 cached_page = NULL;
812                 goto readpage;
813         }
814
815 out:
816         *_ra = ra;
817
818         *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
819         if (cached_page)
820                 page_cache_release(cached_page);
821         file_accessed(filp);
822 }
823
824 EXPORT_SYMBOL(do_generic_mapping_read);
825
826 int file_read_actor(read_descriptor_t *desc, struct page *page,
827                         unsigned long offset, unsigned long size)
828 {
829         char *kaddr;
830         unsigned long left, count = desc->count;
831
832         if (size > count)
833                 size = count;
834
835         /*
836          * Faults on the destination of a read are common, so do it before
837          * taking the kmap.
838          */
839         if (!fault_in_pages_writeable(desc->arg.buf, size)) {
840                 kaddr = kmap_atomic(page, KM_USER0);
841                 left = __copy_to_user_inatomic(desc->arg.buf, kaddr + offset, size);
842                 kunmap_atomic(kaddr, KM_USER0);
843                 if (left == 0)
844                         goto success;
845         }
846
847         /* Do it the slow way */
848         kaddr = kmap(page);
849         left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
850         kunmap(page);
851
852         if (left) {
853                 size -= left;
854                 desc->error = -EFAULT;
855         }
856 success:
857         desc->count = count - size;
858         desc->written += size;
859         desc->arg.buf += size;
860         return size;
861 }
862
863 /*
864  * This is the "read()" routine for all filesystems
865  * that can use the page cache directly.
866  */
867 ssize_t
868 __generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
869                 unsigned long nr_segs, loff_t *ppos)
870 {
871         struct file *filp = iocb->ki_filp;
872         ssize_t retval;
873         unsigned long seg;
874         size_t count;
875
876         count = 0;
877         for (seg = 0; seg < nr_segs; seg++) {
878                 const struct iovec *iv = &iov[seg];
879
880                 /*
881                  * If any segment has a negative length, or the cumulative
882                  * length ever wraps negative then return -EINVAL.
883                  */
884                 count += iv->iov_len;
885                 if (unlikely((ssize_t)(count|iv->iov_len) < 0))
886                         return -EINVAL;
887                 if (access_ok(VERIFY_WRITE, iv->iov_base, iv->iov_len))
888                         continue;
889                 if (seg == 0)
890                         return -EFAULT;
891                 nr_segs = seg;
892                 count -= iv->iov_len;   /* This segment is no good */
893                 break;
894         }
895
896         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
897         if (filp->f_flags & O_DIRECT) {
898                 loff_t pos = *ppos, size;
899                 struct address_space *mapping;
900                 struct inode *inode;
901
902                 mapping = filp->f_mapping;
903                 inode = mapping->host;
904                 retval = 0;
905                 if (!count)
906                         goto out; /* skip atime */
907                 size = i_size_read(inode);
908                 if (pos < size) {
909                         retval = generic_file_direct_IO(READ, iocb,
910                                                 iov, pos, nr_segs);
911                         if (retval >= 0 && !is_sync_kiocb(iocb))
912                                 retval = -EIOCBQUEUED;
913                         if (retval > 0)
914                                 *ppos = pos + retval;
915                 }
916                 file_accessed(filp);
917                 goto out;
918         }
919
920         retval = 0;
921         if (count) {
922                 for (seg = 0; seg < nr_segs; seg++) {
923                         read_descriptor_t desc;
924
925                         desc.written = 0;
926                         desc.arg.buf = iov[seg].iov_base;
927                         desc.count = iov[seg].iov_len;
928                         if (desc.count == 0)
929                                 continue;
930                         desc.error = 0;
931                         do_generic_file_read(filp,ppos,&desc,file_read_actor);
932                         retval += desc.written;
933                         if (!retval) {
934                                 retval = desc.error;
935                                 break;
936                         }
937                 }
938         }
939 out:
940         return retval;
941 }
942
943 EXPORT_SYMBOL(__generic_file_aio_read);
944
945 ssize_t
946 generic_file_aio_read(struct kiocb *iocb, char __user *buf, size_t count, loff_t pos)
947 {
948         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
949
950         BUG_ON(iocb->ki_pos != pos);
951         return __generic_file_aio_read(iocb, &local_iov, 1, &iocb->ki_pos);
952 }
953
954 EXPORT_SYMBOL(generic_file_aio_read);
955
956 ssize_t
957 generic_file_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
958 {
959         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
960         struct kiocb kiocb;
961         ssize_t ret;
962
963         init_sync_kiocb(&kiocb, filp);
964         ret = __generic_file_aio_read(&kiocb, &local_iov, 1, ppos);
965         if (-EIOCBQUEUED == ret)
966                 ret = wait_on_sync_kiocb(&kiocb);
967         return ret;
968 }
969
970 EXPORT_SYMBOL(generic_file_read);
971
972 int file_send_actor(read_descriptor_t * desc, struct page *page, unsigned long offset, unsigned long size)
973 {
974         ssize_t written;
975         unsigned long count = desc->count;
976         struct file *file = desc->arg.data;
977
978         if (size > count)
979                 size = count;
980
981         written = file->f_op->sendpage(file, page, offset,
982                                        size, &file->f_pos, size<count);
983         if (written < 0) {
984                 desc->error = written;
985                 written = 0;
986         }
987         desc->count = count - written;
988         desc->written += written;
989         return written;
990 }
991
992 ssize_t generic_file_sendfile(struct file *in_file, loff_t *ppos,
993                          size_t count, read_actor_t actor, void *target)
994 {
995         read_descriptor_t desc;
996
997         if (!count)
998                 return 0;
999
1000         desc.written = 0;
1001         desc.count = count;
1002         desc.arg.data = target;
1003         desc.error = 0;
1004
1005         do_generic_file_read(in_file, ppos, &desc, actor);
1006         if (desc.written)
1007                 return desc.written;
1008         return desc.error;
1009 }
1010
1011 EXPORT_SYMBOL(generic_file_sendfile);
1012
1013 static ssize_t
1014 do_readahead(struct address_space *mapping, struct file *filp,
1015              unsigned long index, unsigned long nr)
1016 {
1017         if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1018                 return -EINVAL;
1019
1020         force_page_cache_readahead(mapping, filp, index,
1021                                         max_sane_readahead(nr));
1022         return 0;
1023 }
1024
1025 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1026 {
1027         ssize_t ret;
1028         struct file *file;
1029
1030         ret = -EBADF;
1031         file = fget(fd);
1032         if (file) {
1033                 if (file->f_mode & FMODE_READ) {
1034                         struct address_space *mapping = file->f_mapping;
1035                         unsigned long start = offset >> PAGE_CACHE_SHIFT;
1036                         unsigned long end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1037                         unsigned long len = end - start + 1;
1038                         ret = do_readahead(mapping, file, start, len);
1039                 }
1040                 fput(file);
1041         }
1042         return ret;
1043 }
1044
1045 #ifdef CONFIG_MMU
1046 /*
1047  * This adds the requested page to the page cache if it isn't already there,
1048  * and schedules an I/O to read in its contents from disk.
1049  */
1050 static int FASTCALL(page_cache_read(struct file * file, unsigned long offset));
1051 static int fastcall page_cache_read(struct file * file, unsigned long offset)
1052 {
1053         struct address_space *mapping = file->f_mapping;
1054         struct page *page; 
1055         int error;
1056
1057         page = page_cache_alloc_cold(mapping);
1058         if (!page)
1059                 return -ENOMEM;
1060
1061         error = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1062         if (!error) {
1063                 error = mapping->a_ops->readpage(file, page);
1064                 page_cache_release(page);
1065                 return error;
1066         }
1067
1068         /*
1069          * We arrive here in the unlikely event that someone 
1070          * raced with us and added our page to the cache first
1071          * or we are out of memory for radix-tree nodes.
1072          */
1073         page_cache_release(page);
1074         return error == -EEXIST ? 0 : error;
1075 }
1076
1077 #define MMAP_LOTSAMISS  (100)
1078
1079 /*
1080  * filemap_nopage() is invoked via the vma operations vector for a
1081  * mapped memory region to read in file data during a page fault.
1082  *
1083  * The goto's are kind of ugly, but this streamlines the normal case of having
1084  * it in the page cache, and handles the special cases reasonably without
1085  * having a lot of duplicated code.
1086  */
1087 struct page * filemap_nopage(struct vm_area_struct * area, unsigned long address, int *type)
1088 {
1089         int error;
1090         struct file *file = area->vm_file;
1091         struct address_space *mapping = file->f_mapping;
1092         struct file_ra_state *ra = &file->f_ra;
1093         struct inode *inode = mapping->host;
1094         struct page *page;
1095         unsigned long size, pgoff, endoff;
1096         int did_readaround = 0, majmin = VM_FAULT_MINOR;
1097
1098         pgoff = ((address - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1099         endoff = ((area->vm_end - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1100
1101 retry_all:
1102         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1103         if (pgoff >= size)
1104                 goto outside_data_content;
1105
1106         /* If we don't want any read-ahead, don't bother */
1107         if (VM_RandomReadHint(area))
1108                 goto no_cached_page;
1109
1110         /*
1111          * The "size" of the file, as far as mmap is concerned, isn't bigger
1112          * than the mapping
1113          */
1114         if (size > endoff)
1115                 size = endoff;
1116
1117         /*
1118          * The readahead code wants to be told about each and every page
1119          * so it can build and shrink its windows appropriately
1120          *
1121          * For sequential accesses, we use the generic readahead logic.
1122          */
1123         if (VM_SequentialReadHint(area))
1124                 page_cache_readahead(mapping, ra, file, pgoff);
1125
1126         /*
1127          * Do we have something in the page cache already?
1128          */
1129 retry_find:
1130         page = find_get_page(mapping, pgoff);
1131         if (!page) {
1132                 unsigned long ra_pages;
1133
1134                 if (VM_SequentialReadHint(area)) {
1135                         handle_ra_miss(mapping, ra, pgoff);
1136                         goto no_cached_page;
1137                 }
1138                 ra->mmap_miss++;
1139
1140                 /*
1141                  * Do we miss much more than hit in this file? If so,
1142                  * stop bothering with read-ahead. It will only hurt.
1143                  */
1144                 if (ra->mmap_miss > ra->mmap_hit + MMAP_LOTSAMISS)
1145                         goto no_cached_page;
1146
1147                 /*
1148                  * To keep the pgmajfault counter straight, we need to
1149                  * check did_readaround, as this is an inner loop.
1150                  */
1151                 if (!did_readaround) {
1152                         majmin = VM_FAULT_MAJOR;
1153                         inc_page_state(pgmajfault);
1154                 }
1155                 did_readaround = 1;
1156                 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1157                 if (ra_pages) {
1158                         pgoff_t start = 0;
1159
1160                         if (pgoff > ra_pages / 2)
1161                                 start = pgoff - ra_pages / 2;
1162                         do_page_cache_readahead(mapping, file, start, ra_pages);
1163                 }
1164                 page = find_get_page(mapping, pgoff);
1165                 if (!page)
1166                         goto no_cached_page;
1167         }
1168
1169         if (!did_readaround)
1170                 ra->mmap_hit++;
1171
1172         /*
1173          * Ok, found a page in the page cache, now we need to check
1174          * that it's up-to-date.
1175          */
1176         if (!PageUptodate(page))
1177                 goto page_not_uptodate;
1178
1179 success:
1180         /*
1181          * Found the page and have a reference on it.
1182          */
1183         mark_page_accessed(page);
1184         if (type)
1185                 *type = majmin;
1186         return page;
1187
1188 outside_data_content:
1189         /*
1190          * An external ptracer can access pages that normally aren't
1191          * accessible..
1192          */
1193         if (area->vm_mm == current->mm)
1194                 return NULL;
1195         /* Fall through to the non-read-ahead case */
1196 no_cached_page:
1197         /*
1198          * We're only likely to ever get here if MADV_RANDOM is in
1199          * effect.
1200          */
1201         error = page_cache_read(file, pgoff);
1202
1203         /*
1204          * The page we want has now been added to the page cache.
1205          * In the unlikely event that someone removed it in the
1206          * meantime, we'll just come back here and read it again.
1207          */
1208         if (error >= 0)
1209                 goto retry_find;
1210
1211         /*
1212          * An error return from page_cache_read can result if the
1213          * system is low on memory, or a problem occurs while trying
1214          * to schedule I/O.
1215          */
1216         if (error == -ENOMEM)
1217                 return NOPAGE_OOM;
1218         return NULL;
1219
1220 page_not_uptodate:
1221         if (!did_readaround) {
1222                 majmin = VM_FAULT_MAJOR;
1223                 inc_page_state(pgmajfault);
1224         }
1225         lock_page(page);
1226
1227         /* Did it get unhashed while we waited for it? */
1228         if (!page->mapping) {
1229                 unlock_page(page);
1230                 page_cache_release(page);
1231                 goto retry_all;
1232         }
1233
1234         /* Did somebody else get it up-to-date? */
1235         if (PageUptodate(page)) {
1236                 unlock_page(page);
1237                 goto success;
1238         }
1239
1240         if (!mapping->a_ops->readpage(file, page)) {
1241                 wait_on_page_locked(page);
1242                 if (PageUptodate(page))
1243                         goto success;
1244         }
1245
1246         /*
1247          * Umm, take care of errors if the page isn't up-to-date.
1248          * Try to re-read it _once_. We do this synchronously,
1249          * because there really aren't any performance issues here
1250          * and we need to check for errors.
1251          */
1252         lock_page(page);
1253
1254         /* Somebody truncated the page on us? */
1255         if (!page->mapping) {
1256                 unlock_page(page);
1257                 page_cache_release(page);
1258                 goto retry_all;
1259         }
1260
1261         /* Somebody else successfully read it in? */
1262         if (PageUptodate(page)) {
1263                 unlock_page(page);
1264                 goto success;
1265         }
1266         ClearPageError(page);
1267         if (!mapping->a_ops->readpage(file, page)) {
1268                 wait_on_page_locked(page);
1269                 if (PageUptodate(page))
1270                         goto success;
1271         }
1272
1273         /*
1274          * Things didn't work out. Return zero to tell the
1275          * mm layer so, possibly freeing the page cache page first.
1276          */
1277         page_cache_release(page);
1278         return NULL;
1279 }
1280
1281 EXPORT_SYMBOL(filemap_nopage);
1282
1283 static struct page * filemap_getpage(struct file *file, unsigned long pgoff,
1284                                         int nonblock)
1285 {
1286         struct address_space *mapping = file->f_mapping;
1287         struct page *page;
1288         int error;
1289
1290         /*
1291          * Do we have something in the page cache already?
1292          */
1293 retry_find:
1294         page = find_get_page(mapping, pgoff);
1295         if (!page) {
1296                 if (nonblock)
1297                         return NULL;
1298                 goto no_cached_page;
1299         }
1300
1301         /*
1302          * Ok, found a page in the page cache, now we need to check
1303          * that it's up-to-date.
1304          */
1305         if (!PageUptodate(page))
1306                 goto page_not_uptodate;
1307
1308 success:
1309         /*
1310          * Found the page and have a reference on it.
1311          */
1312         mark_page_accessed(page);
1313         return page;
1314
1315 no_cached_page:
1316         error = page_cache_read(file, pgoff);
1317
1318         /*
1319          * The page we want has now been added to the page cache.
1320          * In the unlikely event that someone removed it in the
1321          * meantime, we'll just come back here and read it again.
1322          */
1323         if (error >= 0)
1324                 goto retry_find;
1325
1326         /*
1327          * An error return from page_cache_read can result if the
1328          * system is low on memory, or a problem occurs while trying
1329          * to schedule I/O.
1330          */
1331         return NULL;
1332
1333 page_not_uptodate:
1334         lock_page(page);
1335
1336         /* Did it get unhashed while we waited for it? */
1337         if (!page->mapping) {
1338                 unlock_page(page);
1339                 goto err;
1340         }
1341
1342         /* Did somebody else get it up-to-date? */
1343         if (PageUptodate(page)) {
1344                 unlock_page(page);
1345                 goto success;
1346         }
1347
1348         if (!mapping->a_ops->readpage(file, page)) {
1349                 wait_on_page_locked(page);
1350                 if (PageUptodate(page))
1351                         goto success;
1352         }
1353
1354         /*
1355          * Umm, take care of errors if the page isn't up-to-date.
1356          * Try to re-read it _once_. We do this synchronously,
1357          * because there really aren't any performance issues here
1358          * and we need to check for errors.
1359          */
1360         lock_page(page);
1361
1362         /* Somebody truncated the page on us? */
1363         if (!page->mapping) {
1364                 unlock_page(page);
1365                 goto err;
1366         }
1367         /* Somebody else successfully read it in? */
1368         if (PageUptodate(page)) {
1369                 unlock_page(page);
1370                 goto success;
1371         }
1372
1373         ClearPageError(page);
1374         if (!mapping->a_ops->readpage(file, page)) {
1375                 wait_on_page_locked(page);
1376                 if (PageUptodate(page))
1377                         goto success;
1378         }
1379
1380         /*
1381          * Things didn't work out. Return zero to tell the
1382          * mm layer so, possibly freeing the page cache page first.
1383          */
1384 err:
1385         page_cache_release(page);
1386
1387         return NULL;
1388 }
1389
1390 static int filemap_populate(struct vm_area_struct *vma,
1391                         unsigned long addr,
1392                         unsigned long len,
1393                         pgprot_t prot,
1394                         unsigned long pgoff,
1395                         int nonblock)
1396 {
1397         struct file *file = vma->vm_file;
1398         struct address_space *mapping = file->f_mapping;
1399         struct inode *inode = mapping->host;
1400         unsigned long size;
1401         struct mm_struct *mm = vma->vm_mm;
1402         struct page *page;
1403         int err;
1404
1405         if (!nonblock)
1406                 force_page_cache_readahead(mapping, vma->vm_file,
1407                                         pgoff, len >> PAGE_CACHE_SHIFT);
1408
1409 repeat:
1410         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1411         if (pgoff + (len >> PAGE_CACHE_SHIFT) > size)
1412                 return -EINVAL;
1413
1414         page = filemap_getpage(file, pgoff, nonblock);
1415         if (!page && !nonblock)
1416                 return -ENOMEM;
1417         if (page) {
1418                 err = install_page(mm, vma, addr, page, prot);
1419                 if (err) {
1420                         page_cache_release(page);
1421                         return err;
1422                 }
1423         } else {
1424                 /*
1425                  * If a nonlinear mapping then store the file page offset
1426                  * in the pte.
1427                  */
1428                 if (pgoff != linear_page_index(vma, addr)) {
1429                         err = install_file_pte(mm, vma, addr, pgoff, prot);
1430                         if (err)
1431                                 return err;
1432                 }
1433         }
1434
1435         len -= PAGE_SIZE;
1436         addr += PAGE_SIZE;
1437         pgoff++;
1438         if (len)
1439                 goto repeat;
1440
1441         return 0;
1442 }
1443
1444 static struct vm_operations_struct generic_file_vm_ops = {
1445         .nopage         = filemap_nopage,
1446         .populate       = filemap_populate,
1447 };
1448
1449 /* This is used for a general mmap of a disk file */
1450
1451 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1452 {
1453         struct address_space *mapping = file->f_mapping;
1454
1455         if (!mapping->a_ops->readpage)
1456                 return -ENOEXEC;
1457         file_accessed(file);
1458         vma->vm_ops = &generic_file_vm_ops;
1459         return 0;
1460 }
1461
1462 /*
1463  * This is for filesystems which do not implement ->writepage.
1464  */
1465 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1466 {
1467         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1468                 return -EINVAL;
1469         return generic_file_mmap(file, vma);
1470 }
1471 #else
1472 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1473 {
1474         return -ENOSYS;
1475 }
1476 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1477 {
1478         return -ENOSYS;
1479 }
1480 #endif /* CONFIG_MMU */
1481
1482 EXPORT_SYMBOL(generic_file_mmap);
1483 EXPORT_SYMBOL(generic_file_readonly_mmap);
1484
1485 static inline struct page *__read_cache_page(struct address_space *mapping,
1486                                 unsigned long index,
1487                                 int (*filler)(void *,struct page*),
1488                                 void *data)
1489 {
1490         struct page *page, *cached_page = NULL;
1491         int err;
1492 repeat:
1493         page = find_get_page(mapping, index);
1494         if (!page) {
1495                 if (!cached_page) {
1496                         cached_page = page_cache_alloc_cold(mapping);
1497                         if (!cached_page)
1498                                 return ERR_PTR(-ENOMEM);
1499                 }
1500                 err = add_to_page_cache_lru(cached_page, mapping,
1501                                         index, GFP_KERNEL);
1502                 if (err == -EEXIST)
1503                         goto repeat;
1504                 if (err < 0) {
1505                         /* Presumably ENOMEM for radix tree node */
1506                         page_cache_release(cached_page);
1507                         return ERR_PTR(err);
1508                 }
1509                 page = cached_page;
1510                 cached_page = NULL;
1511                 err = filler(data, page);
1512                 if (err < 0) {
1513                         page_cache_release(page);
1514                         page = ERR_PTR(err);
1515                 }
1516         }
1517         if (cached_page)
1518                 page_cache_release(cached_page);
1519         return page;
1520 }
1521
1522 /*
1523  * Read into the page cache. If a page already exists,
1524  * and PageUptodate() is not set, try to fill the page.
1525  */
1526 struct page *read_cache_page(struct address_space *mapping,
1527                                 unsigned long index,
1528                                 int (*filler)(void *,struct page*),
1529                                 void *data)
1530 {
1531         struct page *page;
1532         int err;
1533
1534 retry:
1535         page = __read_cache_page(mapping, index, filler, data);
1536         if (IS_ERR(page))
1537                 goto out;
1538         mark_page_accessed(page);
1539         if (PageUptodate(page))
1540                 goto out;
1541
1542         lock_page(page);
1543         if (!page->mapping) {
1544                 unlock_page(page);
1545                 page_cache_release(page);
1546                 goto retry;
1547         }
1548         if (PageUptodate(page)) {
1549                 unlock_page(page);
1550                 goto out;
1551         }
1552         err = filler(data, page);
1553         if (err < 0) {
1554                 page_cache_release(page);
1555                 page = ERR_PTR(err);
1556         }
1557  out:
1558         return page;
1559 }
1560
1561 EXPORT_SYMBOL(read_cache_page);
1562
1563 /*
1564  * If the page was newly created, increment its refcount and add it to the
1565  * caller's lru-buffering pagevec.  This function is specifically for
1566  * generic_file_write().
1567  */
1568 static inline struct page *
1569 __grab_cache_page(struct address_space *mapping, unsigned long index,
1570                         struct page **cached_page, struct pagevec *lru_pvec)
1571 {
1572         int err;
1573         struct page *page;
1574 repeat:
1575         page = find_lock_page(mapping, index);
1576         if (!page) {
1577                 if (!*cached_page) {
1578                         *cached_page = page_cache_alloc(mapping);
1579                         if (!*cached_page)
1580                                 return NULL;
1581                 }
1582                 err = add_to_page_cache(*cached_page, mapping,
1583                                         index, GFP_KERNEL);
1584                 if (err == -EEXIST)
1585                         goto repeat;
1586                 if (err == 0) {
1587                         page = *cached_page;
1588                         page_cache_get(page);
1589                         if (!pagevec_add(lru_pvec, page))
1590                                 __pagevec_lru_add(lru_pvec);
1591                         *cached_page = NULL;
1592                 }
1593         }
1594         return page;
1595 }
1596
1597 /*
1598  * The logic we want is
1599  *
1600  *      if suid or (sgid and xgrp)
1601  *              remove privs
1602  */
1603 int remove_suid(struct dentry *dentry)
1604 {
1605         mode_t mode = dentry->d_inode->i_mode;
1606         int kill = 0;
1607         int result = 0;
1608
1609         /* suid always must be killed */
1610         if (unlikely(mode & S_ISUID))
1611                 kill = ATTR_KILL_SUID;
1612
1613         /*
1614          * sgid without any exec bits is just a mandatory locking mark; leave
1615          * it alone.  If some exec bits are set, it's a real sgid; kill it.
1616          */
1617         if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1618                 kill |= ATTR_KILL_SGID;
1619
1620         if (unlikely(kill && !capable(CAP_FSETID))) {
1621                 struct iattr newattrs;
1622
1623                 newattrs.ia_valid = ATTR_FORCE | kill;
1624                 result = notify_change(dentry, &newattrs);
1625         }
1626         return result;
1627 }
1628 EXPORT_SYMBOL(remove_suid);
1629
1630 /*
1631  * Copy as much as we can into the page and return the number of bytes which
1632  * were sucessfully copied.  If a fault is encountered then clear the page
1633  * out to (offset+bytes) and return the number of bytes which were copied.
1634  */
1635 static inline size_t
1636 filemap_copy_from_user(struct page *page, unsigned long offset,
1637                         const char __user *buf, unsigned bytes)
1638 {
1639         char *kaddr;
1640         int left;
1641
1642         kaddr = kmap_atomic(page, KM_USER0);
1643         left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
1644         kunmap_atomic(kaddr, KM_USER0);
1645
1646         if (left != 0) {
1647                 /* Do it the slow way */
1648                 kaddr = kmap(page);
1649                 left = __copy_from_user(kaddr + offset, buf, bytes);
1650                 kunmap(page);
1651         }
1652         return bytes - left;
1653 }
1654
1655 static size_t
1656 __filemap_copy_from_user_iovec(char *vaddr, 
1657                         const struct iovec *iov, size_t base, size_t bytes)
1658 {
1659         size_t copied = 0, left = 0;
1660
1661         while (bytes) {
1662                 char __user *buf = iov->iov_base + base;
1663                 int copy = min(bytes, iov->iov_len - base);
1664
1665                 base = 0;
1666                 left = __copy_from_user_inatomic(vaddr, buf, copy);
1667                 copied += copy;
1668                 bytes -= copy;
1669                 vaddr += copy;
1670                 iov++;
1671
1672                 if (unlikely(left)) {
1673                         /* zero the rest of the target like __copy_from_user */
1674                         if (bytes)
1675                                 memset(vaddr, 0, bytes);
1676                         break;
1677                 }
1678         }
1679         return copied - left;
1680 }
1681
1682 /*
1683  * This has the same sideeffects and return value as filemap_copy_from_user().
1684  * The difference is that on a fault we need to memset the remainder of the
1685  * page (out to offset+bytes), to emulate filemap_copy_from_user()'s
1686  * single-segment behaviour.
1687  */
1688 static inline size_t
1689 filemap_copy_from_user_iovec(struct page *page, unsigned long offset,
1690                         const struct iovec *iov, size_t base, size_t bytes)
1691 {
1692         char *kaddr;
1693         size_t copied;
1694
1695         kaddr = kmap_atomic(page, KM_USER0);
1696         copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1697                                                 base, bytes);
1698         kunmap_atomic(kaddr, KM_USER0);
1699         if (copied != bytes) {
1700                 kaddr = kmap(page);
1701                 copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1702                                                         base, bytes);
1703                 kunmap(page);
1704         }
1705         return copied;
1706 }
1707
1708 static inline void
1709 filemap_set_next_iovec(const struct iovec **iovp, size_t *basep, size_t bytes)
1710 {
1711         const struct iovec *iov = *iovp;
1712         size_t base = *basep;
1713
1714         while (bytes) {
1715                 int copy = min(bytes, iov->iov_len - base);
1716
1717                 bytes -= copy;
1718                 base += copy;
1719                 if (iov->iov_len == base) {
1720                         iov++;
1721                         base = 0;
1722                 }
1723         }
1724         *iovp = iov;
1725         *basep = base;
1726 }
1727
1728 /*
1729  * Performs necessary checks before doing a write
1730  *
1731  * Can adjust writing position aor amount of bytes to write.
1732  * Returns appropriate error code that caller should return or
1733  * zero in case that write should be allowed.
1734  */
1735 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1736 {
1737         struct inode *inode = file->f_mapping->host;
1738         unsigned long limit = current->rlim[RLIMIT_FSIZE].rlim_cur;
1739
1740         if (unlikely(*pos < 0))
1741                 return -EINVAL;
1742
1743         if (unlikely(file->f_error)) {
1744                 int err = file->f_error;
1745                 file->f_error = 0;
1746                 return err;
1747         }
1748
1749         if (!isblk) {
1750                 /* FIXME: this is for backwards compatibility with 2.4 */
1751                 if (file->f_flags & O_APPEND)
1752                         *pos = i_size_read(inode);
1753
1754                 if (limit != RLIM_INFINITY) {
1755                         if (*pos >= limit) {
1756                                 send_sig(SIGXFSZ, current, 0);
1757                                 return -EFBIG;
1758                         }
1759                         if (*count > limit - (typeof(limit))*pos) {
1760                                 *count = limit - (typeof(limit))*pos;
1761                         }
1762                 }
1763         }
1764
1765         /*
1766          * LFS rule
1767          */
1768         if (unlikely(*pos + *count > MAX_NON_LFS &&
1769                                 !(file->f_flags & O_LARGEFILE))) {
1770                 if (*pos >= MAX_NON_LFS) {
1771                         send_sig(SIGXFSZ, current, 0);
1772                         return -EFBIG;
1773                 }
1774                 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1775                         *count = MAX_NON_LFS - (unsigned long)*pos;
1776                 }
1777         }
1778
1779         /*
1780          * Are we about to exceed the fs block limit ?
1781          *
1782          * If we have written data it becomes a short write.  If we have
1783          * exceeded without writing data we send a signal and return EFBIG.
1784          * Linus frestrict idea will clean these up nicely..
1785          */
1786         if (likely(!isblk)) {
1787                 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1788                         if (*count || *pos > inode->i_sb->s_maxbytes) {
1789                                 send_sig(SIGXFSZ, current, 0);
1790                                 return -EFBIG;
1791                         }
1792                         /* zero-length writes at ->s_maxbytes are OK */
1793                 }
1794
1795                 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1796                         *count = inode->i_sb->s_maxbytes - *pos;
1797         } else {
1798                 loff_t isize;
1799                 if (bdev_read_only(I_BDEV(inode)))
1800                         return -EPERM;
1801                 isize = i_size_read(inode);
1802                 if (*pos >= isize) {
1803                         if (*count || *pos > isize)
1804                                 return -ENOSPC;
1805                 }
1806
1807                 if (*pos + *count > isize)
1808                         *count = isize - *pos;
1809         }
1810         return 0;
1811 }
1812
1813 EXPORT_SYMBOL(generic_write_checks);
1814
1815 /*
1816  * Write to a file through the page cache. 
1817  * Called under i_sem for S_ISREG files.
1818  *
1819  * We put everything into the page cache prior to writing it. This is not a
1820  * problem when writing full pages. With partial pages, however, we first have
1821  * to read the data into the cache, then dirty the page, and finally schedule
1822  * it for writing by marking it dirty.
1823  *                                                      okir@monad.swb.de
1824  */
1825 ssize_t
1826 generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
1827                                 unsigned long nr_segs, loff_t *ppos)
1828 {
1829         struct file *file = iocb->ki_filp;
1830         struct address_space * mapping = file->f_mapping;
1831         struct address_space_operations *a_ops = mapping->a_ops;
1832         size_t ocount;          /* original count */
1833         size_t count;           /* after file limit checks */
1834         struct inode    *inode = mapping->host;
1835         long            status = 0;
1836         loff_t          pos;
1837         struct page     *page;
1838         struct page     *cached_page = NULL;
1839         const int       isblk = S_ISBLK(inode->i_mode);
1840         ssize_t         written;
1841         ssize_t         err;
1842         size_t          bytes;
1843         struct pagevec  lru_pvec;
1844         const struct iovec *cur_iov = iov; /* current iovec */
1845         size_t          iov_base = 0;      /* offset in the current iovec */
1846         unsigned long   seg;
1847         char __user     *buf;
1848
1849         ocount = 0;
1850         for (seg = 0; seg < nr_segs; seg++) {
1851                 const struct iovec *iv = &iov[seg];
1852
1853                 /*
1854                  * If any segment has a negative length, or the cumulative
1855                  * length ever wraps negative then return -EINVAL.
1856                  */
1857                 ocount += iv->iov_len;
1858                 if (unlikely((ssize_t)(ocount|iv->iov_len) < 0))
1859                         return -EINVAL;
1860                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1861                         continue;
1862                 if (seg == 0)
1863                         return -EFAULT;
1864                 nr_segs = seg;
1865                 ocount -= iv->iov_len;  /* This segment is no good */
1866                 break;
1867         }
1868
1869         count = ocount;
1870         pos = *ppos;
1871         pagevec_init(&lru_pvec, 0);
1872
1873         /* We can write back this queue in page reclaim */
1874         current->backing_dev_info = mapping->backing_dev_info;
1875         written = 0;
1876
1877         err = generic_write_checks(file, &pos, &count, isblk);
1878         if (err)
1879                 goto out;
1880
1881         if (count == 0)
1882                 goto out;
1883
1884         err = remove_suid(file->f_dentry);
1885         if (err)
1886                 goto out;
1887
1888         inode_update_time(inode, 1);
1889
1890         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1891         if (unlikely(file->f_flags & O_DIRECT)) {
1892                 if (count != ocount)
1893                         nr_segs = iov_shorten((struct iovec *)iov,
1894                                                 nr_segs, count);
1895                 written = generic_file_direct_IO(WRITE, iocb,
1896                                         iov, pos, nr_segs);
1897                 if (written > 0) {
1898                         loff_t end = pos + written;
1899                         if (end > i_size_read(inode) && !isblk) {
1900                                 i_size_write(inode,  end);
1901                                 mark_inode_dirty(inode);
1902                         }
1903                         *ppos = end;
1904                 }
1905                 /*
1906                  * Sync the fs metadata but not the minor inode changes and
1907                  * of course not the data as we did direct DMA for the IO.
1908                  * i_sem is held, which protects generic_osync_inode() from
1909                  * livelocking.
1910                  */
1911                 if (written >= 0 && file->f_flags & O_SYNC)
1912                         status = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1913                 if (written == count && !is_sync_kiocb(iocb))
1914                         written = -EIOCBQUEUED;
1915                 if (written < 0 || written == count)
1916                         goto out_status;
1917                 /*
1918                  * direct-io write to a hole: fall through to buffered I/O
1919                  * for completing the rest of the request.
1920                  */
1921                 pos += written;
1922                 count -= written;
1923         }
1924
1925         buf = iov->iov_base + written;  /* handle partial DIO write */
1926         do {
1927                 unsigned long index;
1928                 unsigned long offset;
1929                 size_t copied;
1930
1931                 offset = (pos & (PAGE_CACHE_SIZE -1)); /* Within page */
1932                 index = pos >> PAGE_CACHE_SHIFT;
1933                 bytes = PAGE_CACHE_SIZE - offset;
1934                 if (bytes > count)
1935                         bytes = count;
1936
1937                 /*
1938                  * Bring in the user page that we will copy from _first_.
1939                  * Otherwise there's a nasty deadlock on copying from the
1940                  * same page as we're writing to, without it being marked
1941                  * up-to-date.
1942                  */
1943                 fault_in_pages_readable(buf, bytes);
1944
1945                 page = __grab_cache_page(mapping,index,&cached_page,&lru_pvec);
1946                 if (!page) {
1947                         status = -ENOMEM;
1948                         break;
1949                 }
1950
1951                 status = a_ops->prepare_write(file, page, offset, offset+bytes);
1952                 if (unlikely(status)) {
1953                         loff_t isize = i_size_read(inode);
1954                         /*
1955                          * prepare_write() may have instantiated a few blocks
1956                          * outside i_size.  Trim these off again.
1957                          */
1958                         unlock_page(page);
1959                         page_cache_release(page);
1960                         if (pos + bytes > isize)
1961                                 vmtruncate(inode, isize);
1962                         break;
1963                 }
1964                 if (likely(nr_segs == 1))
1965                         copied = filemap_copy_from_user(page, offset,
1966                                                         buf, bytes);
1967                 else
1968                         copied = filemap_copy_from_user_iovec(page, offset,
1969                                                 cur_iov, iov_base, bytes);
1970                 flush_dcache_page(page);
1971                 status = a_ops->commit_write(file, page, offset, offset+bytes);
1972                 if (likely(copied > 0)) {
1973                         if (!status)
1974                                 status = copied;
1975
1976                         if (status >= 0) {
1977                                 written += status;
1978                                 count -= status;
1979                                 pos += status;
1980                                 buf += status;
1981                                 if (unlikely(nr_segs > 1))
1982                                         filemap_set_next_iovec(&cur_iov,
1983                                                         &iov_base, status);
1984                         }
1985                 }
1986                 if (unlikely(copied != bytes))
1987                         if (status >= 0)
1988                                 status = -EFAULT;
1989                 unlock_page(page);
1990                 mark_page_accessed(page);
1991                 page_cache_release(page);
1992                 if (status < 0)
1993                         break;
1994                 balance_dirty_pages_ratelimited(mapping);
1995                 cond_resched();
1996         } while (count);
1997         *ppos = pos;
1998
1999         if (cached_page)
2000                 page_cache_release(cached_page);
2001
2002         /*
2003          * For now, when the user asks for O_SYNC, we'll actually give O_DSYNC
2004          */
2005         if (status >= 0) {
2006                 if ((file->f_flags & O_SYNC) || IS_SYNC(inode))
2007                         status = generic_osync_inode(inode, mapping,
2008                                         OSYNC_METADATA|OSYNC_DATA);
2009         }
2010         
2011         /*
2012          * If we get here for O_DIRECT writes then we must have fallen through
2013          * to buffered writes (block instantiation inside i_size).  So we sync
2014          * the file data here, to try to honour O_DIRECT expectations.
2015          */
2016         if (unlikely(file->f_flags & O_DIRECT) && written)
2017                 status = filemap_write_and_wait(mapping);
2018
2019 out_status:     
2020         err = written ? written : status;
2021 out:
2022         pagevec_lru_add(&lru_pvec);
2023         current->backing_dev_info = NULL;
2024         return err;
2025 }
2026
2027 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2028
2029 ssize_t
2030 generic_file_write_nolock(struct file *file, const struct iovec *iov,
2031                                 unsigned long nr_segs, loff_t *ppos)
2032 {
2033         struct kiocb kiocb;
2034         ssize_t ret;
2035
2036         init_sync_kiocb(&kiocb, file);
2037         ret = generic_file_aio_write_nolock(&kiocb, iov, nr_segs, ppos);
2038         if (-EIOCBQUEUED == ret)
2039                 ret = wait_on_sync_kiocb(&kiocb);
2040         return ret;
2041 }
2042
2043 EXPORT_SYMBOL(generic_file_write_nolock);
2044
2045 ssize_t generic_file_aio_write(struct kiocb *iocb, const char __user *buf,
2046                                size_t count, loff_t pos)
2047 {
2048         struct file *file = iocb->ki_filp;
2049         struct inode *inode = file->f_mapping->host;
2050         ssize_t err;
2051         struct iovec local_iov = { .iov_base = (void __user *)buf, .iov_len = count };
2052
2053         BUG_ON(iocb->ki_pos != pos);
2054
2055         down(&inode->i_sem);
2056         err = generic_file_aio_write_nolock(iocb, &local_iov, 1, 
2057                                                 &iocb->ki_pos);
2058         up(&inode->i_sem);
2059
2060         return err;
2061 }
2062
2063 EXPORT_SYMBOL(generic_file_aio_write);
2064
2065 ssize_t generic_file_write(struct file *file, const char __user *buf,
2066                            size_t count, loff_t *ppos)
2067 {
2068         struct inode    *inode = file->f_mapping->host;
2069         ssize_t         err;
2070         struct iovec local_iov = { .iov_base = (void __user *)buf, .iov_len = count };
2071
2072         down(&inode->i_sem);
2073         err = generic_file_write_nolock(file, &local_iov, 1, ppos);
2074         up(&inode->i_sem);
2075
2076         return err;
2077 }
2078
2079 EXPORT_SYMBOL(generic_file_write);
2080
2081 ssize_t generic_file_readv(struct file *filp, const struct iovec *iov,
2082                         unsigned long nr_segs, loff_t *ppos)
2083 {
2084         struct kiocb kiocb;
2085         ssize_t ret;
2086
2087         init_sync_kiocb(&kiocb, filp);
2088         ret = __generic_file_aio_read(&kiocb, iov, nr_segs, ppos);
2089         if (-EIOCBQUEUED == ret)
2090                 ret = wait_on_sync_kiocb(&kiocb);
2091         return ret;
2092 }
2093
2094 EXPORT_SYMBOL(generic_file_readv);
2095
2096 ssize_t generic_file_writev(struct file *file, const struct iovec *iov,
2097                         unsigned long nr_segs, loff_t * ppos) 
2098 {
2099         struct inode *inode = file->f_mapping->host;
2100         ssize_t ret;
2101
2102         down(&inode->i_sem);
2103         ret = generic_file_write_nolock(file, iov, nr_segs, ppos);
2104         up(&inode->i_sem);
2105         return ret;
2106 }
2107
2108 EXPORT_SYMBOL(generic_file_writev);
2109
2110 /*
2111  * Called under i_sem for writes to S_ISREG files
2112  */
2113 ssize_t
2114 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2115         loff_t offset, unsigned long nr_segs)
2116 {
2117         struct file *file = iocb->ki_filp;
2118         struct address_space *mapping = file->f_mapping;
2119         ssize_t retval;
2120
2121         retval = filemap_write_and_wait(mapping);
2122         if (retval == 0) {
2123                 retval = mapping->a_ops->direct_IO(rw, iocb, iov,
2124                                                 offset, nr_segs);
2125                 if (rw == WRITE && mapping->nrpages)
2126                         invalidate_inode_pages2(mapping);
2127         }
2128         return retval;
2129 }
2130
2131 EXPORT_SYMBOL_GPL(generic_file_direct_IO);