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