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