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