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