Merge branch 'release' of git://git.kernel.org/pub/scm/linux/kernel/git/aegl/linux-2.6
[linux-block.git] / mm / filemap.c
CommitLineData
1da177e4
LT
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 */
1da177e4
LT
12#include <linux/module.h>
13#include <linux/slab.h>
14#include <linux/compiler.h>
15#include <linux/fs.h>
c22ce143 16#include <linux/uaccess.h>
1da177e4 17#include <linux/aio.h>
c59ede7b 18#include <linux/capability.h>
1da177e4
LT
19#include <linux/kernel_stat.h>
20#include <linux/mm.h>
21#include <linux/swap.h>
22#include <linux/mman.h>
23#include <linux/pagemap.h>
24#include <linux/file.h>
25#include <linux/uio.h>
26#include <linux/hash.h>
27#include <linux/writeback.h>
53253383 28#include <linux/backing-dev.h>
1da177e4
LT
29#include <linux/pagevec.h>
30#include <linux/blkdev.h>
3a424f2d 31#include <linux/backing-dev.h>
1da177e4
LT
32#include <linux/security.h>
33#include <linux/syscalls.h>
44110fe3 34#include <linux/cpuset.h>
2f718ffc 35#include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
0f8053a5
NP
36#include "internal.h"
37
1da177e4 38/*
1da177e4
LT
39 * FIXME: remove all knowledge of the buffer layer from the core VM
40 */
41#include <linux/buffer_head.h> /* for generic_osync_inode */
42
1da177e4
LT
43#include <asm/mman.h>
44
5ce7852c
AB
45static ssize_t
46generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
47 loff_t offset, unsigned long nr_segs);
48
1da177e4
LT
49/*
50 * Shared mappings implemented 30.11.1994. It's not fully working yet,
51 * though.
52 *
53 * Shared mappings now work. 15.8.1995 Bruno.
54 *
55 * finished 'unifying' the page and buffer cache and SMP-threaded the
56 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
57 *
58 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
59 */
60
61/*
62 * Lock ordering:
63 *
64 * ->i_mmap_lock (vmtruncate)
65 * ->private_lock (__free_pte->__set_page_dirty_buffers)
5d337b91
HD
66 * ->swap_lock (exclusive_swap_page, others)
67 * ->mapping->tree_lock
7a405079 68 * ->zone.lock
1da177e4 69 *
1b1dcc1b 70 * ->i_mutex
1da177e4
LT
71 * ->i_mmap_lock (truncate->unmap_mapping_range)
72 *
73 * ->mmap_sem
74 * ->i_mmap_lock
b8072f09 75 * ->page_table_lock or pte_lock (various, mainly in memory.c)
1da177e4
LT
76 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
77 *
78 * ->mmap_sem
79 * ->lock_page (access_process_vm)
80 *
82591e6e
NP
81 * ->i_mutex (generic_file_buffered_write)
82 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
1da177e4 83 *
1b1dcc1b 84 * ->i_mutex
1da177e4
LT
85 * ->i_alloc_sem (various)
86 *
87 * ->inode_lock
88 * ->sb_lock (fs/fs-writeback.c)
89 * ->mapping->tree_lock (__sync_single_inode)
90 *
91 * ->i_mmap_lock
92 * ->anon_vma.lock (vma_adjust)
93 *
94 * ->anon_vma.lock
b8072f09 95 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
1da177e4 96 *
b8072f09 97 * ->page_table_lock or pte_lock
5d337b91 98 * ->swap_lock (try_to_unmap_one)
1da177e4
LT
99 * ->private_lock (try_to_unmap_one)
100 * ->tree_lock (try_to_unmap_one)
101 * ->zone.lru_lock (follow_page->mark_page_accessed)
053837fc 102 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
1da177e4
LT
103 * ->private_lock (page_remove_rmap->set_page_dirty)
104 * ->tree_lock (page_remove_rmap->set_page_dirty)
105 * ->inode_lock (page_remove_rmap->set_page_dirty)
106 * ->inode_lock (zap_pte_range->set_page_dirty)
107 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
108 *
109 * ->task->proc_lock
110 * ->dcache_lock (proc_pid_lookup)
111 */
112
113/*
114 * Remove a page from the page cache and free it. Caller has to make
115 * sure the page is locked and that nobody else uses it - or that usage
116 * is safe. The caller must hold a write_lock on the mapping's tree_lock.
117 */
118void __remove_from_page_cache(struct page *page)
119{
120 struct address_space *mapping = page->mapping;
121
122 radix_tree_delete(&mapping->page_tree, page->index);
123 page->mapping = NULL;
124 mapping->nrpages--;
347ce434 125 __dec_zone_page_state(page, NR_FILE_PAGES);
45426812 126 BUG_ON(page_mapped(page));
1da177e4
LT
127}
128
129void remove_from_page_cache(struct page *page)
130{
131 struct address_space *mapping = page->mapping;
132
cd7619d6 133 BUG_ON(!PageLocked(page));
1da177e4
LT
134
135 write_lock_irq(&mapping->tree_lock);
136 __remove_from_page_cache(page);
137 write_unlock_irq(&mapping->tree_lock);
138}
139
140static int sync_page(void *word)
141{
142 struct address_space *mapping;
143 struct page *page;
144
07808b74 145 page = container_of((unsigned long *)word, struct page, flags);
1da177e4
LT
146
147 /*
dd1d5afc
WLII
148 * page_mapping() is being called without PG_locked held.
149 * Some knowledge of the state and use of the page is used to
150 * reduce the requirements down to a memory barrier.
151 * The danger here is of a stale page_mapping() return value
152 * indicating a struct address_space different from the one it's
153 * associated with when it is associated with one.
154 * After smp_mb(), it's either the correct page_mapping() for
155 * the page, or an old page_mapping() and the page's own
156 * page_mapping() has gone NULL.
157 * The ->sync_page() address_space operation must tolerate
158 * page_mapping() going NULL. By an amazing coincidence,
159 * this comes about because none of the users of the page
160 * in the ->sync_page() methods make essential use of the
161 * page_mapping(), merely passing the page down to the backing
162 * device's unplug functions when it's non-NULL, which in turn
4c21e2f2 163 * ignore it for all cases but swap, where only page_private(page) is
dd1d5afc
WLII
164 * of interest. When page_mapping() does go NULL, the entire
165 * call stack gracefully ignores the page and returns.
166 * -- wli
1da177e4
LT
167 */
168 smp_mb();
169 mapping = page_mapping(page);
170 if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
171 mapping->a_ops->sync_page(page);
172 io_schedule();
173 return 0;
174}
175
176/**
485bb99b 177 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
67be2dd1
MW
178 * @mapping: address space structure to write
179 * @start: offset in bytes where the range starts
469eb4d0 180 * @end: offset in bytes where the range ends (inclusive)
67be2dd1 181 * @sync_mode: enable synchronous operation
1da177e4 182 *
485bb99b
RD
183 * Start writeback against all of a mapping's dirty pages that lie
184 * within the byte offsets <start, end> inclusive.
185 *
1da177e4 186 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
485bb99b 187 * opposed to a regular memory cleansing writeback. The difference between
1da177e4
LT
188 * these two operations is that if a dirty page/buffer is encountered, it must
189 * be waited upon, and not just skipped over.
190 */
ebcf28e1
AM
191int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
192 loff_t end, int sync_mode)
1da177e4
LT
193{
194 int ret;
195 struct writeback_control wbc = {
196 .sync_mode = sync_mode,
197 .nr_to_write = mapping->nrpages * 2,
111ebb6e
OH
198 .range_start = start,
199 .range_end = end,
1da177e4
LT
200 };
201
202 if (!mapping_cap_writeback_dirty(mapping))
203 return 0;
204
205 ret = do_writepages(mapping, &wbc);
206 return ret;
207}
208
209static inline int __filemap_fdatawrite(struct address_space *mapping,
210 int sync_mode)
211{
111ebb6e 212 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
1da177e4
LT
213}
214
215int filemap_fdatawrite(struct address_space *mapping)
216{
217 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
218}
219EXPORT_SYMBOL(filemap_fdatawrite);
220
ebcf28e1
AM
221static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
222 loff_t end)
1da177e4
LT
223{
224 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
225}
226
485bb99b
RD
227/**
228 * filemap_flush - mostly a non-blocking flush
229 * @mapping: target address_space
230 *
1da177e4
LT
231 * This is a mostly non-blocking flush. Not suitable for data-integrity
232 * purposes - I/O may not be started against all dirty pages.
233 */
234int filemap_flush(struct address_space *mapping)
235{
236 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
237}
238EXPORT_SYMBOL(filemap_flush);
239
485bb99b
RD
240/**
241 * wait_on_page_writeback_range - wait for writeback to complete
242 * @mapping: target address_space
243 * @start: beginning page index
244 * @end: ending page index
245 *
1da177e4
LT
246 * Wait for writeback to complete against pages indexed by start->end
247 * inclusive
248 */
ebcf28e1 249int wait_on_page_writeback_range(struct address_space *mapping,
1da177e4
LT
250 pgoff_t start, pgoff_t end)
251{
252 struct pagevec pvec;
253 int nr_pages;
254 int ret = 0;
255 pgoff_t index;
256
257 if (end < start)
258 return 0;
259
260 pagevec_init(&pvec, 0);
261 index = start;
262 while ((index <= end) &&
263 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
264 PAGECACHE_TAG_WRITEBACK,
265 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
266 unsigned i;
267
268 for (i = 0; i < nr_pages; i++) {
269 struct page *page = pvec.pages[i];
270
271 /* until radix tree lookup accepts end_index */
272 if (page->index > end)
273 continue;
274
275 wait_on_page_writeback(page);
276 if (PageError(page))
277 ret = -EIO;
278 }
279 pagevec_release(&pvec);
280 cond_resched();
281 }
282
283 /* Check for outstanding write errors */
284 if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
285 ret = -ENOSPC;
286 if (test_and_clear_bit(AS_EIO, &mapping->flags))
287 ret = -EIO;
288
289 return ret;
290}
291
485bb99b
RD
292/**
293 * sync_page_range - write and wait on all pages in the passed range
294 * @inode: target inode
295 * @mapping: target address_space
296 * @pos: beginning offset in pages to write
297 * @count: number of bytes to write
298 *
1da177e4
LT
299 * Write and wait upon all the pages in the passed range. This is a "data
300 * integrity" operation. It waits upon in-flight writeout before starting and
301 * waiting upon new writeout. If there was an IO error, return it.
302 *
1b1dcc1b 303 * We need to re-take i_mutex during the generic_osync_inode list walk because
1da177e4
LT
304 * it is otherwise livelockable.
305 */
306int sync_page_range(struct inode *inode, struct address_space *mapping,
268fc16e 307 loff_t pos, loff_t count)
1da177e4
LT
308{
309 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
310 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
311 int ret;
312
313 if (!mapping_cap_writeback_dirty(mapping) || !count)
314 return 0;
315 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
316 if (ret == 0) {
1b1dcc1b 317 mutex_lock(&inode->i_mutex);
1da177e4 318 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1b1dcc1b 319 mutex_unlock(&inode->i_mutex);
1da177e4
LT
320 }
321 if (ret == 0)
322 ret = wait_on_page_writeback_range(mapping, start, end);
323 return ret;
324}
325EXPORT_SYMBOL(sync_page_range);
326
485bb99b
RD
327/**
328 * sync_page_range_nolock
329 * @inode: target inode
330 * @mapping: target address_space
331 * @pos: beginning offset in pages to write
332 * @count: number of bytes to write
333 *
72fd4a35 334 * Note: Holding i_mutex across sync_page_range_nolock() is not a good idea
1da177e4
LT
335 * as it forces O_SYNC writers to different parts of the same file
336 * to be serialised right until io completion.
337 */
268fc16e
OH
338int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
339 loff_t pos, loff_t count)
1da177e4
LT
340{
341 pgoff_t start = pos >> PAGE_CACHE_SHIFT;
342 pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
343 int ret;
344
345 if (!mapping_cap_writeback_dirty(mapping) || !count)
346 return 0;
347 ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
348 if (ret == 0)
349 ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
350 if (ret == 0)
351 ret = wait_on_page_writeback_range(mapping, start, end);
352 return ret;
353}
268fc16e 354EXPORT_SYMBOL(sync_page_range_nolock);
1da177e4
LT
355
356/**
485bb99b 357 * filemap_fdatawait - wait for all under-writeback pages to complete
1da177e4 358 * @mapping: address space structure to wait for
485bb99b
RD
359 *
360 * Walk the list of under-writeback pages of the given address space
361 * and wait for all of them.
1da177e4
LT
362 */
363int filemap_fdatawait(struct address_space *mapping)
364{
365 loff_t i_size = i_size_read(mapping->host);
366
367 if (i_size == 0)
368 return 0;
369
370 return wait_on_page_writeback_range(mapping, 0,
371 (i_size - 1) >> PAGE_CACHE_SHIFT);
372}
373EXPORT_SYMBOL(filemap_fdatawait);
374
375int filemap_write_and_wait(struct address_space *mapping)
376{
28fd1298 377 int err = 0;
1da177e4
LT
378
379 if (mapping->nrpages) {
28fd1298
OH
380 err = filemap_fdatawrite(mapping);
381 /*
382 * Even if the above returned error, the pages may be
383 * written partially (e.g. -ENOSPC), so we wait for it.
384 * But the -EIO is special case, it may indicate the worst
385 * thing (e.g. bug) happened, so we avoid waiting for it.
386 */
387 if (err != -EIO) {
388 int err2 = filemap_fdatawait(mapping);
389 if (!err)
390 err = err2;
391 }
1da177e4 392 }
28fd1298 393 return err;
1da177e4 394}
28fd1298 395EXPORT_SYMBOL(filemap_write_and_wait);
1da177e4 396
485bb99b
RD
397/**
398 * filemap_write_and_wait_range - write out & wait on a file range
399 * @mapping: the address_space for the pages
400 * @lstart: offset in bytes where the range starts
401 * @lend: offset in bytes where the range ends (inclusive)
402 *
469eb4d0
AM
403 * Write out and wait upon file offsets lstart->lend, inclusive.
404 *
405 * Note that `lend' is inclusive (describes the last byte to be written) so
406 * that this function can be used to write to the very end-of-file (end = -1).
407 */
1da177e4
LT
408int filemap_write_and_wait_range(struct address_space *mapping,
409 loff_t lstart, loff_t lend)
410{
28fd1298 411 int err = 0;
1da177e4
LT
412
413 if (mapping->nrpages) {
28fd1298
OH
414 err = __filemap_fdatawrite_range(mapping, lstart, lend,
415 WB_SYNC_ALL);
416 /* See comment of filemap_write_and_wait() */
417 if (err != -EIO) {
418 int err2 = wait_on_page_writeback_range(mapping,
419 lstart >> PAGE_CACHE_SHIFT,
420 lend >> PAGE_CACHE_SHIFT);
421 if (!err)
422 err = err2;
423 }
1da177e4 424 }
28fd1298 425 return err;
1da177e4
LT
426}
427
485bb99b
RD
428/**
429 * add_to_page_cache - add newly allocated pagecache pages
430 * @page: page to add
431 * @mapping: the page's address_space
432 * @offset: page index
433 * @gfp_mask: page allocation mode
434 *
435 * This function is used to add newly allocated pagecache pages;
1da177e4
LT
436 * the page is new, so we can just run SetPageLocked() against it.
437 * The other page state flags were set by rmqueue().
438 *
439 * This function does not add the page to the LRU. The caller must do that.
440 */
441int add_to_page_cache(struct page *page, struct address_space *mapping,
6daa0e28 442 pgoff_t offset, gfp_t gfp_mask)
1da177e4
LT
443{
444 int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
445
446 if (error == 0) {
447 write_lock_irq(&mapping->tree_lock);
448 error = radix_tree_insert(&mapping->page_tree, offset, page);
449 if (!error) {
450 page_cache_get(page);
451 SetPageLocked(page);
452 page->mapping = mapping;
453 page->index = offset;
454 mapping->nrpages++;
347ce434 455 __inc_zone_page_state(page, NR_FILE_PAGES);
1da177e4
LT
456 }
457 write_unlock_irq(&mapping->tree_lock);
458 radix_tree_preload_end();
459 }
460 return error;
461}
1da177e4
LT
462EXPORT_SYMBOL(add_to_page_cache);
463
464int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
6daa0e28 465 pgoff_t offset, gfp_t gfp_mask)
1da177e4
LT
466{
467 int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
468 if (ret == 0)
469 lru_cache_add(page);
470 return ret;
471}
472
44110fe3 473#ifdef CONFIG_NUMA
2ae88149 474struct page *__page_cache_alloc(gfp_t gfp)
44110fe3
PJ
475{
476 if (cpuset_do_page_mem_spread()) {
477 int n = cpuset_mem_spread_node();
2ae88149 478 return alloc_pages_node(n, gfp, 0);
44110fe3 479 }
2ae88149 480 return alloc_pages(gfp, 0);
44110fe3 481}
2ae88149 482EXPORT_SYMBOL(__page_cache_alloc);
44110fe3
PJ
483#endif
484
db37648c
NP
485static int __sleep_on_page_lock(void *word)
486{
487 io_schedule();
488 return 0;
489}
490
1da177e4
LT
491/*
492 * In order to wait for pages to become available there must be
493 * waitqueues associated with pages. By using a hash table of
494 * waitqueues where the bucket discipline is to maintain all
495 * waiters on the same queue and wake all when any of the pages
496 * become available, and for the woken contexts to check to be
497 * sure the appropriate page became available, this saves space
498 * at a cost of "thundering herd" phenomena during rare hash
499 * collisions.
500 */
501static wait_queue_head_t *page_waitqueue(struct page *page)
502{
503 const struct zone *zone = page_zone(page);
504
505 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
506}
507
508static inline void wake_up_page(struct page *page, int bit)
509{
510 __wake_up_bit(page_waitqueue(page), &page->flags, bit);
511}
512
513void fastcall wait_on_page_bit(struct page *page, int bit_nr)
514{
515 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
516
517 if (test_bit(bit_nr, &page->flags))
518 __wait_on_bit(page_waitqueue(page), &wait, sync_page,
519 TASK_UNINTERRUPTIBLE);
520}
521EXPORT_SYMBOL(wait_on_page_bit);
522
523/**
485bb99b 524 * unlock_page - unlock a locked page
1da177e4
LT
525 * @page: the page
526 *
527 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
528 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
529 * mechananism between PageLocked pages and PageWriteback pages is shared.
530 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
531 *
532 * The first mb is necessary to safely close the critical section opened by the
533 * TestSetPageLocked(), the second mb is necessary to enforce ordering between
534 * the clear_bit and the read of the waitqueue (to avoid SMP races with a
535 * parallel wait_on_page_locked()).
536 */
537void fastcall unlock_page(struct page *page)
538{
539 smp_mb__before_clear_bit();
540 if (!TestClearPageLocked(page))
541 BUG();
542 smp_mb__after_clear_bit();
543 wake_up_page(page, PG_locked);
544}
545EXPORT_SYMBOL(unlock_page);
546
485bb99b
RD
547/**
548 * end_page_writeback - end writeback against a page
549 * @page: the page
1da177e4
LT
550 */
551void end_page_writeback(struct page *page)
552{
553 if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
554 if (!test_clear_page_writeback(page))
555 BUG();
556 }
557 smp_mb__after_clear_bit();
558 wake_up_page(page, PG_writeback);
559}
560EXPORT_SYMBOL(end_page_writeback);
561
485bb99b
RD
562/**
563 * __lock_page - get a lock on the page, assuming we need to sleep to get it
564 * @page: the page to lock
1da177e4 565 *
485bb99b 566 * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
1da177e4
LT
567 * random driver's requestfn sets TASK_RUNNING, we could busywait. However
568 * chances are that on the second loop, the block layer's plug list is empty,
569 * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
570 */
571void fastcall __lock_page(struct page *page)
572{
573 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
574
575 __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
576 TASK_UNINTERRUPTIBLE);
577}
578EXPORT_SYMBOL(__lock_page);
579
db37648c
NP
580/*
581 * Variant of lock_page that does not require the caller to hold a reference
582 * on the page's mapping.
583 */
584void fastcall __lock_page_nosync(struct page *page)
585{
586 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
587 __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
588 TASK_UNINTERRUPTIBLE);
589}
590
485bb99b
RD
591/**
592 * find_get_page - find and get a page reference
593 * @mapping: the address_space to search
594 * @offset: the page index
595 *
da6052f7
NP
596 * Is there a pagecache struct page at the given (mapping, offset) tuple?
597 * If yes, increment its refcount and return it; if no, return NULL.
1da177e4 598 */
57f6b96c 599struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
1da177e4
LT
600{
601 struct page *page;
602
603 read_lock_irq(&mapping->tree_lock);
604 page = radix_tree_lookup(&mapping->page_tree, offset);
605 if (page)
606 page_cache_get(page);
607 read_unlock_irq(&mapping->tree_lock);
608 return page;
609}
1da177e4
LT
610EXPORT_SYMBOL(find_get_page);
611
1da177e4
LT
612/**
613 * find_lock_page - locate, pin and lock a pagecache page
67be2dd1
MW
614 * @mapping: the address_space to search
615 * @offset: the page index
1da177e4
LT
616 *
617 * Locates the desired pagecache page, locks it, increments its reference
618 * count and returns its address.
619 *
620 * Returns zero if the page was not present. find_lock_page() may sleep.
621 */
622struct page *find_lock_page(struct address_space *mapping,
57f6b96c 623 pgoff_t offset)
1da177e4
LT
624{
625 struct page *page;
626
1da177e4 627repeat:
45726cb4 628 read_lock_irq(&mapping->tree_lock);
1da177e4
LT
629 page = radix_tree_lookup(&mapping->page_tree, offset);
630 if (page) {
631 page_cache_get(page);
632 if (TestSetPageLocked(page)) {
633 read_unlock_irq(&mapping->tree_lock);
bbfbb7ce 634 __lock_page(page);
1da177e4
LT
635
636 /* Has the page been truncated while we slept? */
45726cb4 637 if (unlikely(page->mapping != mapping)) {
1da177e4
LT
638 unlock_page(page);
639 page_cache_release(page);
640 goto repeat;
641 }
45726cb4
NP
642 VM_BUG_ON(page->index != offset);
643 goto out;
1da177e4
LT
644 }
645 }
646 read_unlock_irq(&mapping->tree_lock);
45726cb4 647out:
1da177e4
LT
648 return page;
649}
1da177e4
LT
650EXPORT_SYMBOL(find_lock_page);
651
652/**
653 * find_or_create_page - locate or add a pagecache page
67be2dd1
MW
654 * @mapping: the page's address_space
655 * @index: the page's index into the mapping
656 * @gfp_mask: page allocation mode
1da177e4
LT
657 *
658 * Locates a page in the pagecache. If the page is not present, a new page
659 * is allocated using @gfp_mask and is added to the pagecache and to the VM's
660 * LRU list. The returned page is locked and has its reference count
661 * incremented.
662 *
663 * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
664 * allocation!
665 *
666 * find_or_create_page() returns the desired page's address, or zero on
667 * memory exhaustion.
668 */
669struct page *find_or_create_page(struct address_space *mapping,
57f6b96c 670 pgoff_t index, gfp_t gfp_mask)
1da177e4 671{
eb2be189 672 struct page *page;
1da177e4
LT
673 int err;
674repeat:
675 page = find_lock_page(mapping, index);
676 if (!page) {
eb2be189
NP
677 page = __page_cache_alloc(gfp_mask);
678 if (!page)
679 return NULL;
680 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
681 if (unlikely(err)) {
682 page_cache_release(page);
683 page = NULL;
684 if (err == -EEXIST)
685 goto repeat;
1da177e4 686 }
1da177e4 687 }
1da177e4
LT
688 return page;
689}
1da177e4
LT
690EXPORT_SYMBOL(find_or_create_page);
691
692/**
693 * find_get_pages - gang pagecache lookup
694 * @mapping: The address_space to search
695 * @start: The starting page index
696 * @nr_pages: The maximum number of pages
697 * @pages: Where the resulting pages are placed
698 *
699 * find_get_pages() will search for and return a group of up to
700 * @nr_pages pages in the mapping. The pages are placed at @pages.
701 * find_get_pages() takes a reference against the returned pages.
702 *
703 * The search returns a group of mapping-contiguous pages with ascending
704 * indexes. There may be holes in the indices due to not-present pages.
705 *
706 * find_get_pages() returns the number of pages which were found.
707 */
708unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
709 unsigned int nr_pages, struct page **pages)
710{
711 unsigned int i;
712 unsigned int ret;
713
714 read_lock_irq(&mapping->tree_lock);
715 ret = radix_tree_gang_lookup(&mapping->page_tree,
716 (void **)pages, start, nr_pages);
717 for (i = 0; i < ret; i++)
718 page_cache_get(pages[i]);
719 read_unlock_irq(&mapping->tree_lock);
720 return ret;
721}
722
ebf43500
JA
723/**
724 * find_get_pages_contig - gang contiguous pagecache lookup
725 * @mapping: The address_space to search
726 * @index: The starting page index
727 * @nr_pages: The maximum number of pages
728 * @pages: Where the resulting pages are placed
729 *
730 * find_get_pages_contig() works exactly like find_get_pages(), except
731 * that the returned number of pages are guaranteed to be contiguous.
732 *
733 * find_get_pages_contig() returns the number of pages which were found.
734 */
735unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
736 unsigned int nr_pages, struct page **pages)
737{
738 unsigned int i;
739 unsigned int ret;
740
741 read_lock_irq(&mapping->tree_lock);
742 ret = radix_tree_gang_lookup(&mapping->page_tree,
743 (void **)pages, index, nr_pages);
744 for (i = 0; i < ret; i++) {
745 if (pages[i]->mapping == NULL || pages[i]->index != index)
746 break;
747
748 page_cache_get(pages[i]);
749 index++;
750 }
751 read_unlock_irq(&mapping->tree_lock);
752 return i;
753}
ef71c15c 754EXPORT_SYMBOL(find_get_pages_contig);
ebf43500 755
485bb99b
RD
756/**
757 * find_get_pages_tag - find and return pages that match @tag
758 * @mapping: the address_space to search
759 * @index: the starting page index
760 * @tag: the tag index
761 * @nr_pages: the maximum number of pages
762 * @pages: where the resulting pages are placed
763 *
1da177e4 764 * Like find_get_pages, except we only return pages which are tagged with
485bb99b 765 * @tag. We update @index to index the next page for the traversal.
1da177e4
LT
766 */
767unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
768 int tag, unsigned int nr_pages, struct page **pages)
769{
770 unsigned int i;
771 unsigned int ret;
772
773 read_lock_irq(&mapping->tree_lock);
774 ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
775 (void **)pages, *index, nr_pages, tag);
776 for (i = 0; i < ret; i++)
777 page_cache_get(pages[i]);
778 if (ret)
779 *index = pages[ret - 1]->index + 1;
780 read_unlock_irq(&mapping->tree_lock);
781 return ret;
782}
ef71c15c 783EXPORT_SYMBOL(find_get_pages_tag);
1da177e4 784
485bb99b
RD
785/**
786 * grab_cache_page_nowait - returns locked page at given index in given cache
787 * @mapping: target address_space
788 * @index: the page index
789 *
72fd4a35 790 * Same as grab_cache_page(), but do not wait if the page is unavailable.
1da177e4
LT
791 * This is intended for speculative data generators, where the data can
792 * be regenerated if the page couldn't be grabbed. This routine should
793 * be safe to call while holding the lock for another page.
794 *
795 * Clear __GFP_FS when allocating the page to avoid recursion into the fs
796 * and deadlock against the caller's locked page.
797 */
798struct page *
57f6b96c 799grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
1da177e4
LT
800{
801 struct page *page = find_get_page(mapping, index);
1da177e4
LT
802
803 if (page) {
804 if (!TestSetPageLocked(page))
805 return page;
806 page_cache_release(page);
807 return NULL;
808 }
2ae88149
NP
809 page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
810 if (page && add_to_page_cache_lru(page, mapping, index, GFP_KERNEL)) {
1da177e4
LT
811 page_cache_release(page);
812 page = NULL;
813 }
814 return page;
815}
1da177e4
LT
816EXPORT_SYMBOL(grab_cache_page_nowait);
817
76d42bd9
WF
818/*
819 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
820 * a _large_ part of the i/o request. Imagine the worst scenario:
821 *
822 * ---R__________________________________________B__________
823 * ^ reading here ^ bad block(assume 4k)
824 *
825 * read(R) => miss => readahead(R...B) => media error => frustrating retries
826 * => failing the whole request => read(R) => read(R+1) =>
827 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
828 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
829 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
830 *
831 * It is going insane. Fix it by quickly scaling down the readahead size.
832 */
833static void shrink_readahead_size_eio(struct file *filp,
834 struct file_ra_state *ra)
835{
836 if (!ra->ra_pages)
837 return;
838
839 ra->ra_pages /= 4;
76d42bd9
WF
840}
841
485bb99b
RD
842/**
843 * do_generic_mapping_read - generic file read routine
844 * @mapping: address_space to be read
8f731f7d 845 * @ra: file's readahead state
485bb99b
RD
846 * @filp: the file to read
847 * @ppos: current file position
848 * @desc: read_descriptor
849 * @actor: read method
850 *
1da177e4 851 * This is a generic file read routine, and uses the
485bb99b 852 * mapping->a_ops->readpage() function for the actual low-level stuff.
1da177e4
LT
853 *
854 * This is really ugly. But the goto's actually try to clarify some
855 * of the logic when it comes to error handling etc.
856 *
485bb99b
RD
857 * Note the struct file* is only passed for the use of readpage.
858 * It may be NULL.
1da177e4
LT
859 */
860void do_generic_mapping_read(struct address_space *mapping,
7ff81078 861 struct file_ra_state *ra,
1da177e4
LT
862 struct file *filp,
863 loff_t *ppos,
864 read_descriptor_t *desc,
865 read_actor_t actor)
866{
867 struct inode *inode = mapping->host;
57f6b96c
FW
868 pgoff_t index;
869 pgoff_t last_index;
870 pgoff_t prev_index;
871 unsigned long offset; /* offset into pagecache page */
ec0f1637 872 unsigned int prev_offset;
1da177e4 873 int error;
1da177e4 874
1da177e4 875 index = *ppos >> PAGE_CACHE_SHIFT;
7ff81078
FW
876 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
877 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1da177e4
LT
878 last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
879 offset = *ppos & ~PAGE_CACHE_MASK;
880
1da177e4
LT
881 for (;;) {
882 struct page *page;
57f6b96c 883 pgoff_t end_index;
a32ea1e1 884 loff_t isize;
1da177e4
LT
885 unsigned long nr, ret;
886
1da177e4 887 cond_resched();
1da177e4
LT
888find_page:
889 page = find_get_page(mapping, index);
3ea89ee8 890 if (!page) {
cf914a7d 891 page_cache_sync_readahead(mapping,
7ff81078 892 ra, filp,
3ea89ee8
FW
893 index, last_index - index);
894 page = find_get_page(mapping, index);
895 if (unlikely(page == NULL))
896 goto no_cached_page;
897 }
898 if (PageReadahead(page)) {
cf914a7d 899 page_cache_async_readahead(mapping,
7ff81078 900 ra, filp, page,
3ea89ee8 901 index, last_index - index);
1da177e4
LT
902 }
903 if (!PageUptodate(page))
904 goto page_not_up_to_date;
905page_ok:
a32ea1e1
N
906 /*
907 * i_size must be checked after we know the page is Uptodate.
908 *
909 * Checking i_size after the check allows us to calculate
910 * the correct value for "nr", which means the zero-filled
911 * part of the page is not copied back to userspace (unless
912 * another truncate extends the file - this is desired though).
913 */
914
915 isize = i_size_read(inode);
916 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
917 if (unlikely(!isize || index > end_index)) {
918 page_cache_release(page);
919 goto out;
920 }
921
922 /* nr is the maximum number of bytes to copy from this page */
923 nr = PAGE_CACHE_SIZE;
924 if (index == end_index) {
925 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
926 if (nr <= offset) {
927 page_cache_release(page);
928 goto out;
929 }
930 }
931 nr = nr - offset;
1da177e4
LT
932
933 /* If users can be writing to this page using arbitrary
934 * virtual addresses, take care about potential aliasing
935 * before reading the page on the kernel side.
936 */
937 if (mapping_writably_mapped(mapping))
938 flush_dcache_page(page);
939
940 /*
ec0f1637
JK
941 * When a sequential read accesses a page several times,
942 * only mark it as accessed the first time.
1da177e4 943 */
ec0f1637 944 if (prev_index != index || offset != prev_offset)
1da177e4
LT
945 mark_page_accessed(page);
946 prev_index = index;
947
948 /*
949 * Ok, we have the page, and it's up-to-date, so
950 * now we can copy it to user space...
951 *
952 * The actor routine returns how many bytes were actually used..
953 * NOTE! This may not be the same as how much of a user buffer
954 * we filled up (we may be padding etc), so we can only update
955 * "pos" here (the actor routine has to update the user buffer
956 * pointers and the remaining count).
957 */
958 ret = actor(desc, page, offset, nr);
959 offset += ret;
960 index += offset >> PAGE_CACHE_SHIFT;
961 offset &= ~PAGE_CACHE_MASK;
6ce745ed 962 prev_offset = offset;
1da177e4
LT
963
964 page_cache_release(page);
965 if (ret == nr && desc->count)
966 continue;
967 goto out;
968
969page_not_up_to_date:
970 /* Get exclusive access to the page ... */
971 lock_page(page);
972
da6052f7 973 /* Did it get truncated before we got the lock? */
1da177e4
LT
974 if (!page->mapping) {
975 unlock_page(page);
976 page_cache_release(page);
977 continue;
978 }
979
980 /* Did somebody else fill it already? */
981 if (PageUptodate(page)) {
982 unlock_page(page);
983 goto page_ok;
984 }
985
986readpage:
987 /* Start the actual read. The read will unlock the page. */
988 error = mapping->a_ops->readpage(filp, page);
989
994fc28c
ZB
990 if (unlikely(error)) {
991 if (error == AOP_TRUNCATED_PAGE) {
992 page_cache_release(page);
993 goto find_page;
994 }
1da177e4 995 goto readpage_error;
994fc28c 996 }
1da177e4
LT
997
998 if (!PageUptodate(page)) {
999 lock_page(page);
1000 if (!PageUptodate(page)) {
1001 if (page->mapping == NULL) {
1002 /*
1003 * invalidate_inode_pages got it
1004 */
1005 unlock_page(page);
1006 page_cache_release(page);
1007 goto find_page;
1008 }
1009 unlock_page(page);
1010 error = -EIO;
7ff81078 1011 shrink_readahead_size_eio(filp, ra);
1da177e4
LT
1012 goto readpage_error;
1013 }
1014 unlock_page(page);
1015 }
1016
1da177e4
LT
1017 goto page_ok;
1018
1019readpage_error:
1020 /* UHHUH! A synchronous read error occurred. Report it */
1021 desc->error = error;
1022 page_cache_release(page);
1023 goto out;
1024
1025no_cached_page:
1026 /*
1027 * Ok, it wasn't cached, so we need to create a new
1028 * page..
1029 */
eb2be189
NP
1030 page = page_cache_alloc_cold(mapping);
1031 if (!page) {
1032 desc->error = -ENOMEM;
1033 goto out;
1da177e4 1034 }
eb2be189 1035 error = add_to_page_cache_lru(page, mapping,
1da177e4
LT
1036 index, GFP_KERNEL);
1037 if (error) {
eb2be189 1038 page_cache_release(page);
1da177e4
LT
1039 if (error == -EEXIST)
1040 goto find_page;
1041 desc->error = error;
1042 goto out;
1043 }
1da177e4
LT
1044 goto readpage;
1045 }
1046
1047out:
7ff81078
FW
1048 ra->prev_pos = prev_index;
1049 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1050 ra->prev_pos |= prev_offset;
1da177e4 1051
f4e6b498 1052 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1da177e4
LT
1053 if (filp)
1054 file_accessed(filp);
1055}
1da177e4
LT
1056EXPORT_SYMBOL(do_generic_mapping_read);
1057
1058int file_read_actor(read_descriptor_t *desc, struct page *page,
1059 unsigned long offset, unsigned long size)
1060{
1061 char *kaddr;
1062 unsigned long left, count = desc->count;
1063
1064 if (size > count)
1065 size = count;
1066
1067 /*
1068 * Faults on the destination of a read are common, so do it before
1069 * taking the kmap.
1070 */
1071 if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1072 kaddr = kmap_atomic(page, KM_USER0);
1073 left = __copy_to_user_inatomic(desc->arg.buf,
1074 kaddr + offset, size);
1075 kunmap_atomic(kaddr, KM_USER0);
1076 if (left == 0)
1077 goto success;
1078 }
1079
1080 /* Do it the slow way */
1081 kaddr = kmap(page);
1082 left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1083 kunmap(page);
1084
1085 if (left) {
1086 size -= left;
1087 desc->error = -EFAULT;
1088 }
1089success:
1090 desc->count = count - size;
1091 desc->written += size;
1092 desc->arg.buf += size;
1093 return size;
1094}
1095
0ceb3314
DM
1096/*
1097 * Performs necessary checks before doing a write
1098 * @iov: io vector request
1099 * @nr_segs: number of segments in the iovec
1100 * @count: number of bytes to write
1101 * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1102 *
1103 * Adjust number of segments and amount of bytes to write (nr_segs should be
1104 * properly initialized first). Returns appropriate error code that caller
1105 * should return or zero in case that write should be allowed.
1106 */
1107int generic_segment_checks(const struct iovec *iov,
1108 unsigned long *nr_segs, size_t *count, int access_flags)
1109{
1110 unsigned long seg;
1111 size_t cnt = 0;
1112 for (seg = 0; seg < *nr_segs; seg++) {
1113 const struct iovec *iv = &iov[seg];
1114
1115 /*
1116 * If any segment has a negative length, or the cumulative
1117 * length ever wraps negative then return -EINVAL.
1118 */
1119 cnt += iv->iov_len;
1120 if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1121 return -EINVAL;
1122 if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1123 continue;
1124 if (seg == 0)
1125 return -EFAULT;
1126 *nr_segs = seg;
1127 cnt -= iv->iov_len; /* This segment is no good */
1128 break;
1129 }
1130 *count = cnt;
1131 return 0;
1132}
1133EXPORT_SYMBOL(generic_segment_checks);
1134
485bb99b 1135/**
b2abacf3 1136 * generic_file_aio_read - generic filesystem read routine
485bb99b
RD
1137 * @iocb: kernel I/O control block
1138 * @iov: io vector request
1139 * @nr_segs: number of segments in the iovec
b2abacf3 1140 * @pos: current file position
485bb99b 1141 *
1da177e4
LT
1142 * This is the "read()" routine for all filesystems
1143 * that can use the page cache directly.
1144 */
1145ssize_t
543ade1f
BP
1146generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1147 unsigned long nr_segs, loff_t pos)
1da177e4
LT
1148{
1149 struct file *filp = iocb->ki_filp;
1150 ssize_t retval;
1151 unsigned long seg;
1152 size_t count;
543ade1f 1153 loff_t *ppos = &iocb->ki_pos;
1da177e4
LT
1154
1155 count = 0;
0ceb3314
DM
1156 retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1157 if (retval)
1158 return retval;
1da177e4
LT
1159
1160 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1161 if (filp->f_flags & O_DIRECT) {
543ade1f 1162 loff_t size;
1da177e4
LT
1163 struct address_space *mapping;
1164 struct inode *inode;
1165
1166 mapping = filp->f_mapping;
1167 inode = mapping->host;
1168 retval = 0;
1169 if (!count)
1170 goto out; /* skip atime */
1171 size = i_size_read(inode);
1172 if (pos < size) {
1173 retval = generic_file_direct_IO(READ, iocb,
1174 iov, pos, nr_segs);
1da177e4
LT
1175 if (retval > 0)
1176 *ppos = pos + retval;
1177 }
0e0bcae3 1178 if (likely(retval != 0)) {
3f1a9aae 1179 file_accessed(filp);
a9e5f4d0 1180 goto out;
0e0bcae3 1181 }
1da177e4
LT
1182 }
1183
1184 retval = 0;
1185 if (count) {
1186 for (seg = 0; seg < nr_segs; seg++) {
1187 read_descriptor_t desc;
1188
1189 desc.written = 0;
1190 desc.arg.buf = iov[seg].iov_base;
1191 desc.count = iov[seg].iov_len;
1192 if (desc.count == 0)
1193 continue;
1194 desc.error = 0;
1195 do_generic_file_read(filp,ppos,&desc,file_read_actor);
1196 retval += desc.written;
39e88ca2
TH
1197 if (desc.error) {
1198 retval = retval ?: desc.error;
1da177e4
LT
1199 break;
1200 }
c44939ec 1201 if (desc.count > 0)
1202 break;
1da177e4
LT
1203 }
1204 }
1205out:
1206 return retval;
1207}
1da177e4
LT
1208EXPORT_SYMBOL(generic_file_aio_read);
1209
1da177e4
LT
1210static ssize_t
1211do_readahead(struct address_space *mapping, struct file *filp,
57f6b96c 1212 pgoff_t index, unsigned long nr)
1da177e4
LT
1213{
1214 if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1215 return -EINVAL;
1216
1217 force_page_cache_readahead(mapping, filp, index,
1218 max_sane_readahead(nr));
1219 return 0;
1220}
1221
1222asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1223{
1224 ssize_t ret;
1225 struct file *file;
1226
1227 ret = -EBADF;
1228 file = fget(fd);
1229 if (file) {
1230 if (file->f_mode & FMODE_READ) {
1231 struct address_space *mapping = file->f_mapping;
57f6b96c
FW
1232 pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1233 pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1da177e4
LT
1234 unsigned long len = end - start + 1;
1235 ret = do_readahead(mapping, file, start, len);
1236 }
1237 fput(file);
1238 }
1239 return ret;
1240}
1241
1242#ifdef CONFIG_MMU
485bb99b
RD
1243/**
1244 * page_cache_read - adds requested page to the page cache if not already there
1245 * @file: file to read
1246 * @offset: page index
1247 *
1da177e4
LT
1248 * This adds the requested page to the page cache if it isn't already there,
1249 * and schedules an I/O to read in its contents from disk.
1250 */
57f6b96c 1251static int fastcall page_cache_read(struct file * file, pgoff_t offset)
1da177e4
LT
1252{
1253 struct address_space *mapping = file->f_mapping;
1254 struct page *page;
994fc28c 1255 int ret;
1da177e4 1256
994fc28c
ZB
1257 do {
1258 page = page_cache_alloc_cold(mapping);
1259 if (!page)
1260 return -ENOMEM;
1261
1262 ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1263 if (ret == 0)
1264 ret = mapping->a_ops->readpage(file, page);
1265 else if (ret == -EEXIST)
1266 ret = 0; /* losing race to add is OK */
1da177e4 1267
1da177e4 1268 page_cache_release(page);
1da177e4 1269
994fc28c
ZB
1270 } while (ret == AOP_TRUNCATED_PAGE);
1271
1272 return ret;
1da177e4
LT
1273}
1274
1275#define MMAP_LOTSAMISS (100)
1276
485bb99b 1277/**
54cb8821 1278 * filemap_fault - read in file data for page fault handling
d0217ac0
NP
1279 * @vma: vma in which the fault was taken
1280 * @vmf: struct vm_fault containing details of the fault
485bb99b 1281 *
54cb8821 1282 * filemap_fault() is invoked via the vma operations vector for a
1da177e4
LT
1283 * mapped memory region to read in file data during a page fault.
1284 *
1285 * The goto's are kind of ugly, but this streamlines the normal case of having
1286 * it in the page cache, and handles the special cases reasonably without
1287 * having a lot of duplicated code.
1288 */
d0217ac0 1289int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1da177e4
LT
1290{
1291 int error;
54cb8821 1292 struct file *file = vma->vm_file;
1da177e4
LT
1293 struct address_space *mapping = file->f_mapping;
1294 struct file_ra_state *ra = &file->f_ra;
1295 struct inode *inode = mapping->host;
1296 struct page *page;
54cb8821
NP
1297 unsigned long size;
1298 int did_readaround = 0;
83c54070 1299 int ret = 0;
1da177e4 1300
1da177e4 1301 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
d0217ac0 1302 if (vmf->pgoff >= size)
1da177e4
LT
1303 goto outside_data_content;
1304
1305 /* If we don't want any read-ahead, don't bother */
54cb8821 1306 if (VM_RandomReadHint(vma))
1da177e4
LT
1307 goto no_cached_page;
1308
1da177e4
LT
1309 /*
1310 * Do we have something in the page cache already?
1311 */
1312retry_find:
d0217ac0 1313 page = find_lock_page(mapping, vmf->pgoff);
3ea89ee8
FW
1314 /*
1315 * For sequential accesses, we use the generic readahead logic.
1316 */
1317 if (VM_SequentialReadHint(vma)) {
1318 if (!page) {
cf914a7d 1319 page_cache_sync_readahead(mapping, ra, file,
3ea89ee8
FW
1320 vmf->pgoff, 1);
1321 page = find_lock_page(mapping, vmf->pgoff);
1322 if (!page)
1323 goto no_cached_page;
1324 }
1325 if (PageReadahead(page)) {
cf914a7d 1326 page_cache_async_readahead(mapping, ra, file, page,
3ea89ee8
FW
1327 vmf->pgoff, 1);
1328 }
1329 }
1330
1da177e4
LT
1331 if (!page) {
1332 unsigned long ra_pages;
1333
1da177e4
LT
1334 ra->mmap_miss++;
1335
1336 /*
1337 * Do we miss much more than hit in this file? If so,
1338 * stop bothering with read-ahead. It will only hurt.
1339 */
0bb7ba6b 1340 if (ra->mmap_miss > MMAP_LOTSAMISS)
1da177e4
LT
1341 goto no_cached_page;
1342
1343 /*
1344 * To keep the pgmajfault counter straight, we need to
1345 * check did_readaround, as this is an inner loop.
1346 */
1347 if (!did_readaround) {
d0217ac0 1348 ret = VM_FAULT_MAJOR;
f8891e5e 1349 count_vm_event(PGMAJFAULT);
1da177e4
LT
1350 }
1351 did_readaround = 1;
1352 ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1353 if (ra_pages) {
1354 pgoff_t start = 0;
1355
d0217ac0
NP
1356 if (vmf->pgoff > ra_pages / 2)
1357 start = vmf->pgoff - ra_pages / 2;
1da177e4
LT
1358 do_page_cache_readahead(mapping, file, start, ra_pages);
1359 }
d0217ac0 1360 page = find_lock_page(mapping, vmf->pgoff);
1da177e4
LT
1361 if (!page)
1362 goto no_cached_page;
1363 }
1364
1365 if (!did_readaround)
0bb7ba6b 1366 ra->mmap_miss--;
1da177e4
LT
1367
1368 /*
d00806b1
NP
1369 * We have a locked page in the page cache, now we need to check
1370 * that it's up-to-date. If not, it is going to be due to an error.
1da177e4 1371 */
d00806b1 1372 if (unlikely(!PageUptodate(page)))
1da177e4
LT
1373 goto page_not_uptodate;
1374
d00806b1
NP
1375 /* Must recheck i_size under page lock */
1376 size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
d0217ac0 1377 if (unlikely(vmf->pgoff >= size)) {
d00806b1 1378 unlock_page(page);
745ad48e 1379 page_cache_release(page);
d00806b1
NP
1380 goto outside_data_content;
1381 }
1382
1da177e4
LT
1383 /*
1384 * Found the page and have a reference on it.
1385 */
1386 mark_page_accessed(page);
f4e6b498 1387 ra->prev_pos = (loff_t)page->index << PAGE_CACHE_SHIFT;
d0217ac0 1388 vmf->page = page;
83c54070 1389 return ret | VM_FAULT_LOCKED;
1da177e4
LT
1390
1391outside_data_content:
1392 /*
1393 * An external ptracer can access pages that normally aren't
1394 * accessible..
1395 */
d0217ac0
NP
1396 if (vma->vm_mm == current->mm)
1397 return VM_FAULT_SIGBUS;
1398
1da177e4
LT
1399 /* Fall through to the non-read-ahead case */
1400no_cached_page:
1401 /*
1402 * We're only likely to ever get here if MADV_RANDOM is in
1403 * effect.
1404 */
d0217ac0 1405 error = page_cache_read(file, vmf->pgoff);
1da177e4
LT
1406
1407 /*
1408 * The page we want has now been added to the page cache.
1409 * In the unlikely event that someone removed it in the
1410 * meantime, we'll just come back here and read it again.
1411 */
1412 if (error >= 0)
1413 goto retry_find;
1414
1415 /*
1416 * An error return from page_cache_read can result if the
1417 * system is low on memory, or a problem occurs while trying
1418 * to schedule I/O.
1419 */
1420 if (error == -ENOMEM)
d0217ac0
NP
1421 return VM_FAULT_OOM;
1422 return VM_FAULT_SIGBUS;
1da177e4
LT
1423
1424page_not_uptodate:
d00806b1 1425 /* IO error path */
1da177e4 1426 if (!did_readaround) {
d0217ac0 1427 ret = VM_FAULT_MAJOR;
f8891e5e 1428 count_vm_event(PGMAJFAULT);
1da177e4 1429 }
1da177e4
LT
1430
1431 /*
1432 * Umm, take care of errors if the page isn't up-to-date.
1433 * Try to re-read it _once_. We do this synchronously,
1434 * because there really aren't any performance issues here
1435 * and we need to check for errors.
1436 */
1da177e4 1437 ClearPageError(page);
994fc28c 1438 error = mapping->a_ops->readpage(file, page);
d00806b1
NP
1439 page_cache_release(page);
1440
1441 if (!error || error == AOP_TRUNCATED_PAGE)
994fc28c 1442 goto retry_find;
1da177e4 1443
d00806b1 1444 /* Things didn't work out. Return zero to tell the mm layer so. */
76d42bd9 1445 shrink_readahead_size_eio(file, ra);
d0217ac0 1446 return VM_FAULT_SIGBUS;
54cb8821
NP
1447}
1448EXPORT_SYMBOL(filemap_fault);
1449
1da177e4 1450struct vm_operations_struct generic_file_vm_ops = {
54cb8821 1451 .fault = filemap_fault,
1da177e4
LT
1452};
1453
1454/* This is used for a general mmap of a disk file */
1455
1456int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1457{
1458 struct address_space *mapping = file->f_mapping;
1459
1460 if (!mapping->a_ops->readpage)
1461 return -ENOEXEC;
1462 file_accessed(file);
1463 vma->vm_ops = &generic_file_vm_ops;
d0217ac0 1464 vma->vm_flags |= VM_CAN_NONLINEAR;
1da177e4
LT
1465 return 0;
1466}
1da177e4
LT
1467
1468/*
1469 * This is for filesystems which do not implement ->writepage.
1470 */
1471int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1472{
1473 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1474 return -EINVAL;
1475 return generic_file_mmap(file, vma);
1476}
1477#else
1478int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1479{
1480 return -ENOSYS;
1481}
1482int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1483{
1484 return -ENOSYS;
1485}
1486#endif /* CONFIG_MMU */
1487
1488EXPORT_SYMBOL(generic_file_mmap);
1489EXPORT_SYMBOL(generic_file_readonly_mmap);
1490
6fe6900e 1491static struct page *__read_cache_page(struct address_space *mapping,
57f6b96c 1492 pgoff_t index,
1da177e4
LT
1493 int (*filler)(void *,struct page*),
1494 void *data)
1495{
eb2be189 1496 struct page *page;
1da177e4
LT
1497 int err;
1498repeat:
1499 page = find_get_page(mapping, index);
1500 if (!page) {
eb2be189
NP
1501 page = page_cache_alloc_cold(mapping);
1502 if (!page)
1503 return ERR_PTR(-ENOMEM);
1504 err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
1505 if (unlikely(err)) {
1506 page_cache_release(page);
1507 if (err == -EEXIST)
1508 goto repeat;
1da177e4 1509 /* Presumably ENOMEM for radix tree node */
1da177e4
LT
1510 return ERR_PTR(err);
1511 }
1da177e4
LT
1512 err = filler(data, page);
1513 if (err < 0) {
1514 page_cache_release(page);
1515 page = ERR_PTR(err);
1516 }
1517 }
1da177e4
LT
1518 return page;
1519}
1520
6fe6900e
NP
1521/*
1522 * Same as read_cache_page, but don't wait for page to become unlocked
1523 * after submitting it to the filler.
1da177e4 1524 */
6fe6900e 1525struct page *read_cache_page_async(struct address_space *mapping,
57f6b96c 1526 pgoff_t index,
1da177e4
LT
1527 int (*filler)(void *,struct page*),
1528 void *data)
1529{
1530 struct page *page;
1531 int err;
1532
1533retry:
1534 page = __read_cache_page(mapping, index, filler, data);
1535 if (IS_ERR(page))
c855ff37 1536 return page;
1da177e4
LT
1537 if (PageUptodate(page))
1538 goto out;
1539
1540 lock_page(page);
1541 if (!page->mapping) {
1542 unlock_page(page);
1543 page_cache_release(page);
1544 goto retry;
1545 }
1546 if (PageUptodate(page)) {
1547 unlock_page(page);
1548 goto out;
1549 }
1550 err = filler(data, page);
1551 if (err < 0) {
1552 page_cache_release(page);
c855ff37 1553 return ERR_PTR(err);
1da177e4 1554 }
c855ff37 1555out:
6fe6900e
NP
1556 mark_page_accessed(page);
1557 return page;
1558}
1559EXPORT_SYMBOL(read_cache_page_async);
1560
1561/**
1562 * read_cache_page - read into page cache, fill it if needed
1563 * @mapping: the page's address_space
1564 * @index: the page index
1565 * @filler: function to perform the read
1566 * @data: destination for read data
1567 *
1568 * Read into the page cache. If a page already exists, and PageUptodate() is
1569 * not set, try to fill the page then wait for it to become unlocked.
1570 *
1571 * If the page does not get brought uptodate, return -EIO.
1572 */
1573struct page *read_cache_page(struct address_space *mapping,
57f6b96c 1574 pgoff_t index,
6fe6900e
NP
1575 int (*filler)(void *,struct page*),
1576 void *data)
1577{
1578 struct page *page;
1579
1580 page = read_cache_page_async(mapping, index, filler, data);
1581 if (IS_ERR(page))
1582 goto out;
1583 wait_on_page_locked(page);
1584 if (!PageUptodate(page)) {
1585 page_cache_release(page);
1586 page = ERR_PTR(-EIO);
1587 }
1da177e4
LT
1588 out:
1589 return page;
1590}
1da177e4
LT
1591EXPORT_SYMBOL(read_cache_page);
1592
1da177e4
LT
1593/*
1594 * The logic we want is
1595 *
1596 * if suid or (sgid and xgrp)
1597 * remove privs
1598 */
01de85e0 1599int should_remove_suid(struct dentry *dentry)
1da177e4
LT
1600{
1601 mode_t mode = dentry->d_inode->i_mode;
1602 int kill = 0;
1da177e4
LT
1603
1604 /* suid always must be killed */
1605 if (unlikely(mode & S_ISUID))
1606 kill = ATTR_KILL_SUID;
1607
1608 /*
1609 * sgid without any exec bits is just a mandatory locking mark; leave
1610 * it alone. If some exec bits are set, it's a real sgid; kill it.
1611 */
1612 if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1613 kill |= ATTR_KILL_SGID;
1614
01de85e0
JA
1615 if (unlikely(kill && !capable(CAP_FSETID)))
1616 return kill;
1da177e4 1617
01de85e0
JA
1618 return 0;
1619}
d23a147b 1620EXPORT_SYMBOL(should_remove_suid);
01de85e0
JA
1621
1622int __remove_suid(struct dentry *dentry, int kill)
1623{
1624 struct iattr newattrs;
1625
1626 newattrs.ia_valid = ATTR_FORCE | kill;
1627 return notify_change(dentry, &newattrs);
1628}
1629
1630int remove_suid(struct dentry *dentry)
1631{
b5376771
SH
1632 int killsuid = should_remove_suid(dentry);
1633 int killpriv = security_inode_need_killpriv(dentry);
1634 int error = 0;
01de85e0 1635
b5376771
SH
1636 if (killpriv < 0)
1637 return killpriv;
1638 if (killpriv)
1639 error = security_inode_killpriv(dentry);
1640 if (!error && killsuid)
1641 error = __remove_suid(dentry, killsuid);
01de85e0 1642
b5376771 1643 return error;
1da177e4
LT
1644}
1645EXPORT_SYMBOL(remove_suid);
1646
2f718ffc 1647static size_t __iovec_copy_from_user_inatomic(char *vaddr,
1da177e4
LT
1648 const struct iovec *iov, size_t base, size_t bytes)
1649{
1650 size_t copied = 0, left = 0;
1651
1652 while (bytes) {
1653 char __user *buf = iov->iov_base + base;
1654 int copy = min(bytes, iov->iov_len - base);
1655
1656 base = 0;
c22ce143 1657 left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
1da177e4
LT
1658 copied += copy;
1659 bytes -= copy;
1660 vaddr += copy;
1661 iov++;
1662
01408c49 1663 if (unlikely(left))
1da177e4 1664 break;
1da177e4
LT
1665 }
1666 return copied - left;
1667}
1668
2f718ffc
NP
1669/*
1670 * Copy as much as we can into the page and return the number of bytes which
1671 * were sucessfully copied. If a fault is encountered then return the number of
1672 * bytes which were copied.
1673 */
1674size_t iov_iter_copy_from_user_atomic(struct page *page,
1675 struct iov_iter *i, unsigned long offset, size_t bytes)
1676{
1677 char *kaddr;
1678 size_t copied;
1679
1680 BUG_ON(!in_atomic());
1681 kaddr = kmap_atomic(page, KM_USER0);
1682 if (likely(i->nr_segs == 1)) {
1683 int left;
1684 char __user *buf = i->iov->iov_base + i->iov_offset;
1685 left = __copy_from_user_inatomic_nocache(kaddr + offset,
1686 buf, bytes);
1687 copied = bytes - left;
1688 } else {
1689 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1690 i->iov, i->iov_offset, bytes);
1691 }
1692 kunmap_atomic(kaddr, KM_USER0);
1693
1694 return copied;
1695}
89e10787 1696EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
2f718ffc
NP
1697
1698/*
1699 * This has the same sideeffects and return value as
1700 * iov_iter_copy_from_user_atomic().
1701 * The difference is that it attempts to resolve faults.
1702 * Page must not be locked.
1703 */
1704size_t iov_iter_copy_from_user(struct page *page,
1705 struct iov_iter *i, unsigned long offset, size_t bytes)
1706{
1707 char *kaddr;
1708 size_t copied;
1709
1710 kaddr = kmap(page);
1711 if (likely(i->nr_segs == 1)) {
1712 int left;
1713 char __user *buf = i->iov->iov_base + i->iov_offset;
1714 left = __copy_from_user_nocache(kaddr + offset, buf, bytes);
1715 copied = bytes - left;
1716 } else {
1717 copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1718 i->iov, i->iov_offset, bytes);
1719 }
1720 kunmap(page);
1721 return copied;
1722}
89e10787 1723EXPORT_SYMBOL(iov_iter_copy_from_user);
2f718ffc
NP
1724
1725static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
1726{
1727 if (likely(i->nr_segs == 1)) {
1728 i->iov_offset += bytes;
1729 } else {
1730 const struct iovec *iov = i->iov;
1731 size_t base = i->iov_offset;
1732
1733 while (bytes) {
1734 int copy = min(bytes, iov->iov_len - base);
1735
1736 bytes -= copy;
1737 base += copy;
1738 if (iov->iov_len == base) {
1739 iov++;
1740 base = 0;
1741 }
1742 }
1743 i->iov = iov;
1744 i->iov_offset = base;
1745 }
1746}
1747
1748void iov_iter_advance(struct iov_iter *i, size_t bytes)
1749{
1750 BUG_ON(i->count < bytes);
1751
1752 __iov_iter_advance_iov(i, bytes);
1753 i->count -= bytes;
1754}
89e10787 1755EXPORT_SYMBOL(iov_iter_advance);
2f718ffc 1756
afddba49
NP
1757/*
1758 * Fault in the first iovec of the given iov_iter, to a maximum length
1759 * of bytes. Returns 0 on success, or non-zero if the memory could not be
1760 * accessed (ie. because it is an invalid address).
1761 *
1762 * writev-intensive code may want this to prefault several iovecs -- that
1763 * would be possible (callers must not rely on the fact that _only_ the
1764 * first iovec will be faulted with the current implementation).
1765 */
1766int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
2f718ffc 1767{
2f718ffc 1768 char __user *buf = i->iov->iov_base + i->iov_offset;
afddba49
NP
1769 bytes = min(bytes, i->iov->iov_len - i->iov_offset);
1770 return fault_in_pages_readable(buf, bytes);
2f718ffc 1771}
89e10787 1772EXPORT_SYMBOL(iov_iter_fault_in_readable);
2f718ffc
NP
1773
1774/*
1775 * Return the count of just the current iov_iter segment.
1776 */
1777size_t iov_iter_single_seg_count(struct iov_iter *i)
1778{
1779 const struct iovec *iov = i->iov;
1780 if (i->nr_segs == 1)
1781 return i->count;
1782 else
1783 return min(i->count, iov->iov_len - i->iov_offset);
1784}
89e10787 1785EXPORT_SYMBOL(iov_iter_single_seg_count);
2f718ffc 1786
1da177e4
LT
1787/*
1788 * Performs necessary checks before doing a write
1789 *
485bb99b 1790 * Can adjust writing position or amount of bytes to write.
1da177e4
LT
1791 * Returns appropriate error code that caller should return or
1792 * zero in case that write should be allowed.
1793 */
1794inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1795{
1796 struct inode *inode = file->f_mapping->host;
1797 unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
1798
1799 if (unlikely(*pos < 0))
1800 return -EINVAL;
1801
1da177e4
LT
1802 if (!isblk) {
1803 /* FIXME: this is for backwards compatibility with 2.4 */
1804 if (file->f_flags & O_APPEND)
1805 *pos = i_size_read(inode);
1806
1807 if (limit != RLIM_INFINITY) {
1808 if (*pos >= limit) {
1809 send_sig(SIGXFSZ, current, 0);
1810 return -EFBIG;
1811 }
1812 if (*count > limit - (typeof(limit))*pos) {
1813 *count = limit - (typeof(limit))*pos;
1814 }
1815 }
1816 }
1817
1818 /*
1819 * LFS rule
1820 */
1821 if (unlikely(*pos + *count > MAX_NON_LFS &&
1822 !(file->f_flags & O_LARGEFILE))) {
1823 if (*pos >= MAX_NON_LFS) {
1da177e4
LT
1824 return -EFBIG;
1825 }
1826 if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1827 *count = MAX_NON_LFS - (unsigned long)*pos;
1828 }
1829 }
1830
1831 /*
1832 * Are we about to exceed the fs block limit ?
1833 *
1834 * If we have written data it becomes a short write. If we have
1835 * exceeded without writing data we send a signal and return EFBIG.
1836 * Linus frestrict idea will clean these up nicely..
1837 */
1838 if (likely(!isblk)) {
1839 if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1840 if (*count || *pos > inode->i_sb->s_maxbytes) {
1da177e4
LT
1841 return -EFBIG;
1842 }
1843 /* zero-length writes at ->s_maxbytes are OK */
1844 }
1845
1846 if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1847 *count = inode->i_sb->s_maxbytes - *pos;
1848 } else {
9361401e 1849#ifdef CONFIG_BLOCK
1da177e4
LT
1850 loff_t isize;
1851 if (bdev_read_only(I_BDEV(inode)))
1852 return -EPERM;
1853 isize = i_size_read(inode);
1854 if (*pos >= isize) {
1855 if (*count || *pos > isize)
1856 return -ENOSPC;
1857 }
1858
1859 if (*pos + *count > isize)
1860 *count = isize - *pos;
9361401e
DH
1861#else
1862 return -EPERM;
1863#endif
1da177e4
LT
1864 }
1865 return 0;
1866}
1867EXPORT_SYMBOL(generic_write_checks);
1868
afddba49
NP
1869int pagecache_write_begin(struct file *file, struct address_space *mapping,
1870 loff_t pos, unsigned len, unsigned flags,
1871 struct page **pagep, void **fsdata)
1872{
1873 const struct address_space_operations *aops = mapping->a_ops;
1874
1875 if (aops->write_begin) {
1876 return aops->write_begin(file, mapping, pos, len, flags,
1877 pagep, fsdata);
1878 } else {
1879 int ret;
1880 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1881 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1882 struct inode *inode = mapping->host;
1883 struct page *page;
1884again:
1885 page = __grab_cache_page(mapping, index);
1886 *pagep = page;
1887 if (!page)
1888 return -ENOMEM;
1889
1890 if (flags & AOP_FLAG_UNINTERRUPTIBLE && !PageUptodate(page)) {
1891 /*
1892 * There is no way to resolve a short write situation
1893 * for a !Uptodate page (except by double copying in
1894 * the caller done by generic_perform_write_2copy).
1895 *
1896 * Instead, we have to bring it uptodate here.
1897 */
1898 ret = aops->readpage(file, page);
1899 page_cache_release(page);
1900 if (ret) {
1901 if (ret == AOP_TRUNCATED_PAGE)
1902 goto again;
1903 return ret;
1904 }
1905 goto again;
1906 }
1907
1908 ret = aops->prepare_write(file, page, offset, offset+len);
1909 if (ret) {
55144768 1910 unlock_page(page);
afddba49
NP
1911 page_cache_release(page);
1912 if (pos + len > inode->i_size)
1913 vmtruncate(inode, inode->i_size);
afddba49
NP
1914 }
1915 return ret;
1916 }
1917}
1918EXPORT_SYMBOL(pagecache_write_begin);
1919
1920int pagecache_write_end(struct file *file, struct address_space *mapping,
1921 loff_t pos, unsigned len, unsigned copied,
1922 struct page *page, void *fsdata)
1923{
1924 const struct address_space_operations *aops = mapping->a_ops;
1925 int ret;
1926
1927 if (aops->write_end) {
1928 mark_page_accessed(page);
1929 ret = aops->write_end(file, mapping, pos, len, copied,
1930 page, fsdata);
1931 } else {
1932 unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1933 struct inode *inode = mapping->host;
1934
1935 flush_dcache_page(page);
1936 ret = aops->commit_write(file, page, offset, offset+len);
1937 unlock_page(page);
1938 mark_page_accessed(page);
1939 page_cache_release(page);
afddba49
NP
1940
1941 if (ret < 0) {
1942 if (pos + len > inode->i_size)
1943 vmtruncate(inode, inode->i_size);
1944 } else if (ret > 0)
1945 ret = min_t(size_t, copied, ret);
1946 else
1947 ret = copied;
1948 }
1949
1950 return ret;
1951}
1952EXPORT_SYMBOL(pagecache_write_end);
1953
1da177e4
LT
1954ssize_t
1955generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
1956 unsigned long *nr_segs, loff_t pos, loff_t *ppos,
1957 size_t count, size_t ocount)
1958{
1959 struct file *file = iocb->ki_filp;
1960 struct address_space *mapping = file->f_mapping;
1961 struct inode *inode = mapping->host;
1962 ssize_t written;
1963
1964 if (count != ocount)
1965 *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
1966
1967 written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
1968 if (written > 0) {
1969 loff_t end = pos + written;
1970 if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
1971 i_size_write(inode, end);
1972 mark_inode_dirty(inode);
1973 }
1974 *ppos = end;
1975 }
1976
1977 /*
1978 * Sync the fs metadata but not the minor inode changes and
1979 * of course not the data as we did direct DMA for the IO.
1b1dcc1b 1980 * i_mutex is held, which protects generic_osync_inode() from
8459d86a 1981 * livelocking. AIO O_DIRECT ops attempt to sync metadata here.
1da177e4 1982 */
8459d86a
ZB
1983 if ((written >= 0 || written == -EIOCBQUEUED) &&
1984 ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
1e8a81c5
HH
1985 int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1986 if (err < 0)
1987 written = err;
1988 }
1da177e4
LT
1989 return written;
1990}
1991EXPORT_SYMBOL(generic_file_direct_write);
1992
eb2be189
NP
1993/*
1994 * Find or create a page at the given pagecache position. Return the locked
1995 * page. This function is specifically for buffered writes.
1996 */
afddba49 1997struct page *__grab_cache_page(struct address_space *mapping, pgoff_t index)
eb2be189
NP
1998{
1999 int status;
2000 struct page *page;
2001repeat:
2002 page = find_lock_page(mapping, index);
2003 if (likely(page))
2004 return page;
2005
2006 page = page_cache_alloc(mapping);
2007 if (!page)
2008 return NULL;
2009 status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
2010 if (unlikely(status)) {
2011 page_cache_release(page);
2012 if (status == -EEXIST)
2013 goto repeat;
2014 return NULL;
2015 }
2016 return page;
2017}
afddba49 2018EXPORT_SYMBOL(__grab_cache_page);
eb2be189 2019
afddba49
NP
2020static ssize_t generic_perform_write_2copy(struct file *file,
2021 struct iov_iter *i, loff_t pos)
1da177e4 2022{
ae37461c 2023 struct address_space *mapping = file->f_mapping;
f5e54d6e 2024 const struct address_space_operations *a_ops = mapping->a_ops;
afddba49
NP
2025 struct inode *inode = mapping->host;
2026 long status = 0;
2027 ssize_t written = 0;
1da177e4
LT
2028
2029 do {
08291429 2030 struct page *src_page;
eb2be189 2031 struct page *page;
ae37461c
AM
2032 pgoff_t index; /* Pagecache index for current page */
2033 unsigned long offset; /* Offset into pagecache page */
08291429 2034 unsigned long bytes; /* Bytes to write to page */
ae37461c 2035 size_t copied; /* Bytes copied from user */
1da177e4 2036
ae37461c 2037 offset = (pos & (PAGE_CACHE_SIZE - 1));
1da177e4 2038 index = pos >> PAGE_CACHE_SHIFT;
2f718ffc 2039 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
afddba49 2040 iov_iter_count(i));
41cb8ac0 2041
08291429
NP
2042 /*
2043 * a non-NULL src_page indicates that we're doing the
2044 * copy via get_user_pages and kmap.
2045 */
2046 src_page = NULL;
2047
41cb8ac0
NP
2048 /*
2049 * Bring in the user page that we will copy from _first_.
2050 * Otherwise there's a nasty deadlock on copying from the
2051 * same page as we're writing to, without it being marked
2052 * up-to-date.
08291429
NP
2053 *
2054 * Not only is this an optimisation, but it is also required
2055 * to check that the address is actually valid, when atomic
2056 * usercopies are used, below.
41cb8ac0 2057 */
afddba49 2058 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
08291429
NP
2059 status = -EFAULT;
2060 break;
2061 }
eb2be189
NP
2062
2063 page = __grab_cache_page(mapping, index);
1da177e4
LT
2064 if (!page) {
2065 status = -ENOMEM;
2066 break;
2067 }
2068
08291429
NP
2069 /*
2070 * non-uptodate pages cannot cope with short copies, and we
2071 * cannot take a pagefault with the destination page locked.
2072 * So pin the source page to copy it.
2073 */
674b892e 2074 if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) {
08291429
NP
2075 unlock_page(page);
2076
2077 src_page = alloc_page(GFP_KERNEL);
2078 if (!src_page) {
2079 page_cache_release(page);
2080 status = -ENOMEM;
2081 break;
2082 }
2083
2084 /*
2085 * Cannot get_user_pages with a page locked for the
2086 * same reason as we can't take a page fault with a
2087 * page locked (as explained below).
2088 */
afddba49 2089 copied = iov_iter_copy_from_user(src_page, i,
2f718ffc 2090 offset, bytes);
08291429
NP
2091 if (unlikely(copied == 0)) {
2092 status = -EFAULT;
2093 page_cache_release(page);
2094 page_cache_release(src_page);
2095 break;
2096 }
2097 bytes = copied;
2098
2099 lock_page(page);
2100 /*
2101 * Can't handle the page going uptodate here, because
2102 * that means we would use non-atomic usercopies, which
2103 * zero out the tail of the page, which can cause
2104 * zeroes to become transiently visible. We could just
2105 * use a non-zeroing copy, but the APIs aren't too
2106 * consistent.
2107 */
2108 if (unlikely(!page->mapping || PageUptodate(page))) {
2109 unlock_page(page);
2110 page_cache_release(page);
2111 page_cache_release(src_page);
2112 continue;
2113 }
08291429
NP
2114 }
2115
1da177e4 2116 status = a_ops->prepare_write(file, page, offset, offset+bytes);
64649a58
NP
2117 if (unlikely(status))
2118 goto fs_write_aop_error;
994fc28c 2119
08291429
NP
2120 if (!src_page) {
2121 /*
2122 * Must not enter the pagefault handler here, because
2123 * we hold the page lock, so we might recursively
2124 * deadlock on the same lock, or get an ABBA deadlock
2125 * against a different lock, or against the mmap_sem
2126 * (which nests outside the page lock). So increment
2127 * preempt count, and use _atomic usercopies.
2128 *
2129 * The page is uptodate so we are OK to encounter a
2130 * short copy: if unmodified parts of the page are
2131 * marked dirty and written out to disk, it doesn't
2132 * really matter.
2133 */
2134 pagefault_disable();
afddba49 2135 copied = iov_iter_copy_from_user_atomic(page, i,
2f718ffc 2136 offset, bytes);
08291429
NP
2137 pagefault_enable();
2138 } else {
2139 void *src, *dst;
2140 src = kmap_atomic(src_page, KM_USER0);
2141 dst = kmap_atomic(page, KM_USER1);
2142 memcpy(dst + offset, src + offset, bytes);
2143 kunmap_atomic(dst, KM_USER1);
2144 kunmap_atomic(src, KM_USER0);
2145 copied = bytes;
2146 }
1da177e4 2147 flush_dcache_page(page);
4a9e5ef1 2148
1da177e4 2149 status = a_ops->commit_write(file, page, offset, offset+bytes);
55144768 2150 if (unlikely(status < 0))
64649a58 2151 goto fs_write_aop_error;
64649a58 2152 if (unlikely(status > 0)) /* filesystem did partial write */
08291429
NP
2153 copied = min_t(size_t, copied, status);
2154
2155 unlock_page(page);
2156 mark_page_accessed(page);
2157 page_cache_release(page);
2158 if (src_page)
2159 page_cache_release(src_page);
64649a58 2160
afddba49 2161 iov_iter_advance(i, copied);
4a9e5ef1 2162 pos += copied;
afddba49 2163 written += copied;
4a9e5ef1 2164
1da177e4
LT
2165 balance_dirty_pages_ratelimited(mapping);
2166 cond_resched();
64649a58
NP
2167 continue;
2168
2169fs_write_aop_error:
55144768 2170 unlock_page(page);
64649a58 2171 page_cache_release(page);
08291429
NP
2172 if (src_page)
2173 page_cache_release(src_page);
64649a58
NP
2174
2175 /*
2176 * prepare_write() may have instantiated a few blocks
2177 * outside i_size. Trim these off again. Don't need
2178 * i_size_read because we hold i_mutex.
2179 */
2180 if (pos + bytes > inode->i_size)
2181 vmtruncate(inode, inode->i_size);
55144768 2182 break;
afddba49
NP
2183 } while (iov_iter_count(i));
2184
2185 return written ? written : status;
2186}
2187
2188static ssize_t generic_perform_write(struct file *file,
2189 struct iov_iter *i, loff_t pos)
2190{
2191 struct address_space *mapping = file->f_mapping;
2192 const struct address_space_operations *a_ops = mapping->a_ops;
2193 long status = 0;
2194 ssize_t written = 0;
674b892e
NP
2195 unsigned int flags = 0;
2196
2197 /*
2198 * Copies from kernel address space cannot fail (NFSD is a big user).
2199 */
2200 if (segment_eq(get_fs(), KERNEL_DS))
2201 flags |= AOP_FLAG_UNINTERRUPTIBLE;
afddba49
NP
2202
2203 do {
2204 struct page *page;
2205 pgoff_t index; /* Pagecache index for current page */
2206 unsigned long offset; /* Offset into pagecache page */
2207 unsigned long bytes; /* Bytes to write to page */
2208 size_t copied; /* Bytes copied from user */
2209 void *fsdata;
2210
2211 offset = (pos & (PAGE_CACHE_SIZE - 1));
2212 index = pos >> PAGE_CACHE_SHIFT;
2213 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2214 iov_iter_count(i));
2215
2216again:
2217
2218 /*
2219 * Bring in the user page that we will copy from _first_.
2220 * Otherwise there's a nasty deadlock on copying from the
2221 * same page as we're writing to, without it being marked
2222 * up-to-date.
2223 *
2224 * Not only is this an optimisation, but it is also required
2225 * to check that the address is actually valid, when atomic
2226 * usercopies are used, below.
2227 */
2228 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2229 status = -EFAULT;
2230 break;
2231 }
2232
674b892e 2233 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
afddba49
NP
2234 &page, &fsdata);
2235 if (unlikely(status))
2236 break;
2237
2238 pagefault_disable();
2239 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2240 pagefault_enable();
2241 flush_dcache_page(page);
2242
2243 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2244 page, fsdata);
2245 if (unlikely(status < 0))
2246 break;
2247 copied = status;
2248
2249 cond_resched();
2250
2251 if (unlikely(copied == 0)) {
2252 /*
2253 * If we were unable to copy any data at all, we must
2254 * fall back to a single segment length write.
2255 *
2256 * If we didn't fallback here, we could livelock
2257 * because not all segments in the iov can be copied at
2258 * once without a pagefault.
2259 */
2260 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2261 iov_iter_single_seg_count(i));
2262 goto again;
2263 }
2264 iov_iter_advance(i, copied);
2265 pos += copied;
2266 written += copied;
2267
2268 balance_dirty_pages_ratelimited(mapping);
2269
2270 } while (iov_iter_count(i));
2271
2272 return written ? written : status;
2273}
2274
2275ssize_t
2276generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2277 unsigned long nr_segs, loff_t pos, loff_t *ppos,
2278 size_t count, ssize_t written)
2279{
2280 struct file *file = iocb->ki_filp;
2281 struct address_space *mapping = file->f_mapping;
2282 const struct address_space_operations *a_ops = mapping->a_ops;
2283 struct inode *inode = mapping->host;
2284 ssize_t status;
2285 struct iov_iter i;
2286
2287 iov_iter_init(&i, iov, nr_segs, count, written);
2288 if (a_ops->write_begin)
2289 status = generic_perform_write(file, &i, pos);
2290 else
2291 status = generic_perform_write_2copy(file, &i, pos);
1da177e4 2292
1da177e4 2293 if (likely(status >= 0)) {
afddba49
NP
2294 written += status;
2295 *ppos = pos + status;
2296
2297 /*
2298 * For now, when the user asks for O_SYNC, we'll actually give
2299 * O_DSYNC
2300 */
1da177e4
LT
2301 if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2302 if (!a_ops->writepage || !is_sync_kiocb(iocb))
2303 status = generic_osync_inode(inode, mapping,
2304 OSYNC_METADATA|OSYNC_DATA);
2305 }
2306 }
2307
2308 /*
2309 * If we get here for O_DIRECT writes then we must have fallen through
2310 * to buffered writes (block instantiation inside i_size). So we sync
2311 * the file data here, to try to honour O_DIRECT expectations.
2312 */
2313 if (unlikely(file->f_flags & O_DIRECT) && written)
2314 status = filemap_write_and_wait(mapping);
2315
1da177e4
LT
2316 return written ? written : status;
2317}
2318EXPORT_SYMBOL(generic_file_buffered_write);
2319
5ce7852c 2320static ssize_t
1da177e4
LT
2321__generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2322 unsigned long nr_segs, loff_t *ppos)
2323{
2324 struct file *file = iocb->ki_filp;
fb5527e6 2325 struct address_space * mapping = file->f_mapping;
1da177e4
LT
2326 size_t ocount; /* original count */
2327 size_t count; /* after file limit checks */
2328 struct inode *inode = mapping->host;
1da177e4
LT
2329 loff_t pos;
2330 ssize_t written;
2331 ssize_t err;
2332
2333 ocount = 0;
0ceb3314
DM
2334 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2335 if (err)
2336 return err;
1da177e4
LT
2337
2338 count = ocount;
2339 pos = *ppos;
2340
2341 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2342
2343 /* We can write back this queue in page reclaim */
2344 current->backing_dev_info = mapping->backing_dev_info;
2345 written = 0;
2346
2347 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2348 if (err)
2349 goto out;
2350
2351 if (count == 0)
2352 goto out;
2353
d3ac7f89 2354 err = remove_suid(file->f_path.dentry);
1da177e4
LT
2355 if (err)
2356 goto out;
2357
870f4817 2358 file_update_time(file);
1da177e4
LT
2359
2360 /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2361 if (unlikely(file->f_flags & O_DIRECT)) {
fb5527e6
JM
2362 loff_t endbyte;
2363 ssize_t written_buffered;
2364
2365 written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2366 ppos, count, ocount);
1da177e4
LT
2367 if (written < 0 || written == count)
2368 goto out;
2369 /*
2370 * direct-io write to a hole: fall through to buffered I/O
2371 * for completing the rest of the request.
2372 */
2373 pos += written;
2374 count -= written;
fb5527e6
JM
2375 written_buffered = generic_file_buffered_write(iocb, iov,
2376 nr_segs, pos, ppos, count,
2377 written);
2378 /*
2379 * If generic_file_buffered_write() retuned a synchronous error
2380 * then we want to return the number of bytes which were
2381 * direct-written, or the error code if that was zero. Note
2382 * that this differs from normal direct-io semantics, which
2383 * will return -EFOO even if some bytes were written.
2384 */
2385 if (written_buffered < 0) {
2386 err = written_buffered;
2387 goto out;
2388 }
1da177e4 2389
fb5527e6
JM
2390 /*
2391 * We need to ensure that the page cache pages are written to
2392 * disk and invalidated to preserve the expected O_DIRECT
2393 * semantics.
2394 */
2395 endbyte = pos + written_buffered - written - 1;
ef51c976
MF
2396 err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
2397 SYNC_FILE_RANGE_WAIT_BEFORE|
2398 SYNC_FILE_RANGE_WRITE|
2399 SYNC_FILE_RANGE_WAIT_AFTER);
fb5527e6
JM
2400 if (err == 0) {
2401 written = written_buffered;
2402 invalidate_mapping_pages(mapping,
2403 pos >> PAGE_CACHE_SHIFT,
2404 endbyte >> PAGE_CACHE_SHIFT);
2405 } else {
2406 /*
2407 * We don't know how much we wrote, so just return
2408 * the number of bytes which were direct-written
2409 */
2410 }
2411 } else {
2412 written = generic_file_buffered_write(iocb, iov, nr_segs,
2413 pos, ppos, count, written);
2414 }
1da177e4
LT
2415out:
2416 current->backing_dev_info = NULL;
2417 return written ? written : err;
2418}
1da177e4 2419
027445c3
BP
2420ssize_t generic_file_aio_write_nolock(struct kiocb *iocb,
2421 const struct iovec *iov, unsigned long nr_segs, loff_t pos)
1da177e4
LT
2422{
2423 struct file *file = iocb->ki_filp;
2424 struct address_space *mapping = file->f_mapping;
2425 struct inode *inode = mapping->host;
2426 ssize_t ret;
1da177e4 2427
027445c3
BP
2428 BUG_ON(iocb->ki_pos != pos);
2429
2430 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2431 &iocb->ki_pos);
1da177e4
LT
2432
2433 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
027445c3 2434 ssize_t err;
1da177e4
LT
2435
2436 err = sync_page_range_nolock(inode, mapping, pos, ret);
2437 if (err < 0)
2438 ret = err;
2439 }
2440 return ret;
2441}
027445c3 2442EXPORT_SYMBOL(generic_file_aio_write_nolock);
1da177e4 2443
027445c3
BP
2444ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2445 unsigned long nr_segs, loff_t pos)
1da177e4
LT
2446{
2447 struct file *file = iocb->ki_filp;
2448 struct address_space *mapping = file->f_mapping;
2449 struct inode *inode = mapping->host;
2450 ssize_t ret;
1da177e4
LT
2451
2452 BUG_ON(iocb->ki_pos != pos);
2453
1b1dcc1b 2454 mutex_lock(&inode->i_mutex);
027445c3
BP
2455 ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2456 &iocb->ki_pos);
1b1dcc1b 2457 mutex_unlock(&inode->i_mutex);
1da177e4
LT
2458
2459 if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2460 ssize_t err;
2461
2462 err = sync_page_range(inode, mapping, pos, ret);
2463 if (err < 0)
2464 ret = err;
2465 }
2466 return ret;
2467}
2468EXPORT_SYMBOL(generic_file_aio_write);
2469
1da177e4 2470/*
1b1dcc1b 2471 * Called under i_mutex for writes to S_ISREG files. Returns -EIO if something
1da177e4
LT
2472 * went wrong during pagecache shootdown.
2473 */
5ce7852c 2474static ssize_t
1da177e4
LT
2475generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2476 loff_t offset, unsigned long nr_segs)
2477{
2478 struct file *file = iocb->ki_filp;
2479 struct address_space *mapping = file->f_mapping;
2480 ssize_t retval;
65b8291c
ZB
2481 size_t write_len;
2482 pgoff_t end = 0; /* silence gcc */
1da177e4
LT
2483
2484 /*
2485 * If it's a write, unmap all mmappings of the file up-front. This
2486 * will cause any pte dirty bits to be propagated into the pageframes
2487 * for the subsequent filemap_write_and_wait().
2488 */
2489 if (rw == WRITE) {
2490 write_len = iov_length(iov, nr_segs);
65b8291c 2491 end = (offset + write_len - 1) >> PAGE_CACHE_SHIFT;
1da177e4
LT
2492 if (mapping_mapped(mapping))
2493 unmap_mapping_range(mapping, offset, write_len, 0);
2494 }
2495
2496 retval = filemap_write_and_wait(mapping);
65b8291c
ZB
2497 if (retval)
2498 goto out;
2499
2500 /*
2501 * After a write we want buffered reads to be sure to go to disk to get
2502 * the new data. We invalidate clean cached page from the region we're
2503 * about to write. We do this *before* the write so that we can return
2504 * -EIO without clobbering -EIOCBQUEUED from ->direct_IO().
2505 */
2506 if (rw == WRITE && mapping->nrpages) {
2507 retval = invalidate_inode_pages2_range(mapping,
1da177e4 2508 offset >> PAGE_CACHE_SHIFT, end);
65b8291c
ZB
2509 if (retval)
2510 goto out;
1da177e4 2511 }
65b8291c
ZB
2512
2513 retval = mapping->a_ops->direct_IO(rw, iocb, iov, offset, nr_segs);
2514 if (retval)
2515 goto out;
2516
2517 /*
2518 * Finally, try again to invalidate clean pages which might have been
2519 * faulted in by get_user_pages() if the source of the write was an
2520 * mmap()ed region of the file we're writing. That's a pretty crazy
2521 * thing to do, so we don't support it 100%. If this invalidation
2522 * fails and we have -EIOCBQUEUED we ignore the failure.
2523 */
2524 if (rw == WRITE && mapping->nrpages) {
2525 int err = invalidate_inode_pages2_range(mapping,
2526 offset >> PAGE_CACHE_SHIFT, end);
2527 if (err && retval >= 0)
2528 retval = err;
2529 }
2530out:
1da177e4
LT
2531 return retval;
2532}
cf9a2ae8
DH
2533
2534/**
2535 * try_to_release_page() - release old fs-specific metadata on a page
2536 *
2537 * @page: the page which the kernel is trying to free
2538 * @gfp_mask: memory allocation flags (and I/O mode)
2539 *
2540 * The address_space is to try to release any data against the page
2541 * (presumably at page->private). If the release was successful, return `1'.
2542 * Otherwise return zero.
2543 *
2544 * The @gfp_mask argument specifies whether I/O may be performed to release
2545 * this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
2546 *
2547 * NOTE: @gfp_mask may go away, and this function may become non-blocking.
2548 */
2549int try_to_release_page(struct page *page, gfp_t gfp_mask)
2550{
2551 struct address_space * const mapping = page->mapping;
2552
2553 BUG_ON(!PageLocked(page));
2554 if (PageWriteback(page))
2555 return 0;
2556
2557 if (mapping && mapping->a_ops->releasepage)
2558 return mapping->a_ops->releasepage(page, gfp_mask);
2559 return try_to_free_buffers(page);
2560}
2561
2562EXPORT_SYMBOL(try_to_release_page);