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