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