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