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