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