Merge to Fedora Core 2 kernel-2.6.8-1.521
[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         spin_lock_irq(&mapping->tree_lock);
444         page = radix_tree_lookup(&mapping->page_tree, offset);
445         if (page)
446                 page_cache_get(page);
447         spin_unlock_irq(&mapping->tree_lock);
448         return page;
449 }
450
451 EXPORT_SYMBOL(find_get_page);
452
453 /*
454  * Same as above, but trylock it instead of incrementing the count.
455  */
456 struct page *find_trylock_page(struct address_space *mapping, unsigned long offset)
457 {
458         struct page *page;
459
460         spin_lock_irq(&mapping->tree_lock);
461         page = radix_tree_lookup(&mapping->page_tree, offset);
462         if (page && TestSetPageLocked(page))
463                 page = NULL;
464         spin_unlock_irq(&mapping->tree_lock);
465         return page;
466 }
467
468 EXPORT_SYMBOL(find_trylock_page);
469
470 /**
471  * find_lock_page - locate, pin and lock a pagecache page
472  *
473  * @mapping - the address_space to search
474  * @offset - the page index
475  *
476  * Locates the desired pagecache page, locks it, increments its reference
477  * count and returns its address.
478  *
479  * Returns zero if the page was not present. find_lock_page() may sleep.
480  */
481 struct page *find_lock_page(struct address_space *mapping,
482                                 unsigned long offset)
483 {
484         struct page *page;
485
486         spin_lock_irq(&mapping->tree_lock);
487 repeat:
488         page = radix_tree_lookup(&mapping->page_tree, offset);
489         if (page) {
490                 page_cache_get(page);
491                 if (TestSetPageLocked(page)) {
492                         spin_unlock_irq(&mapping->tree_lock);
493                         lock_page(page);
494                         spin_lock_irq(&mapping->tree_lock);
495
496                         /* Has the page been truncated while we slept? */
497                         if (page->mapping != mapping || page->index != offset) {
498                                 unlock_page(page);
499                                 page_cache_release(page);
500                                 goto repeat;
501                         }
502                 }
503         }
504         spin_unlock_irq(&mapping->tree_lock);
505         return page;
506 }
507
508 EXPORT_SYMBOL(find_lock_page);
509
510 /**
511  * find_or_create_page - locate or add a pagecache page
512  *
513  * @mapping - the page's address_space
514  * @index - the page's index into the mapping
515  * @gfp_mask - page allocation mode
516  *
517  * Locates a page in the pagecache.  If the page is not present, a new page
518  * is allocated using @gfp_mask and is added to the pagecache and to the VM's
519  * LRU list.  The returned page is locked and has its reference count
520  * incremented.
521  *
522  * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
523  * allocation!
524  *
525  * find_or_create_page() returns the desired page's address, or zero on
526  * memory exhaustion.
527  */
528 struct page *find_or_create_page(struct address_space *mapping,
529                 unsigned long index, unsigned int gfp_mask)
530 {
531         struct page *page, *cached_page = NULL;
532         int err;
533 repeat:
534         page = find_lock_page(mapping, index);
535         if (!page) {
536                 if (!cached_page) {
537                         cached_page = alloc_page(gfp_mask);
538                         if (!cached_page)
539                                 return NULL;
540                 }
541                 err = add_to_page_cache_lru(cached_page, mapping,
542                                         index, gfp_mask);
543                 if (!err) {
544                         page = cached_page;
545                         cached_page = NULL;
546                 } else if (err == -EEXIST)
547                         goto repeat;
548         }
549         if (cached_page)
550                 page_cache_release(cached_page);
551         return page;
552 }
553
554 EXPORT_SYMBOL(find_or_create_page);
555
556 /**
557  * find_get_pages - gang pagecache lookup
558  * @mapping:    The address_space to search
559  * @start:      The starting page index
560  * @nr_pages:   The maximum number of pages
561  * @pages:      Where the resulting pages are placed
562  *
563  * find_get_pages() will search for and return a group of up to
564  * @nr_pages pages in the mapping.  The pages are placed at @pages.
565  * find_get_pages() takes a reference against the returned pages.
566  *
567  * The search returns a group of mapping-contiguous pages with ascending
568  * indexes.  There may be holes in the indices due to not-present pages.
569  *
570  * find_get_pages() returns the number of pages which were found.
571  */
572 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
573                             unsigned int nr_pages, struct page **pages)
574 {
575         unsigned int i;
576         unsigned int ret;
577
578         spin_lock_irq(&mapping->tree_lock);
579         ret = radix_tree_gang_lookup(&mapping->page_tree,
580                                 (void **)pages, start, nr_pages);
581         for (i = 0; i < ret; i++)
582                 page_cache_get(pages[i]);
583         spin_unlock_irq(&mapping->tree_lock);
584         return ret;
585 }
586
587 /*
588  * Like find_get_pages, except we only return pages which are tagged with
589  * `tag'.   We update *index to index the next page for the traversal.
590  */
591 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
592                         int tag, unsigned int nr_pages, struct page **pages)
593 {
594         unsigned int i;
595         unsigned int ret;
596
597         spin_lock_irq(&mapping->tree_lock);
598         ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
599                                 (void **)pages, *index, nr_pages, tag);
600         for (i = 0; i < ret; i++)
601                 page_cache_get(pages[i]);
602         if (ret)
603                 *index = pages[ret - 1]->index + 1;
604         spin_unlock_irq(&mapping->tree_lock);
605         return ret;
606 }
607
608 /*
609  * Same as grab_cache_page, but do not wait if the page is unavailable.
610  * This is intended for speculative data generators, where the data can
611  * be regenerated if the page couldn't be grabbed.  This routine should
612  * be safe to call while holding the lock for another page.
613  *
614  * Clear __GFP_FS when allocating the page to avoid recursion into the fs
615  * and deadlock against the caller's locked page.
616  */
617 struct page *
618 grab_cache_page_nowait(struct address_space *mapping, unsigned long index)
619 {
620         struct page *page = find_get_page(mapping, index);
621         int gfp_mask;
622
623         if (page) {
624                 if (!TestSetPageLocked(page))
625                         return page;
626                 page_cache_release(page);
627                 return NULL;
628         }
629         gfp_mask = mapping_gfp_mask(mapping) & ~__GFP_FS;
630         page = alloc_pages(gfp_mask, 0);
631         if (page && add_to_page_cache_lru(page, mapping, index, gfp_mask)) {
632                 page_cache_release(page);
633                 page = NULL;
634         }
635         return page;
636 }
637
638 EXPORT_SYMBOL(grab_cache_page_nowait);
639
640 /*
641  * This is a generic file read routine, and uses the
642  * mapping->a_ops->readpage() function for the actual low-level
643  * stuff.
644  *
645  * This is really ugly. But the goto's actually try to clarify some
646  * of the logic when it comes to error handling etc.
647  * - note the struct file * is only passed for the use of readpage
648  */
649 void do_generic_mapping_read(struct address_space *mapping,
650                              struct file_ra_state *_ra,
651                              struct file * filp,
652                              loff_t *ppos,
653                              read_descriptor_t * desc,
654                              read_actor_t actor,
655                              int nonblock)
656 {
657         struct inode *inode = mapping->host;
658         unsigned long index, end_index, offset;
659         loff_t isize;
660         struct page *cached_page;
661         int error;
662         struct file_ra_state ra = *_ra;
663
664         cached_page = NULL;
665         index = *ppos >> PAGE_CACHE_SHIFT;
666         offset = *ppos & ~PAGE_CACHE_MASK;
667
668         isize = i_size_read(inode);
669         end_index = isize >> PAGE_CACHE_SHIFT;
670         if (index > end_index)
671                 goto out;
672
673         for (;;) {
674                 struct page *page;
675                 unsigned long nr, ret;
676
677                 cond_resched();
678                 page_cache_readahead(mapping, &ra, filp, index);
679
680 find_page:
681                 page = find_get_page(mapping, index);
682                 if (unlikely(page == NULL)) {
683                         if (nonblock) {
684                                 desc->error = -EWOULDBLOCKIO;
685                                 break;
686                         }
687                         handle_ra_miss(mapping, &ra, index);
688                         goto no_cached_page;
689                 }
690                 if (!PageUptodate(page)) {
691                         if (nonblock) {
692                                 page_cache_release(page);
693                                 desc->error = -EWOULDBLOCKIO;
694                                 break;
695                         }
696                         goto page_not_up_to_date;
697                 }
698 page_ok:
699                 /* nr is the maximum number of bytes to copy from this page */
700                 nr = PAGE_CACHE_SIZE;
701                 if (index == end_index) {
702                         nr = isize & ~PAGE_CACHE_MASK;
703                         if (nr <= offset) {
704                                 page_cache_release(page);
705                                 goto out;
706                         }
707                 }
708                 nr = nr - offset;
709
710                 /* If users can be writing to this page using arbitrary
711                  * virtual addresses, take care about potential aliasing
712                  * before reading the page on the kernel side.
713                  */
714                 if (mapping_writably_mapped(mapping))
715                         flush_dcache_page(page);
716
717                 /*
718                  * Mark the page accessed if we read the beginning.
719                  */
720                 if (!offset)
721                         mark_page_accessed(page);
722
723                 /*
724                  * Ok, we have the page, and it's up-to-date, so
725                  * now we can copy it to user space...
726                  *
727                  * The actor routine returns how many bytes were actually used..
728                  * NOTE! This may not be the same as how much of a user buffer
729                  * we filled up (we may be padding etc), so we can only update
730                  * "pos" here (the actor routine has to update the user buffer
731                  * pointers and the remaining count).
732                  */
733                 ret = actor(desc, page, offset, nr);
734                 offset += ret;
735                 index += offset >> PAGE_CACHE_SHIFT;
736                 offset &= ~PAGE_CACHE_MASK;
737
738                 page_cache_release(page);
739                 if (ret == nr && desc->count)
740                         continue;
741                 goto out;
742
743 page_not_up_to_date:
744                 /* Get exclusive access to the page ... */
745                 lock_page(page);
746
747                 /* Did it get unhashed before we got the lock? */
748                 if (!page->mapping) {
749                         unlock_page(page);
750                         page_cache_release(page);
751                         continue;
752                 }
753
754                 /* Did somebody else fill it already? */
755                 if (PageUptodate(page)) {
756                         unlock_page(page);
757                         goto page_ok;
758                 }
759
760 readpage:
761                 /* Start the actual read. The read will unlock the page. */
762                 error = mapping->a_ops->readpage(filp, page);
763
764                 if (unlikely(error))
765                         goto readpage_error;
766
767                 if (!PageUptodate(page)) {
768                         wait_on_page_locked(page);
769                         if (!PageUptodate(page)) {
770                                 error = -EIO;
771                                 goto readpage_error;
772                         }
773                 }
774
775                 /*
776                  * i_size must be checked after we have done ->readpage.
777                  *
778                  * Checking i_size after the readpage allows us to calculate
779                  * the correct value for "nr", which means the zero-filled
780                  * part of the page is not copied back to userspace (unless
781                  * another truncate extends the file - this is desired though).
782                  */
783                 isize = i_size_read(inode);
784                 end_index = isize >> PAGE_CACHE_SHIFT;
785                 if (index > end_index) {
786                         page_cache_release(page);
787                         goto out;
788                 }
789                 goto page_ok;
790
791 readpage_error:
792                 /* UHHUH! A synchronous read error occurred. Report it */
793                 desc->error = error;
794                 page_cache_release(page);
795                 goto out;
796
797 no_cached_page:
798                 /*
799                  * Ok, it wasn't cached, so we need to create a new
800                  * page..
801                  */
802                 if (!cached_page) {
803                         cached_page = page_cache_alloc_cold(mapping);
804                         if (!cached_page) {
805                                 desc->error = -ENOMEM;
806                                 goto out;
807                         }
808                 }
809                 error = add_to_page_cache_lru(cached_page, mapping,
810                                                 index, GFP_KERNEL);
811                 if (error) {
812                         if (error == -EEXIST)
813                                 goto find_page;
814                         desc->error = error;
815                         goto out;
816                 }
817                 page = cached_page;
818                 cached_page = NULL;
819                 goto readpage;
820         }
821
822 out:
823         *_ra = ra;
824
825         *ppos = ((loff_t) index << PAGE_CACHE_SHIFT) + offset;
826         if (cached_page)
827                 page_cache_release(cached_page);
828         file_accessed(filp);
829 }
830
831 EXPORT_SYMBOL(do_generic_mapping_read);
832
833 int file_read_actor(read_descriptor_t *desc, struct page *page,
834                         unsigned long offset, unsigned long size)
835 {
836         char *kaddr;
837         unsigned long left, count = desc->count;
838
839         if (size > count)
840                 size = count;
841
842         /*
843          * Faults on the destination of a read are common, so do it before
844          * taking the kmap.
845          */
846         if (!fault_in_pages_writeable(desc->arg.buf, size)) {
847                 kaddr = kmap_atomic(page, KM_USER0);
848                 left = __copy_to_user_inatomic(desc->arg.buf, kaddr + offset, size);
849                 kunmap_atomic(kaddr, KM_USER0);
850                 if (left == 0)
851                         goto success;
852         }
853
854         /* Do it the slow way */
855         kaddr = kmap(page);
856         left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
857         kunmap(page);
858
859         if (left) {
860                 size -= left;
861                 desc->error = -EFAULT;
862         }
863 success:
864         desc->count = count - size;
865         desc->written += size;
866         desc->arg.buf += size;
867         return size;
868 }
869
870 /*
871  * This is the "read()" routine for all filesystems
872  * that can use the page cache directly.
873  */
874 ssize_t
875 __generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
876                 unsigned long nr_segs, loff_t *ppos)
877 {
878         struct file *filp = iocb->ki_filp;
879         ssize_t retval;
880         unsigned long seg;
881         size_t count;
882
883         count = 0;
884         for (seg = 0; seg < nr_segs; seg++) {
885                 const struct iovec *iv = &iov[seg];
886
887                 /*
888                  * If any segment has a negative length, or the cumulative
889                  * length ever wraps negative then return -EINVAL.
890                  */
891                 count += iv->iov_len;
892                 if (unlikely((ssize_t)(count|iv->iov_len) < 0))
893                         return -EINVAL;
894                 if (access_ok(VERIFY_WRITE, iv->iov_base, iv->iov_len))
895                         continue;
896                 if (seg == 0)
897                         return -EFAULT;
898                 nr_segs = seg;
899                 count -= iv->iov_len;   /* This segment is no good */
900                 break;
901         }
902
903         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
904         if (filp->f_flags & O_DIRECT) {
905                 loff_t pos = *ppos, size;
906                 struct address_space *mapping;
907                 struct inode *inode;
908
909                 mapping = filp->f_mapping;
910                 inode = mapping->host;
911                 retval = 0;
912                 if (!count)
913                         goto out; /* skip atime */
914                 size = i_size_read(inode);
915                 if (pos < size) {
916                         retval = generic_file_direct_IO(READ, iocb,
917                                                 iov, pos, nr_segs);
918                         if (retval >= 0 && !is_sync_kiocb(iocb))
919                                 retval = -EIOCBQUEUED;
920                         if (retval > 0)
921                                 *ppos = pos + retval;
922                 }
923                 file_accessed(filp);
924                 goto out;
925         }
926
927         retval = 0;
928         if (count) {
929                 for (seg = 0; seg < nr_segs; seg++) {
930                         read_descriptor_t desc;
931
932                         desc.written = 0;
933                         desc.arg.buf = iov[seg].iov_base;
934                         desc.count = iov[seg].iov_len;
935                         if (desc.count == 0)
936                                 continue;
937                         desc.error = 0;
938                         do_generic_file_read(filp,ppos,&desc,file_read_actor,0);
939                         retval += desc.written;
940                         if (!retval) {
941                                 retval = desc.error;
942                                 break;
943                         }
944                 }
945         }
946 out:
947         return retval;
948 }
949
950 EXPORT_SYMBOL(__generic_file_aio_read);
951
952 ssize_t
953 generic_file_aio_read(struct kiocb *iocb, char __user *buf, size_t count, loff_t pos)
954 {
955         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
956
957         BUG_ON(iocb->ki_pos != pos);
958         return __generic_file_aio_read(iocb, &local_iov, 1, &iocb->ki_pos);
959 }
960
961 EXPORT_SYMBOL(generic_file_aio_read);
962
963 ssize_t
964 generic_file_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
965 {
966         struct iovec local_iov = { .iov_base = buf, .iov_len = count };
967         struct kiocb kiocb;
968         ssize_t ret;
969
970         init_sync_kiocb(&kiocb, filp);
971         ret = __generic_file_aio_read(&kiocb, &local_iov, 1, ppos);
972         if (-EIOCBQUEUED == ret)
973                 ret = wait_on_sync_kiocb(&kiocb);
974         return ret;
975 }
976
977 EXPORT_SYMBOL(generic_file_read);
978
979 int file_send_actor(read_descriptor_t * desc, struct page *page, unsigned long offset, unsigned long size)
980 {
981         ssize_t written;
982         unsigned long count = desc->count;
983         struct file *file = desc->arg.data;
984
985         if (size > count)
986                 size = count;
987
988         written = file->f_op->sendpage(file, page, offset,
989                                        size, &file->f_pos, size<count);
990         if (written < 0) {
991                 desc->error = written;
992                 written = 0;
993         }
994         desc->count = count - written;
995         desc->written += written;
996         return written;
997 }
998
999 ssize_t generic_file_sendfile(struct file *in_file, loff_t *ppos,
1000                          size_t count, read_actor_t actor, void *target)
1001 {
1002         read_descriptor_t desc;
1003
1004         if (!count)
1005                 return 0;
1006
1007         desc.written = 0;
1008         desc.count = count;
1009         desc.arg.data = target;
1010         desc.error = 0;
1011
1012         do_generic_file_read(in_file, ppos, &desc, actor, 0);
1013         if (desc.written)
1014                 return desc.written;
1015         return desc.error;
1016 }
1017
1018 EXPORT_SYMBOL(generic_file_sendfile);
1019
1020 static ssize_t
1021 do_readahead(struct address_space *mapping, struct file *filp,
1022              unsigned long index, unsigned long nr)
1023 {
1024         if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1025                 return -EINVAL;
1026
1027         force_page_cache_readahead(mapping, filp, index,
1028                                         max_sane_readahead(nr));
1029         return 0;
1030 }
1031
1032 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1033 {
1034         ssize_t ret;
1035         struct file *file;
1036
1037         ret = -EBADF;
1038         file = fget(fd);
1039         if (file) {
1040                 if (file->f_mode & FMODE_READ) {
1041                         struct address_space *mapping = file->f_mapping;
1042                         unsigned long start = offset >> PAGE_CACHE_SHIFT;
1043                         unsigned long end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1044                         unsigned long len = end - start + 1;
1045                         ret = do_readahead(mapping, file, start, len);
1046                 }
1047                 fput(file);
1048         }
1049         return ret;
1050 }
1051
1052 #ifdef CONFIG_MMU
1053 /*
1054  * This adds the requested page to the page cache if it isn't already there,
1055  * and schedules an I/O to read in its contents from disk.
1056  */
1057 static int FASTCALL(page_cache_read(struct file * file, unsigned long offset));
1058 static int fastcall page_cache_read(struct file * file, unsigned long offset)
1059 {
1060         struct address_space *mapping = file->f_mapping;
1061         struct page *page; 
1062         int error;
1063
1064         page = page_cache_alloc_cold(mapping);
1065         if (!page)
1066                 return -ENOMEM;
1067
1068         error = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1069         if (!error) {
1070                 error = mapping->a_ops->readpage(file, page);
1071                 page_cache_release(page);
1072                 return error;
1073         }
1074
1075         /*
1076          * We arrive here in the unlikely event that someone 
1077          * raced with us and added our page to the cache first
1078          * or we are out of memory for radix-tree nodes.
1079          */
1080         page_cache_release(page);
1081         return error == -EEXIST ? 0 : error;
1082 }
1083
1084 #define MMAP_LOTSAMISS  (100)
1085
1086 /*
1087  * filemap_nopage() is invoked via the vma operations vector for a
1088  * mapped memory region to read in file data during a page fault.
1089  *
1090  * The goto's are kind of ugly, but this streamlines the normal case of having
1091  * it in the page cache, and handles the special cases reasonably without
1092  * having a lot of duplicated code.
1093  */
1094 struct page * filemap_nopage(struct vm_area_struct * area, unsigned long address, int *type)
1095 {
1096         int error;
1097         struct file *file = area->vm_file;
1098         struct address_space *mapping = file->f_mapping;
1099         struct file_ra_state *ra = &file->f_ra;
1100         struct inode *inode = mapping->host;
1101         struct page *page;
1102         unsigned long size, pgoff, endoff;
1103         int did_readaround = 0, majmin = VM_FAULT_MINOR;
1104
1105         pgoff = ((address - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1106         endoff = ((area->vm_end - area->vm_start) >> PAGE_CACHE_SHIFT) + area->vm_pgoff;
1107
1108 retry_all:
1109         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1110         if (pgoff >= size)
1111                 goto outside_data_content;
1112
1113         /* If we don't want any read-ahead, don't bother */
1114         if (VM_RandomReadHint(area))
1115                 goto no_cached_page;
1116
1117         /*
1118          * The "size" of the file, as far as mmap is concerned, isn't bigger
1119          * than the mapping
1120          */
1121         if (size > endoff)
1122                 size = endoff;
1123
1124         /*
1125          * The readahead code wants to be told about each and every page
1126          * so it can build and shrink its windows appropriately
1127          *
1128          * For sequential accesses, we use the generic readahead logic.
1129          */
1130         if (VM_SequentialReadHint(area))
1131                 page_cache_readahead(mapping, ra, file, pgoff);
1132
1133         /*
1134          * Do we have something in the page cache already?
1135          */
1136 retry_find:
1137         page = find_get_page(mapping, pgoff);
1138         if (!page) {
1139                 unsigned long ra_pages;
1140
1141                 if (VM_SequentialReadHint(area)) {
1142                         handle_ra_miss(mapping, ra, pgoff);
1143                         goto no_cached_page;
1144                 }
1145                 ra->mmap_miss++;
1146
1147                 /*
1148                  * Do we miss much more than hit in this file? If so,
1149                  * stop bothering with read-ahead. It will only hurt.
1150                  */
1151                 if (ra->mmap_miss > ra->mmap_hit + MMAP_LOTSAMISS)
1152                         goto no_cached_page;
1153
1154                 /*
1155                  * To keep the pgmajfault counter straight, we need to
1156                  * check did_readaround, as this is an inner loop.
1157                  */
1158                 if (!did_readaround) {
1159                         majmin = VM_FAULT_MAJOR;
1160                         inc_page_state(pgmajfault);
1161                 }
1162                 did_readaround = 1;
1163                 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1164                 if (ra_pages) {
1165                         pgoff_t start = 0;
1166
1167                         if (pgoff > ra_pages / 2)
1168                                 start = pgoff - ra_pages / 2;
1169                         do_page_cache_readahead(mapping, file, start, ra_pages);
1170                 }
1171                 page = find_get_page(mapping, pgoff);
1172                 if (!page)
1173                         goto no_cached_page;
1174         }
1175
1176         if (!did_readaround)
1177                 ra->mmap_hit++;
1178
1179         /*
1180          * Ok, found a page in the page cache, now we need to check
1181          * that it's up-to-date.
1182          */
1183         if (!PageUptodate(page))
1184                 goto page_not_uptodate;
1185
1186 success:
1187         /*
1188          * Found the page and have a reference on it.
1189          */
1190         mark_page_accessed(page);
1191         if (type)
1192                 *type = majmin;
1193         return page;
1194
1195 outside_data_content:
1196         /*
1197          * An external ptracer can access pages that normally aren't
1198          * accessible..
1199          */
1200         if (area->vm_mm == current->mm)
1201                 return NULL;
1202         /* Fall through to the non-read-ahead case */
1203 no_cached_page:
1204         /*
1205          * We're only likely to ever get here if MADV_RANDOM is in
1206          * effect.
1207          */
1208         error = page_cache_read(file, pgoff);
1209         grab_swap_token();
1210
1211         /*
1212          * The page we want has now been added to the page cache.
1213          * In the unlikely event that someone removed it in the
1214          * meantime, we'll just come back here and read it again.
1215          */
1216         if (error >= 0)
1217                 goto retry_find;
1218
1219         /*
1220          * An error return from page_cache_read can result if the
1221          * system is low on memory, or a problem occurs while trying
1222          * to schedule I/O.
1223          */
1224         if (error == -ENOMEM)
1225                 return NOPAGE_OOM;
1226         return NULL;
1227
1228 page_not_uptodate:
1229         if (!did_readaround) {
1230                 majmin = VM_FAULT_MAJOR;
1231                 inc_page_state(pgmajfault);
1232         }
1233         lock_page(page);
1234
1235         /* Did it get unhashed while we waited for it? */
1236         if (!page->mapping) {
1237                 unlock_page(page);
1238                 page_cache_release(page);
1239                 goto retry_all;
1240         }
1241
1242         /* Did somebody else get it up-to-date? */
1243         if (PageUptodate(page)) {
1244                 unlock_page(page);
1245                 goto success;
1246         }
1247
1248         if (!mapping->a_ops->readpage(file, page)) {
1249                 wait_on_page_locked(page);
1250                 if (PageUptodate(page))
1251                         goto success;
1252         }
1253
1254         /*
1255          * Umm, take care of errors if the page isn't up-to-date.
1256          * Try to re-read it _once_. We do this synchronously,
1257          * because there really aren't any performance issues here
1258          * and we need to check for errors.
1259          */
1260         lock_page(page);
1261
1262         /* Somebody truncated the page on us? */
1263         if (!page->mapping) {
1264                 unlock_page(page);
1265                 page_cache_release(page);
1266                 goto retry_all;
1267         }
1268
1269         /* Somebody else successfully read it in? */
1270         if (PageUptodate(page)) {
1271                 unlock_page(page);
1272                 goto success;
1273         }
1274         ClearPageError(page);
1275         if (!mapping->a_ops->readpage(file, page)) {
1276                 wait_on_page_locked(page);
1277                 if (PageUptodate(page))
1278                         goto success;
1279         }
1280
1281         /*
1282          * Things didn't work out. Return zero to tell the
1283          * mm layer so, possibly freeing the page cache page first.
1284          */
1285         page_cache_release(page);
1286         return NULL;
1287 }
1288
1289 EXPORT_SYMBOL(filemap_nopage);
1290
1291 static struct page * filemap_getpage(struct file *file, unsigned long pgoff,
1292                                         int nonblock)
1293 {
1294         struct address_space *mapping = file->f_mapping;
1295         struct page *page;
1296         int error;
1297
1298         /*
1299          * Do we have something in the page cache already?
1300          */
1301 retry_find:
1302         page = find_get_page(mapping, pgoff);
1303         if (!page) {
1304                 if (nonblock)
1305                         return NULL;
1306                 goto no_cached_page;
1307         }
1308
1309         /*
1310          * Ok, found a page in the page cache, now we need to check
1311          * that it's up-to-date.
1312          */
1313         if (!PageUptodate(page))
1314                 goto page_not_uptodate;
1315
1316 success:
1317         /*
1318          * Found the page and have a reference on it.
1319          */
1320         mark_page_accessed(page);
1321         return page;
1322
1323 no_cached_page:
1324         error = page_cache_read(file, pgoff);
1325
1326         /*
1327          * The page we want has now been added to the page cache.
1328          * In the unlikely event that someone removed it in the
1329          * meantime, we'll just come back here and read it again.
1330          */
1331         if (error >= 0)
1332                 goto retry_find;
1333
1334         /*
1335          * An error return from page_cache_read can result if the
1336          * system is low on memory, or a problem occurs while trying
1337          * to schedule I/O.
1338          */
1339         return NULL;
1340
1341 page_not_uptodate:
1342         lock_page(page);
1343
1344         /* Did it get unhashed while we waited for it? */
1345         if (!page->mapping) {
1346                 unlock_page(page);
1347                 goto err;
1348         }
1349
1350         /* Did somebody else get it up-to-date? */
1351         if (PageUptodate(page)) {
1352                 unlock_page(page);
1353                 goto success;
1354         }
1355
1356         if (!mapping->a_ops->readpage(file, page)) {
1357                 wait_on_page_locked(page);
1358                 if (PageUptodate(page))
1359                         goto success;
1360         }
1361
1362         /*
1363          * Umm, take care of errors if the page isn't up-to-date.
1364          * Try to re-read it _once_. We do this synchronously,
1365          * because there really aren't any performance issues here
1366          * and we need to check for errors.
1367          */
1368         lock_page(page);
1369
1370         /* Somebody truncated the page on us? */
1371         if (!page->mapping) {
1372                 unlock_page(page);
1373                 goto err;
1374         }
1375         /* Somebody else successfully read it in? */
1376         if (PageUptodate(page)) {
1377                 unlock_page(page);
1378                 goto success;
1379         }
1380
1381         ClearPageError(page);
1382         if (!mapping->a_ops->readpage(file, page)) {
1383                 wait_on_page_locked(page);
1384                 if (PageUptodate(page))
1385                         goto success;
1386         }
1387
1388         /*
1389          * Things didn't work out. Return zero to tell the
1390          * mm layer so, possibly freeing the page cache page first.
1391          */
1392 err:
1393         page_cache_release(page);
1394
1395         return NULL;
1396 }
1397
1398 static int filemap_populate(struct vm_area_struct *vma,
1399                         unsigned long addr,
1400                         unsigned long len,
1401                         pgprot_t prot,
1402                         unsigned long pgoff,
1403                         int nonblock)
1404 {
1405         struct file *file = vma->vm_file;
1406         struct address_space *mapping = file->f_mapping;
1407         struct inode *inode = mapping->host;
1408         unsigned long size;
1409         struct mm_struct *mm = vma->vm_mm;
1410         struct page *page;
1411         int err;
1412
1413         if (!nonblock)
1414                 force_page_cache_readahead(mapping, vma->vm_file,
1415                                         pgoff, len >> PAGE_CACHE_SHIFT);
1416
1417 repeat:
1418         size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1419         if (pgoff + (len >> PAGE_CACHE_SHIFT) > size)
1420                 return -EINVAL;
1421
1422         page = filemap_getpage(file, pgoff, nonblock);
1423         if (!page && !nonblock)
1424                 return -ENOMEM;
1425         if (page) {
1426                 err = install_page(mm, vma, addr, page, prot);
1427                 if (err) {
1428                         page_cache_release(page);
1429                         return err;
1430                 }
1431         } else {
1432                 err = install_file_pte(mm, vma, addr, pgoff, prot);
1433                 if (err)
1434                         return err;
1435         }
1436
1437         len -= PAGE_SIZE;
1438         addr += PAGE_SIZE;
1439         pgoff++;
1440         if (len)
1441                 goto repeat;
1442
1443         return 0;
1444 }
1445
1446 static struct vm_operations_struct generic_file_vm_ops = {
1447         .nopage         = filemap_nopage,
1448         .populate       = filemap_populate,
1449 };
1450
1451 /* This is used for a general mmap of a disk file */
1452
1453 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1454 {
1455         struct address_space *mapping = file->f_mapping;
1456
1457         if (!mapping->a_ops->readpage)
1458                 return -ENOEXEC;
1459         file_accessed(file);
1460         vma->vm_ops = &generic_file_vm_ops;
1461         return 0;
1462 }
1463
1464 /*
1465  * This is for filesystems which do not implement ->writepage.
1466  */
1467 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1468 {
1469         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1470                 return -EINVAL;
1471         return generic_file_mmap(file, vma);
1472 }
1473 #else
1474 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1475 {
1476         return -ENOSYS;
1477 }
1478 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1479 {
1480         return -ENOSYS;
1481 }
1482 #endif /* CONFIG_MMU */
1483
1484 EXPORT_SYMBOL(generic_file_mmap);
1485 EXPORT_SYMBOL(generic_file_readonly_mmap);
1486
1487 static inline struct page *__read_cache_page(struct address_space *mapping,
1488                                 unsigned long index,
1489                                 int (*filler)(void *,struct page*),
1490                                 void *data)
1491 {
1492         struct page *page, *cached_page = NULL;
1493         int err;
1494 repeat:
1495         page = find_get_page(mapping, index);
1496         if (!page) {
1497                 if (!cached_page) {
1498                         cached_page = page_cache_alloc_cold(mapping);
1499                         if (!cached_page)
1500                                 return ERR_PTR(-ENOMEM);
1501                 }
1502                 err = add_to_page_cache_lru(cached_page, mapping,
1503                                         index, GFP_KERNEL);
1504                 if (err == -EEXIST)
1505                         goto repeat;
1506                 if (err < 0) {
1507                         /* Presumably ENOMEM for radix tree node */
1508                         page_cache_release(cached_page);
1509                         return ERR_PTR(err);
1510                 }
1511                 page = cached_page;
1512                 cached_page = NULL;
1513                 err = filler(data, page);
1514                 if (err < 0) {
1515                         page_cache_release(page);
1516                         page = ERR_PTR(err);
1517                 }
1518         }
1519         if (cached_page)
1520                 page_cache_release(cached_page);
1521         return page;
1522 }
1523
1524 /*
1525  * Read into the page cache. If a page already exists,
1526  * and PageUptodate() is not set, try to fill the page.
1527  */
1528 struct page *read_cache_page(struct address_space *mapping,
1529                                 unsigned long index,
1530                                 int (*filler)(void *,struct page*),
1531                                 void *data)
1532 {
1533         struct page *page;
1534         int err;
1535
1536 retry:
1537         page = __read_cache_page(mapping, index, filler, data);
1538         if (IS_ERR(page))
1539                 goto out;
1540         mark_page_accessed(page);
1541         if (PageUptodate(page))
1542                 goto out;
1543
1544         lock_page(page);
1545         if (!page->mapping) {
1546                 unlock_page(page);
1547                 page_cache_release(page);
1548                 goto retry;
1549         }
1550         if (PageUptodate(page)) {
1551                 unlock_page(page);
1552                 goto out;
1553         }
1554         err = filler(data, page);
1555         if (err < 0) {
1556                 page_cache_release(page);
1557                 page = ERR_PTR(err);
1558         }
1559  out:
1560         return page;
1561 }
1562
1563 EXPORT_SYMBOL(read_cache_page);
1564
1565 /*
1566  * If the page was newly created, increment its refcount and add it to the
1567  * caller's lru-buffering pagevec.  This function is specifically for
1568  * generic_file_write().
1569  */
1570 static inline struct page *
1571 __grab_cache_page(struct address_space *mapping, unsigned long index,
1572                         struct page **cached_page, struct pagevec *lru_pvec)
1573 {
1574         int err;
1575         struct page *page;
1576 repeat:
1577         page = find_lock_page(mapping, index);
1578         if (!page) {
1579                 if (!*cached_page) {
1580                         *cached_page = page_cache_alloc(mapping);
1581                         if (!*cached_page)
1582                                 return NULL;
1583                 }
1584                 err = add_to_page_cache(*cached_page, mapping,
1585                                         index, GFP_KERNEL);
1586                 if (err == -EEXIST)
1587                         goto repeat;
1588                 if (err == 0) {
1589                         page = *cached_page;
1590                         page_cache_get(page);
1591                         if (!pagevec_add(lru_pvec, page))
1592                                 __pagevec_lru_add(lru_pvec);
1593                         *cached_page = NULL;
1594                 }
1595         }
1596         return page;
1597 }
1598
1599 /*
1600  * The logic we want is
1601  *
1602  *      if suid or (sgid and xgrp)
1603  *              remove privs
1604  */
1605 int remove_suid(struct dentry *dentry)
1606 {
1607         mode_t mode = dentry->d_inode->i_mode;
1608         int kill = 0;
1609         int result = 0;
1610
1611         /* suid always must be killed */
1612         if (unlikely(mode & S_ISUID))
1613                 kill = ATTR_KILL_SUID;
1614
1615         /*
1616          * sgid without any exec bits is just a mandatory locking mark; leave
1617          * it alone.  If some exec bits are set, it's a real sgid; kill it.
1618          */
1619         if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1620                 kill |= ATTR_KILL_SGID;
1621
1622         if (unlikely(kill && !capable(CAP_FSETID))) {
1623                 struct iattr newattrs;
1624
1625                 newattrs.ia_valid = ATTR_FORCE | kill;
1626                 result = notify_change(dentry, &newattrs);
1627         }
1628         return result;
1629 }
1630 EXPORT_SYMBOL(remove_suid);
1631
1632 /*
1633  * Copy as much as we can into the page and return the number of bytes which
1634  * were sucessfully copied.  If a fault is encountered then clear the page
1635  * out to (offset+bytes) and return the number of bytes which were copied.
1636  */
1637 static inline size_t
1638 filemap_copy_from_user(struct page *page, unsigned long offset,
1639                         const char __user *buf, unsigned bytes)
1640 {
1641         char *kaddr;
1642         int left;
1643
1644         kaddr = kmap_atomic(page, KM_USER0);
1645         left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
1646         kunmap_atomic(kaddr, KM_USER0);
1647
1648         if (left != 0) {
1649                 /* Do it the slow way */
1650                 kaddr = kmap(page);
1651                 left = __copy_from_user(kaddr + offset, buf, bytes);
1652                 kunmap(page);
1653         }
1654         return bytes - left;
1655 }
1656
1657 static size_t
1658 __filemap_copy_from_user_iovec(char *vaddr, 
1659                         const struct iovec *iov, size_t base, size_t bytes)
1660 {
1661         size_t copied = 0, left = 0;
1662
1663         while (bytes) {
1664                 char __user *buf = iov->iov_base + base;
1665                 int copy = min(bytes, iov->iov_len - base);
1666
1667                 base = 0;
1668                 left = __copy_from_user_inatomic(vaddr, buf, copy);
1669                 copied += copy;
1670                 bytes -= copy;
1671                 vaddr += copy;
1672                 iov++;
1673
1674                 if (unlikely(left)) {
1675                         /* zero the rest of the target like __copy_from_user */
1676                         if (bytes)
1677                                 memset(vaddr, 0, bytes);
1678                         break;
1679                 }
1680         }
1681         return copied - left;
1682 }
1683
1684 /*
1685  * This has the same sideeffects and return value as filemap_copy_from_user().
1686  * The difference is that on a fault we need to memset the remainder of the
1687  * page (out to offset+bytes), to emulate filemap_copy_from_user()'s
1688  * single-segment behaviour.
1689  */
1690 static inline size_t
1691 filemap_copy_from_user_iovec(struct page *page, unsigned long offset,
1692                         const struct iovec *iov, size_t base, size_t bytes)
1693 {
1694         char *kaddr;
1695         size_t copied;
1696
1697         kaddr = kmap_atomic(page, KM_USER0);
1698         copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1699                                                 base, bytes);
1700         kunmap_atomic(kaddr, KM_USER0);
1701         if (copied != bytes) {
1702                 kaddr = kmap(page);
1703                 copied = __filemap_copy_from_user_iovec(kaddr + offset, iov,
1704                                                         base, bytes);
1705                 kunmap(page);
1706         }
1707         return copied;
1708 }
1709
1710 static inline void
1711 filemap_set_next_iovec(const struct iovec **iovp, size_t *basep, size_t bytes)
1712 {
1713         const struct iovec *iov = *iovp;
1714         size_t base = *basep;
1715
1716         while (bytes) {
1717                 int copy = min(bytes, iov->iov_len - base);
1718
1719                 bytes -= copy;
1720                 base += copy;
1721                 if (iov->iov_len == base) {
1722                         iov++;
1723                         base = 0;
1724                 }
1725         }
1726         *iovp = iov;
1727         *basep = base;
1728 }
1729
1730 /*
1731  * Performs necessary checks before doing a write
1732  *
1733  * Can adjust writing position aor amount of bytes to write.
1734  * Returns appropriate error code that caller should return or
1735  * zero in case that write should be allowed.
1736  */
1737 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1738 {
1739         struct inode *inode = file->f_mapping->host;
1740         unsigned long limit = current->rlim[RLIMIT_FSIZE].rlim_cur;
1741
1742         if (unlikely(*pos < 0))
1743                 return -EINVAL;
1744
1745         if (unlikely(file->f_error)) {
1746                 int err = file->f_error;
1747                 file->f_error = 0;
1748                 return err;
1749         }
1750
1751         if (!isblk) {
1752                 /* FIXME: this is for backwards compatibility with 2.4 */
1753                 if (file->f_flags & O_APPEND)
1754                         *pos = i_size_read(inode);
1755
1756                 if (limit != RLIM_INFINITY) {
1757                         if (*pos >= limit) {
1758                                 send_sig(SIGXFSZ, current, 0);
1759                                 return -EFBIG;
1760                         }
1761                         if (*count > limit - (typeof(limit))*pos) {
1762                                 *count = limit - (typeof(limit))*pos;
1763                         }
1764                 }
1765         }
1766
1767         /*
1768          * LFS rule
1769          */
1770         if (unlikely(*pos + *count > MAX_NON_LFS &&
1771                                 !(file->f_flags & O_LARGEFILE))) {
1772                 if (*pos >= MAX_NON_LFS) {
1773                         send_sig(SIGXFSZ, current, 0);
1774                         return -EFBIG;
1775                 }
1776                 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1777                         *count = MAX_NON_LFS - (unsigned long)*pos;
1778                 }
1779         }
1780
1781         /*
1782          * Are we about to exceed the fs block limit ?
1783          *
1784          * If we have written data it becomes a short write.  If we have
1785          * exceeded without writing data we send a signal and return EFBIG.
1786          * Linus frestrict idea will clean these up nicely..
1787          */
1788         if (likely(!isblk)) {
1789                 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1790                         if (*count || *pos > inode->i_sb->s_maxbytes) {
1791                                 send_sig(SIGXFSZ, current, 0);
1792                                 return -EFBIG;
1793                         }
1794                         /* zero-length writes at ->s_maxbytes are OK */
1795                 }
1796
1797                 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1798                         *count = inode->i_sb->s_maxbytes - *pos;
1799         } else {
1800                 loff_t isize;
1801                 if (bdev_read_only(I_BDEV(inode)))
1802                         return -EPERM;
1803                 isize = i_size_read(inode);
1804                 if (*pos >= isize) {
1805                         if (*count || *pos > isize)
1806                                 return -ENOSPC;
1807                 }
1808
1809                 if (*pos + *count > isize)
1810                         *count = isize - *pos;
1811         }
1812         return 0;
1813 }
1814
1815 EXPORT_SYMBOL(generic_write_checks);
1816
1817 /*
1818  * Write to a file through the page cache. 
1819  * Called under i_sem for S_ISREG files.
1820  *
1821  * We put everything into the page cache prior to writing it. This is not a
1822  * problem when writing full pages. With partial pages, however, we first have
1823  * to read the data into the cache, then dirty the page, and finally schedule
1824  * it for writing by marking it dirty.
1825  *                                                      okir@monad.swb.de
1826  */
1827 ssize_t
1828 generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
1829                                 unsigned long nr_segs, loff_t *ppos)
1830 {
1831         struct file *file = iocb->ki_filp;
1832         struct address_space * mapping = file->f_mapping;
1833         struct address_space_operations *a_ops = mapping->a_ops;
1834         size_t ocount;          /* original count */
1835         size_t count;           /* after file limit checks */
1836         struct inode    *inode = mapping->host;
1837         long            status = 0;
1838         loff_t          pos;
1839         struct page     *page;
1840         struct page     *cached_page = NULL;
1841         const int       isblk = S_ISBLK(inode->i_mode);
1842         ssize_t         written;
1843         ssize_t         err;
1844         size_t          bytes;
1845         struct pagevec  lru_pvec;
1846         const struct iovec *cur_iov = iov; /* current iovec */
1847         size_t          iov_base = 0;      /* offset in the current iovec */
1848         unsigned long   seg;
1849         char __user     *buf;
1850
1851         ocount = 0;
1852         for (seg = 0; seg < nr_segs; seg++) {
1853                 const struct iovec *iv = &iov[seg];
1854
1855                 /*
1856                  * If any segment has a negative length, or the cumulative
1857                  * length ever wraps negative then return -EINVAL.
1858                  */
1859                 ocount += iv->iov_len;
1860                 if (unlikely((ssize_t)(ocount|iv->iov_len) < 0))
1861                         return -EINVAL;
1862                 if (access_ok(VERIFY_READ, iv->iov_base, iv->iov_len))
1863                         continue;
1864                 if (seg == 0)
1865                         return -EFAULT;
1866                 nr_segs = seg;
1867                 ocount -= iv->iov_len;  /* This segment is no good */
1868                 break;
1869         }
1870
1871         count = ocount;
1872         pos = *ppos;
1873         pagevec_init(&lru_pvec, 0);
1874
1875         /* We can write back this queue in page reclaim */
1876         current->backing_dev_info = mapping->backing_dev_info;
1877         written = 0;
1878
1879         err = generic_write_checks(file, &pos, &count, isblk);
1880         if (err)
1881                 goto out;
1882
1883         if (count == 0)
1884                 goto out;
1885
1886         err = remove_suid(file->f_dentry);
1887         if (err)
1888                 goto out;
1889
1890         inode_update_time(inode, 1);
1891
1892         /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1893         if (unlikely(file->f_flags & O_DIRECT)) {
1894                 if (count != ocount)
1895                         nr_segs = iov_shorten((struct iovec *)iov,
1896                                                 nr_segs, count);
1897                 written = generic_file_direct_IO(WRITE, iocb,
1898                                         iov, pos, nr_segs);
1899                 if (written > 0) {
1900                         loff_t end = pos + written;
1901                         if (end > i_size_read(inode) && !isblk) {
1902                                 i_size_write(inode,  end);
1903                                 mark_inode_dirty(inode);
1904                         }
1905                         *ppos = end;
1906                 }
1907                 /*
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.
1912                  */
1913                 if (written >= 0 && file->f_flags & O_SYNC)
1914                         status = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1915                 if (written == count && !is_sync_kiocb(iocb))
1916                         written = -EIOCBQUEUED;
1917                 if (written < 0 || written == count)
1918                         goto out_status;
1919                 /*
1920                  * direct-io write to a hole: fall through to buffered I/O
1921                  * for completing the rest of the request.
1922                  */
1923                 pos += written;
1924                 count -= written;
1925         }
1926
1927         buf = iov->iov_base + written;  /* handle partial DIO write */
1928         do {
1929                 unsigned long index;
1930                 unsigned long offset;
1931                 size_t copied;
1932
1933                 offset = (pos & (PAGE_CACHE_SIZE -1)); /* Within page */
1934                 index = pos >> PAGE_CACHE_SHIFT;
1935                 bytes = PAGE_CACHE_SIZE - offset;
1936                 if (bytes > count)
1937                         bytes = count;
1938
1939                 /*
1940                  * Bring in the user page that we will copy from _first_.
1941                  * Otherwise there's a nasty deadlock on copying from the
1942                  * same page as we're writing to, without it being marked
1943                  * up-to-date.
1944                  */
1945                 fault_in_pages_readable(buf, bytes);
1946
1947                 page = __grab_cache_page(mapping,index,&cached_page,&lru_pvec);
1948                 if (!page) {
1949                         status = -ENOMEM;
1950                         break;
1951                 }
1952
1953                 status = a_ops->prepare_write(file, page, offset, offset+bytes);
1954                 if (unlikely(status)) {
1955                         loff_t isize = i_size_read(inode);
1956                         /*
1957                          * prepare_write() may have instantiated a few blocks
1958                          * outside i_size.  Trim these off again.
1959                          */
1960                         unlock_page(page);
1961                         page_cache_release(page);
1962                         if (pos + bytes > isize)
1963                                 vmtruncate(inode, isize);
1964                         break;
1965                 }
1966                 if (likely(nr_segs == 1))
1967                         copied = filemap_copy_from_user(page, offset,
1968                                                         buf, bytes);
1969                 else
1970                         copied = filemap_copy_from_user_iovec(page, offset,
1971                                                 cur_iov, iov_base, bytes);
1972                 flush_dcache_page(page);
1973                 status = a_ops->commit_write(file, page, offset, offset+bytes);
1974                 if (likely(copied > 0)) {
1975                         if (!status)
1976                                 status = copied;
1977
1978                         if (status >= 0) {
1979                                 written += status;
1980                                 count -= status;
1981                                 pos += status;
1982                                 buf += status;
1983                                 if (unlikely(nr_segs > 1))
1984                                         filemap_set_next_iovec(&cur_iov,
1985                                                         &iov_base, status);
1986                         }
1987                 }
1988                 if (unlikely(copied != bytes))
1989                         if (status >= 0)
1990                                 status = -EFAULT;
1991                 unlock_page(page);
1992                 mark_page_accessed(page);
1993                 page_cache_release(page);
1994                 if (status < 0)
1995                         break;
1996                 balance_dirty_pages_ratelimited(mapping);
1997                 cond_resched();
1998         } while (count);
1999         *ppos = pos;
2000
2001         if (cached_page)
2002                 page_cache_release(cached_page);
2003
2004         /*
2005          * For now, when the user asks for O_SYNC, we'll actually give O_DSYNC
2006          */
2007         if (status >= 0) {
2008                 if ((file->f_flags & O_SYNC) || IS_SYNC(inode))
2009                         status = generic_osync_inode(inode, mapping,
2010                                         OSYNC_METADATA|OSYNC_DATA);
2011         }
2012         
2013         /*
2014          * If we get here for O_DIRECT writes then we must have fallen through
2015          * to buffered writes (block instantiation inside i_size).  So we sync
2016          * the file data here, to try to honour O_DIRECT expectations.
2017          */
2018         if (unlikely(file->f_flags & O_DIRECT) && written)
2019                 status = filemap_write_and_wait(mapping);
2020
2021 out_status:     
2022         err = written ? written : status;
2023 out:
2024         pagevec_lru_add(&lru_pvec);
2025         current->backing_dev_info = NULL;
2026         return err;
2027 }
2028
2029 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2030
2031 ssize_t
2032 generic_file_write_nolock(struct file *file, const struct iovec *iov,
2033                                 unsigned long nr_segs, loff_t *ppos)
2034 {
2035         struct kiocb kiocb;
2036         ssize_t ret;
2037
2038         init_sync_kiocb(&kiocb, file);
2039         ret = generic_file_aio_write_nolock(&kiocb, iov, nr_segs, ppos);
2040         if (-EIOCBQUEUED == ret)
2041                 ret = wait_on_sync_kiocb(&kiocb);
2042         return ret;
2043 }
2044
2045 EXPORT_SYMBOL(generic_file_write_nolock);
2046
2047 ssize_t generic_file_aio_write(struct kiocb *iocb, const char __user *buf,
2048                                size_t count, loff_t pos)
2049 {
2050         struct file *file = iocb->ki_filp;
2051         struct inode *inode = file->f_mapping->host;
2052         ssize_t err;
2053         struct iovec local_iov = { .iov_base = (void __user *)buf, .iov_len = count };
2054
2055         BUG_ON(iocb->ki_pos != pos);
2056
2057         down(&inode->i_sem);
2058         err = generic_file_aio_write_nolock(iocb, &local_iov, 1, 
2059                                                 &iocb->ki_pos);
2060         up(&inode->i_sem);
2061
2062         return err;
2063 }
2064
2065 EXPORT_SYMBOL(generic_file_aio_write);
2066
2067 ssize_t generic_file_write(struct file *file, const char __user *buf,
2068                            size_t count, loff_t *ppos)
2069 {
2070         struct inode    *inode = file->f_mapping->host;
2071         ssize_t         err;
2072         struct iovec local_iov = { .iov_base = (void __user *)buf, .iov_len = count };
2073
2074         down(&inode->i_sem);
2075         err = generic_file_write_nolock(file, &local_iov, 1, ppos);
2076         up(&inode->i_sem);
2077
2078         return err;
2079 }
2080
2081 EXPORT_SYMBOL(generic_file_write);
2082
2083 ssize_t generic_file_readv(struct file *filp, const struct iovec *iov,
2084                         unsigned long nr_segs, loff_t *ppos)
2085 {
2086         struct kiocb kiocb;
2087         ssize_t ret;
2088
2089         init_sync_kiocb(&kiocb, filp);
2090         ret = __generic_file_aio_read(&kiocb, iov, nr_segs, ppos);
2091         if (-EIOCBQUEUED == ret)
2092                 ret = wait_on_sync_kiocb(&kiocb);
2093         return ret;
2094 }
2095
2096 EXPORT_SYMBOL(generic_file_readv);
2097
2098 ssize_t generic_file_writev(struct file *file, const struct iovec *iov,
2099                         unsigned long nr_segs, loff_t * ppos) 
2100 {
2101         struct inode *inode = file->f_mapping->host;
2102         ssize_t ret;
2103
2104         down(&inode->i_sem);
2105         ret = generic_file_write_nolock(file, iov, nr_segs, ppos);
2106         up(&inode->i_sem);
2107         return ret;
2108 }
2109
2110 EXPORT_SYMBOL(generic_file_writev);
2111
2112 /*
2113  * Called under i_sem for writes to S_ISREG files
2114  */
2115 ssize_t
2116 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2117         loff_t offset, unsigned long nr_segs)
2118 {
2119         struct file *file = iocb->ki_filp;
2120         struct address_space *mapping = file->f_mapping;
2121         ssize_t retval;
2122
2123         retval = filemap_write_and_wait(mapping);
2124         if (retval == 0) {
2125                 retval = mapping->a_ops->direct_IO(rw, iocb, iov,
2126                                                 offset, nr_segs);
2127                 if (rw == WRITE && mapping->nrpages)
2128                         invalidate_inode_pages2(mapping);
2129         }
2130         return retval;
2131 }
2132
2133 EXPORT_SYMBOL_GPL(generic_file_direct_IO);