1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/mm/filemap.c
4 *
5 * Copyright (C) 1994-1999 Linus Torvalds
6 */
7
8 /*
9 * This file handles the generic file mmap semantics used by
10 * most "normal" filesystems (but you don't /have/ to use this:
11 * the NFS filesystem used to do this differently, for example)
12 */
13 #include <linux/export.h>
14 #include <linux/compiler.h>
15 #include <linux/dax.h>
16 #include <linux/fs.h>
17 #include <linux/sched/signal.h>
18 #include <linux/uaccess.h>
19 #include <linux/capability.h>
20 #include <linux/kernel_stat.h>
21 #include <linux/gfp.h>
22 #include <linux/mm.h>
23 #include <linux/swap.h>
24 #include <linux/mman.h>
25 #include <linux/pagemap.h>
26 #include <linux/file.h>
27 #include <linux/uio.h>
28 #include <linux/error-injection.h>
29 #include <linux/hash.h>
30 #include <linux/writeback.h>
31 #include <linux/backing-dev.h>
32 #include <linux/pagevec.h>
33 #include <linux/blkdev.h>
34 #include <linux/security.h>
35 #include <linux/cpuset.h>
36 #include <linux/hugetlb.h>
37 #include <linux/memcontrol.h>
38 #include <linux/cleancache.h>
39 #include <linux/shmem_fs.h>
40 #include <linux/rmap.h>
41 #include <linux/delayacct.h>
42 #include <linux/psi.h>
43 #include <linux/ramfs.h>
44 #include <linux/page_idle.h>
45 #include <asm/pgalloc.h>
46 #include <asm/tlbflush.h>
47 #include "internal.h"
48
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/filemap.h>
51
52 /*
53 * FIXME: remove all knowledge of the buffer layer from the core VM
54 */
55 #include <linux/buffer_head.h> /* for try_to_free_buffers */
56
57 #include <asm/mman.h>
58
59 /*
60 * Shared mappings implemented 30.11.1994. It's not fully working yet,
61 * though.
62 *
63 * Shared mappings now work. 15.8.1995 Bruno.
64 *
65 * finished 'unifying' the page and buffer cache and SMP-threaded the
66 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
67 *
68 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
69 */
70
71 /*
72 * Lock ordering:
73 *
74 * ->i_mmap_rwsem (truncate_pagecache)
75 * ->private_lock (__free_pte->__set_page_dirty_buffers)
76 * ->swap_lock (exclusive_swap_page, others)
77 * ->i_pages lock
78 *
79 * ->i_rwsem
80 * ->invalidate_lock (acquired by fs in truncate path)
81 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
82 *
83 * ->mmap_lock
84 * ->i_mmap_rwsem
85 * ->page_table_lock or pte_lock (various, mainly in memory.c)
86 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
87 *
88 * ->mmap_lock
89 * ->invalidate_lock (filemap_fault)
90 * ->lock_page (filemap_fault, access_process_vm)
91 *
92 * ->i_rwsem (generic_perform_write)
93 * ->mmap_lock (fault_in_readable->do_page_fault)
94 *
95 * bdi->wb.list_lock
96 * sb_lock (fs/fs-writeback.c)
97 * ->i_pages lock (__sync_single_inode)
98 *
99 * ->i_mmap_rwsem
100 * ->anon_vma.lock (vma_adjust)
101 *
102 * ->anon_vma.lock
103 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
104 *
105 * ->page_table_lock or pte_lock
106 * ->swap_lock (try_to_unmap_one)
107 * ->private_lock (try_to_unmap_one)
108 * ->i_pages lock (try_to_unmap_one)
109 * ->lruvec->lru_lock (follow_page->mark_page_accessed)
110 * ->lruvec->lru_lock (check_pte_range->isolate_lru_page)
111 * ->private_lock (page_remove_rmap->set_page_dirty)
112 * ->i_pages lock (page_remove_rmap->set_page_dirty)
113 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
114 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
115 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
116 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
117 * ->inode->i_lock (zap_pte_range->set_page_dirty)
118 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
119 *
120 * ->i_mmap_rwsem
121 * ->tasklist_lock (memory_failure, collect_procs_ao)
122 */
123
124 /* Export tracepoints that act as a bare tracehook */
125 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_filemap_delete_from_page_cache);
126 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_filemap_add_to_page_cache);
127
page_cache_delete(struct address_space * mapping,struct page * page,void * shadow)128 static void page_cache_delete(struct address_space *mapping,
129 struct page *page, void *shadow)
130 {
131 XA_STATE(xas, &mapping->i_pages, page->index);
132 unsigned int nr = 1;
133
134 mapping_set_update(&xas, mapping);
135
136 /* hugetlb pages are represented by a single entry in the xarray */
137 if (!PageHuge(page)) {
138 xas_set_order(&xas, page->index, compound_order(page));
139 nr = compound_nr(page);
140 }
141
142 VM_BUG_ON_PAGE(!PageLocked(page), page);
143 VM_BUG_ON_PAGE(PageTail(page), page);
144 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
145
146 xas_store(&xas, shadow);
147 xas_init_marks(&xas);
148
149 page->mapping = NULL;
150 /* Leave page->index set: truncation lookup relies upon it */
151 mapping->nrpages -= nr;
152 }
153
unaccount_page_cache_page(struct address_space * mapping,struct page * page)154 static void unaccount_page_cache_page(struct address_space *mapping,
155 struct page *page)
156 {
157 int nr;
158
159 /*
160 * if we're uptodate, flush out into the cleancache, otherwise
161 * invalidate any existing cleancache entries. We can't leave
162 * stale data around in the cleancache once our page is gone
163 */
164 if (PageUptodate(page) && PageMappedToDisk(page))
165 cleancache_put_page(page);
166 else
167 cleancache_invalidate_page(mapping, page);
168
169 VM_BUG_ON_PAGE(PageTail(page), page);
170 VM_BUG_ON_PAGE(page_mapped(page), page);
171 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
172 int mapcount;
173
174 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
175 current->comm, page_to_pfn(page));
176 dump_page(page, "still mapped when deleted");
177 dump_stack();
178 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
179
180 mapcount = page_mapcount(page);
181 if (mapping_exiting(mapping) &&
182 page_count(page) >= mapcount + 2) {
183 /*
184 * All vmas have already been torn down, so it's
185 * a good bet that actually the page is unmapped,
186 * and we'd prefer not to leak it: if we're wrong,
187 * some other bad page check should catch it later.
188 */
189 page_mapcount_reset(page);
190 page_ref_sub(page, mapcount);
191 }
192 }
193
194 /* hugetlb pages do not participate in page cache accounting. */
195 if (PageHuge(page))
196 return;
197
198 nr = thp_nr_pages(page);
199
200 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
201 if (PageSwapBacked(page)) {
202 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
203 if (PageTransHuge(page))
204 __mod_lruvec_page_state(page, NR_SHMEM_THPS, -nr);
205 } else if (PageTransHuge(page)) {
206 __mod_lruvec_page_state(page, NR_FILE_THPS, -nr);
207 filemap_nr_thps_dec(mapping);
208 }
209
210 /*
211 * At this point page must be either written or cleaned by
212 * truncate. Dirty page here signals a bug and loss of
213 * unwritten data.
214 *
215 * This fixes dirty accounting after removing the page entirely
216 * but leaves PageDirty set: it has no effect for truncated
217 * page and anyway will be cleared before returning page into
218 * buddy allocator.
219 */
220 if (WARN_ON_ONCE(PageDirty(page)))
221 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
222 }
223
224 /*
225 * Delete a page from the page cache and free it. Caller has to make
226 * sure the page is locked and that nobody else uses it - or that usage
227 * is safe. The caller must hold the i_pages lock.
228 */
__delete_from_page_cache(struct page * page,void * shadow)229 void __delete_from_page_cache(struct page *page, void *shadow)
230 {
231 struct address_space *mapping = page->mapping;
232
233 trace_mm_filemap_delete_from_page_cache(page);
234
235 unaccount_page_cache_page(mapping, page);
236 page_cache_delete(mapping, page, shadow);
237 }
238
page_cache_free_page(struct address_space * mapping,struct page * page)239 static void page_cache_free_page(struct address_space *mapping,
240 struct page *page)
241 {
242 void (*freepage)(struct page *);
243
244 freepage = mapping->a_ops->freepage;
245 if (freepage)
246 freepage(page);
247
248 if (PageTransHuge(page) && !PageHuge(page)) {
249 page_ref_sub(page, thp_nr_pages(page));
250 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
251 } else {
252 put_page(page);
253 }
254 }
255
256 /**
257 * delete_from_page_cache - delete page from page cache
258 * @page: the page which the kernel is trying to remove from page cache
259 *
260 * This must be called only on pages that have been verified to be in the page
261 * cache and locked. It will never put the page into the free list, the caller
262 * has a reference on the page.
263 */
delete_from_page_cache(struct page * page)264 void delete_from_page_cache(struct page *page)
265 {
266 struct address_space *mapping = page_mapping(page);
267
268 BUG_ON(!PageLocked(page));
269 xa_lock_irq(&mapping->i_pages);
270 __delete_from_page_cache(page, NULL);
271 xa_unlock_irq(&mapping->i_pages);
272
273 page_cache_free_page(mapping, page);
274 }
275 EXPORT_SYMBOL(delete_from_page_cache);
276
277 /*
278 * page_cache_delete_batch - delete several pages from page cache
279 * @mapping: the mapping to which pages belong
280 * @pvec: pagevec with pages to delete
281 *
282 * The function walks over mapping->i_pages and removes pages passed in @pvec
283 * from the mapping. The function expects @pvec to be sorted by page index
284 * and is optimised for it to be dense.
285 * It tolerates holes in @pvec (mapping entries at those indices are not
286 * modified). The function expects only THP head pages to be present in the
287 * @pvec.
288 *
289 * The function expects the i_pages lock to be held.
290 */
page_cache_delete_batch(struct address_space * mapping,struct pagevec * pvec)291 static void page_cache_delete_batch(struct address_space *mapping,
292 struct pagevec *pvec)
293 {
294 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
295 int total_pages = 0;
296 int i = 0;
297 struct page *page;
298
299 mapping_set_update(&xas, mapping);
300 xas_for_each(&xas, page, ULONG_MAX) {
301 if (i >= pagevec_count(pvec))
302 break;
303
304 /* A swap/dax/shadow entry got inserted? Skip it. */
305 if (xa_is_value(page))
306 continue;
307 /*
308 * A page got inserted in our range? Skip it. We have our
309 * pages locked so they are protected from being removed.
310 * If we see a page whose index is higher than ours, it
311 * means our page has been removed, which shouldn't be
312 * possible because we're holding the PageLock.
313 */
314 if (page != pvec->pages[i]) {
315 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
316 page);
317 continue;
318 }
319
320 WARN_ON_ONCE(!PageLocked(page));
321
322 if (page->index == xas.xa_index)
323 page->mapping = NULL;
324 /* Leave page->index set: truncation lookup relies on it */
325
326 /*
327 * Move to the next page in the vector if this is a regular
328 * page or the index is of the last sub-page of this compound
329 * page.
330 */
331 if (page->index + compound_nr(page) - 1 == xas.xa_index)
332 i++;
333 xas_store(&xas, NULL);
334 total_pages++;
335 }
336 mapping->nrpages -= total_pages;
337 }
338
delete_from_page_cache_batch(struct address_space * mapping,struct pagevec * pvec)339 void delete_from_page_cache_batch(struct address_space *mapping,
340 struct pagevec *pvec)
341 {
342 int i;
343
344 if (!pagevec_count(pvec))
345 return;
346
347 xa_lock_irq(&mapping->i_pages);
348 for (i = 0; i < pagevec_count(pvec); i++) {
349 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
350
351 unaccount_page_cache_page(mapping, pvec->pages[i]);
352 }
353 page_cache_delete_batch(mapping, pvec);
354 xa_unlock_irq(&mapping->i_pages);
355
356 for (i = 0; i < pagevec_count(pvec); i++)
357 page_cache_free_page(mapping, pvec->pages[i]);
358 }
359
filemap_check_errors(struct address_space * mapping)360 int filemap_check_errors(struct address_space *mapping)
361 {
362 int ret = 0;
363 /* Check for outstanding write errors */
364 if (test_bit(AS_ENOSPC, &mapping->flags) &&
365 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
366 ret = -ENOSPC;
367 if (test_bit(AS_EIO, &mapping->flags) &&
368 test_and_clear_bit(AS_EIO, &mapping->flags))
369 ret = -EIO;
370 return ret;
371 }
372 EXPORT_SYMBOL(filemap_check_errors);
373
filemap_check_and_keep_errors(struct address_space * mapping)374 static int filemap_check_and_keep_errors(struct address_space *mapping)
375 {
376 /* Check for outstanding write errors */
377 if (test_bit(AS_EIO, &mapping->flags))
378 return -EIO;
379 if (test_bit(AS_ENOSPC, &mapping->flags))
380 return -ENOSPC;
381 return 0;
382 }
383
384 /**
385 * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
386 * @mapping: address space structure to write
387 * @wbc: the writeback_control controlling the writeout
388 *
389 * Call writepages on the mapping using the provided wbc to control the
390 * writeout.
391 *
392 * Return: %0 on success, negative error code otherwise.
393 */
filemap_fdatawrite_wbc(struct address_space * mapping,struct writeback_control * wbc)394 int filemap_fdatawrite_wbc(struct address_space *mapping,
395 struct writeback_control *wbc)
396 {
397 int ret;
398
399 if (!mapping_can_writeback(mapping) ||
400 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
401 return 0;
402
403 wbc_attach_fdatawrite_inode(wbc, mapping->host);
404 ret = do_writepages(mapping, wbc);
405 wbc_detach_inode(wbc);
406 return ret;
407 }
408 EXPORT_SYMBOL(filemap_fdatawrite_wbc);
409
410 /**
411 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
412 * @mapping: address space structure to write
413 * @start: offset in bytes where the range starts
414 * @end: offset in bytes where the range ends (inclusive)
415 * @sync_mode: enable synchronous operation
416 *
417 * Start writeback against all of a mapping's dirty pages that lie
418 * within the byte offsets <start, end> inclusive.
419 *
420 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
421 * opposed to a regular memory cleansing writeback. The difference between
422 * these two operations is that if a dirty page/buffer is encountered, it must
423 * be waited upon, and not just skipped over.
424 *
425 * Return: %0 on success, negative error code otherwise.
426 */
__filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end,int sync_mode)427 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
428 loff_t end, int sync_mode)
429 {
430 struct writeback_control wbc = {
431 .sync_mode = sync_mode,
432 .nr_to_write = LONG_MAX,
433 .range_start = start,
434 .range_end = end,
435 };
436
437 return filemap_fdatawrite_wbc(mapping, &wbc);
438 }
439
__filemap_fdatawrite(struct address_space * mapping,int sync_mode)440 static inline int __filemap_fdatawrite(struct address_space *mapping,
441 int sync_mode)
442 {
443 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
444 }
445
filemap_fdatawrite(struct address_space * mapping)446 int filemap_fdatawrite(struct address_space *mapping)
447 {
448 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
449 }
450 EXPORT_SYMBOL(filemap_fdatawrite);
451
filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end)452 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
453 loff_t end)
454 {
455 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
456 }
457 EXPORT_SYMBOL(filemap_fdatawrite_range);
458
459 /**
460 * filemap_flush - mostly a non-blocking flush
461 * @mapping: target address_space
462 *
463 * This is a mostly non-blocking flush. Not suitable for data-integrity
464 * purposes - I/O may not be started against all dirty pages.
465 *
466 * Return: %0 on success, negative error code otherwise.
467 */
filemap_flush(struct address_space * mapping)468 int filemap_flush(struct address_space *mapping)
469 {
470 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
471 }
472 EXPORT_SYMBOL(filemap_flush);
473
474 /**
475 * filemap_range_has_page - check if a page exists in range.
476 * @mapping: address space within which to check
477 * @start_byte: offset in bytes where the range starts
478 * @end_byte: offset in bytes where the range ends (inclusive)
479 *
480 * Find at least one page in the range supplied, usually used to check if
481 * direct writing in this range will trigger a writeback.
482 *
483 * Return: %true if at least one page exists in the specified range,
484 * %false otherwise.
485 */
filemap_range_has_page(struct address_space * mapping,loff_t start_byte,loff_t end_byte)486 bool filemap_range_has_page(struct address_space *mapping,
487 loff_t start_byte, loff_t end_byte)
488 {
489 struct page *page;
490 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
491 pgoff_t max = end_byte >> PAGE_SHIFT;
492
493 if (end_byte < start_byte)
494 return false;
495
496 rcu_read_lock();
497 for (;;) {
498 page = xas_find(&xas, max);
499 if (xas_retry(&xas, page))
500 continue;
501 /* Shadow entries don't count */
502 if (xa_is_value(page))
503 continue;
504 /*
505 * We don't need to try to pin this page; we're about to
506 * release the RCU lock anyway. It is enough to know that
507 * there was a page here recently.
508 */
509 break;
510 }
511 rcu_read_unlock();
512
513 return page != NULL;
514 }
515 EXPORT_SYMBOL(filemap_range_has_page);
516
__filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)517 static void __filemap_fdatawait_range(struct address_space *mapping,
518 loff_t start_byte, loff_t end_byte)
519 {
520 pgoff_t index = start_byte >> PAGE_SHIFT;
521 pgoff_t end = end_byte >> PAGE_SHIFT;
522 struct pagevec pvec;
523 int nr_pages;
524
525 if (end_byte < start_byte)
526 return;
527
528 pagevec_init(&pvec);
529 while (index <= end) {
530 unsigned i;
531
532 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
533 end, PAGECACHE_TAG_WRITEBACK);
534 if (!nr_pages)
535 break;
536
537 for (i = 0; i < nr_pages; i++) {
538 struct page *page = pvec.pages[i];
539
540 wait_on_page_writeback(page);
541 ClearPageError(page);
542 }
543 pagevec_release(&pvec);
544 cond_resched();
545 }
546 }
547
548 /**
549 * filemap_fdatawait_range - wait for writeback to complete
550 * @mapping: address space structure to wait for
551 * @start_byte: offset in bytes where the range starts
552 * @end_byte: offset in bytes where the range ends (inclusive)
553 *
554 * Walk the list of under-writeback pages of the given address space
555 * in the given range and wait for all of them. Check error status of
556 * the address space and return it.
557 *
558 * Since the error status of the address space is cleared by this function,
559 * callers are responsible for checking the return value and handling and/or
560 * reporting the error.
561 *
562 * Return: error status of the address space.
563 */
filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)564 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
565 loff_t end_byte)
566 {
567 __filemap_fdatawait_range(mapping, start_byte, end_byte);
568 return filemap_check_errors(mapping);
569 }
570 EXPORT_SYMBOL(filemap_fdatawait_range);
571
572 /**
573 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
574 * @mapping: address space structure to wait for
575 * @start_byte: offset in bytes where the range starts
576 * @end_byte: offset in bytes where the range ends (inclusive)
577 *
578 * Walk the list of under-writeback pages of the given address space in the
579 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
580 * this function does not clear error status of the address space.
581 *
582 * Use this function if callers don't handle errors themselves. Expected
583 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
584 * fsfreeze(8)
585 */
filemap_fdatawait_range_keep_errors(struct address_space * mapping,loff_t start_byte,loff_t end_byte)586 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
587 loff_t start_byte, loff_t end_byte)
588 {
589 __filemap_fdatawait_range(mapping, start_byte, end_byte);
590 return filemap_check_and_keep_errors(mapping);
591 }
592 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
593
594 /**
595 * file_fdatawait_range - wait for writeback to complete
596 * @file: file pointing to address space structure to wait for
597 * @start_byte: offset in bytes where the range starts
598 * @end_byte: offset in bytes where the range ends (inclusive)
599 *
600 * Walk the list of under-writeback pages of the address space that file
601 * refers to, in the given range and wait for all of them. Check error
602 * status of the address space vs. the file->f_wb_err cursor and return it.
603 *
604 * Since the error status of the file is advanced by this function,
605 * callers are responsible for checking the return value and handling and/or
606 * reporting the error.
607 *
608 * Return: error status of the address space vs. the file->f_wb_err cursor.
609 */
file_fdatawait_range(struct file * file,loff_t start_byte,loff_t end_byte)610 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
611 {
612 struct address_space *mapping = file->f_mapping;
613
614 __filemap_fdatawait_range(mapping, start_byte, end_byte);
615 return file_check_and_advance_wb_err(file);
616 }
617 EXPORT_SYMBOL(file_fdatawait_range);
618
619 /**
620 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
621 * @mapping: address space structure to wait for
622 *
623 * Walk the list of under-writeback pages of the given address space
624 * and wait for all of them. Unlike filemap_fdatawait(), this function
625 * does not clear error status of the address space.
626 *
627 * Use this function if callers don't handle errors themselves. Expected
628 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
629 * fsfreeze(8)
630 *
631 * Return: error status of the address space.
632 */
filemap_fdatawait_keep_errors(struct address_space * mapping)633 int filemap_fdatawait_keep_errors(struct address_space *mapping)
634 {
635 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
636 return filemap_check_and_keep_errors(mapping);
637 }
638 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
639
640 /* Returns true if writeback might be needed or already in progress. */
mapping_needs_writeback(struct address_space * mapping)641 static bool mapping_needs_writeback(struct address_space *mapping)
642 {
643 return mapping->nrpages;
644 }
645
646 /**
647 * filemap_range_needs_writeback - check if range potentially needs writeback
648 * @mapping: address space within which to check
649 * @start_byte: offset in bytes where the range starts
650 * @end_byte: offset in bytes where the range ends (inclusive)
651 *
652 * Find at least one page in the range supplied, usually used to check if
653 * direct writing in this range will trigger a writeback. Used by O_DIRECT
654 * read/write with IOCB_NOWAIT, to see if the caller needs to do
655 * filemap_write_and_wait_range() before proceeding.
656 *
657 * Return: %true if the caller should do filemap_write_and_wait_range() before
658 * doing O_DIRECT to a page in this range, %false otherwise.
659 */
filemap_range_needs_writeback(struct address_space * mapping,loff_t start_byte,loff_t end_byte)660 bool filemap_range_needs_writeback(struct address_space *mapping,
661 loff_t start_byte, loff_t end_byte)
662 {
663 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
664 pgoff_t max = end_byte >> PAGE_SHIFT;
665 struct page *page;
666
667 if (!mapping_needs_writeback(mapping))
668 return false;
669 if (!mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
670 !mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
671 return false;
672 if (end_byte < start_byte)
673 return false;
674
675 rcu_read_lock();
676 xas_for_each(&xas, page, max) {
677 if (xas_retry(&xas, page))
678 continue;
679 if (xa_is_value(page))
680 continue;
681 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
682 break;
683 }
684 rcu_read_unlock();
685 return page != NULL;
686 }
687 EXPORT_SYMBOL_GPL(filemap_range_needs_writeback);
688
689 /**
690 * filemap_write_and_wait_range - write out & wait on a file range
691 * @mapping: the address_space for the pages
692 * @lstart: offset in bytes where the range starts
693 * @lend: offset in bytes where the range ends (inclusive)
694 *
695 * Write out and wait upon file offsets lstart->lend, inclusive.
696 *
697 * Note that @lend is inclusive (describes the last byte to be written) so
698 * that this function can be used to write to the very end-of-file (end = -1).
699 *
700 * Return: error status of the address space.
701 */
filemap_write_and_wait_range(struct address_space * mapping,loff_t lstart,loff_t lend)702 int filemap_write_and_wait_range(struct address_space *mapping,
703 loff_t lstart, loff_t lend)
704 {
705 int err = 0;
706
707 if (mapping_needs_writeback(mapping)) {
708 err = __filemap_fdatawrite_range(mapping, lstart, lend,
709 WB_SYNC_ALL);
710 /*
711 * Even if the above returned error, the pages may be
712 * written partially (e.g. -ENOSPC), so we wait for it.
713 * But the -EIO is special case, it may indicate the worst
714 * thing (e.g. bug) happened, so we avoid waiting for it.
715 */
716 if (err != -EIO) {
717 int err2 = filemap_fdatawait_range(mapping,
718 lstart, lend);
719 if (!err)
720 err = err2;
721 } else {
722 /* Clear any previously stored errors */
723 filemap_check_errors(mapping);
724 }
725 } else {
726 err = filemap_check_errors(mapping);
727 }
728 return err;
729 }
730 EXPORT_SYMBOL(filemap_write_and_wait_range);
731
__filemap_set_wb_err(struct address_space * mapping,int err)732 void __filemap_set_wb_err(struct address_space *mapping, int err)
733 {
734 errseq_t eseq = errseq_set(&mapping->wb_err, err);
735
736 trace_filemap_set_wb_err(mapping, eseq);
737 }
738 EXPORT_SYMBOL(__filemap_set_wb_err);
739
740 /**
741 * file_check_and_advance_wb_err - report wb error (if any) that was previously
742 * and advance wb_err to current one
743 * @file: struct file on which the error is being reported
744 *
745 * When userland calls fsync (or something like nfsd does the equivalent), we
746 * want to report any writeback errors that occurred since the last fsync (or
747 * since the file was opened if there haven't been any).
748 *
749 * Grab the wb_err from the mapping. If it matches what we have in the file,
750 * then just quickly return 0. The file is all caught up.
751 *
752 * If it doesn't match, then take the mapping value, set the "seen" flag in
753 * it and try to swap it into place. If it works, or another task beat us
754 * to it with the new value, then update the f_wb_err and return the error
755 * portion. The error at this point must be reported via proper channels
756 * (a'la fsync, or NFS COMMIT operation, etc.).
757 *
758 * While we handle mapping->wb_err with atomic operations, the f_wb_err
759 * value is protected by the f_lock since we must ensure that it reflects
760 * the latest value swapped in for this file descriptor.
761 *
762 * Return: %0 on success, negative error code otherwise.
763 */
file_check_and_advance_wb_err(struct file * file)764 int file_check_and_advance_wb_err(struct file *file)
765 {
766 int err = 0;
767 errseq_t old = READ_ONCE(file->f_wb_err);
768 struct address_space *mapping = file->f_mapping;
769
770 /* Locklessly handle the common case where nothing has changed */
771 if (errseq_check(&mapping->wb_err, old)) {
772 /* Something changed, must use slow path */
773 spin_lock(&file->f_lock);
774 old = file->f_wb_err;
775 err = errseq_check_and_advance(&mapping->wb_err,
776 &file->f_wb_err);
777 trace_file_check_and_advance_wb_err(file, old);
778 spin_unlock(&file->f_lock);
779 }
780
781 /*
782 * We're mostly using this function as a drop in replacement for
783 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
784 * that the legacy code would have had on these flags.
785 */
786 clear_bit(AS_EIO, &mapping->flags);
787 clear_bit(AS_ENOSPC, &mapping->flags);
788 return err;
789 }
790 EXPORT_SYMBOL(file_check_and_advance_wb_err);
791
792 /**
793 * file_write_and_wait_range - write out & wait on a file range
794 * @file: file pointing to address_space with pages
795 * @lstart: offset in bytes where the range starts
796 * @lend: offset in bytes where the range ends (inclusive)
797 *
798 * Write out and wait upon file offsets lstart->lend, inclusive.
799 *
800 * Note that @lend is inclusive (describes the last byte to be written) so
801 * that this function can be used to write to the very end-of-file (end = -1).
802 *
803 * After writing out and waiting on the data, we check and advance the
804 * f_wb_err cursor to the latest value, and return any errors detected there.
805 *
806 * Return: %0 on success, negative error code otherwise.
807 */
file_write_and_wait_range(struct file * file,loff_t lstart,loff_t lend)808 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
809 {
810 int err = 0, err2;
811 struct address_space *mapping = file->f_mapping;
812
813 if (mapping_needs_writeback(mapping)) {
814 err = __filemap_fdatawrite_range(mapping, lstart, lend,
815 WB_SYNC_ALL);
816 /* See comment of filemap_write_and_wait() */
817 if (err != -EIO)
818 __filemap_fdatawait_range(mapping, lstart, lend);
819 }
820 err2 = file_check_and_advance_wb_err(file);
821 if (!err)
822 err = err2;
823 return err;
824 }
825 EXPORT_SYMBOL(file_write_and_wait_range);
826
827 /**
828 * replace_page_cache_page - replace a pagecache page with a new one
829 * @old: page to be replaced
830 * @new: page to replace with
831 *
832 * This function replaces a page in the pagecache with a new one. On
833 * success it acquires the pagecache reference for the new page and
834 * drops it for the old page. Both the old and new pages must be
835 * locked. This function does not add the new page to the LRU, the
836 * caller must do that.
837 *
838 * The remove + add is atomic. This function cannot fail.
839 */
replace_page_cache_page(struct page * old,struct page * new)840 void replace_page_cache_page(struct page *old, struct page *new)
841 {
842 struct address_space *mapping = old->mapping;
843 void (*freepage)(struct page *) = mapping->a_ops->freepage;
844 pgoff_t offset = old->index;
845 XA_STATE(xas, &mapping->i_pages, offset);
846
847 VM_BUG_ON_PAGE(!PageLocked(old), old);
848 VM_BUG_ON_PAGE(!PageLocked(new), new);
849 VM_BUG_ON_PAGE(new->mapping, new);
850
851 get_page(new);
852 new->mapping = mapping;
853 new->index = offset;
854
855 mem_cgroup_migrate(old, new);
856
857 xas_lock_irq(&xas);
858 xas_store(&xas, new);
859
860 old->mapping = NULL;
861 /* hugetlb pages do not participate in page cache accounting. */
862 if (!PageHuge(old))
863 __dec_lruvec_page_state(old, NR_FILE_PAGES);
864 if (!PageHuge(new))
865 __inc_lruvec_page_state(new, NR_FILE_PAGES);
866 if (PageSwapBacked(old))
867 __dec_lruvec_page_state(old, NR_SHMEM);
868 if (PageSwapBacked(new))
869 __inc_lruvec_page_state(new, NR_SHMEM);
870 xas_unlock_irq(&xas);
871 if (freepage)
872 freepage(old);
873 put_page(old);
874 }
875 EXPORT_SYMBOL_GPL(replace_page_cache_page);
876
__add_to_page_cache_locked(struct page * page,struct address_space * mapping,pgoff_t offset,gfp_t gfp,void ** shadowp)877 noinline int __add_to_page_cache_locked(struct page *page,
878 struct address_space *mapping,
879 pgoff_t offset, gfp_t gfp,
880 void **shadowp)
881 {
882 XA_STATE(xas, &mapping->i_pages, offset);
883 int huge = PageHuge(page);
884 int error;
885 bool charged = false;
886
887 VM_BUG_ON_PAGE(!PageLocked(page), page);
888 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
889 mapping_set_update(&xas, mapping);
890
891 get_page(page);
892 page->mapping = mapping;
893 page->index = offset;
894
895 if (!huge) {
896 error = mem_cgroup_charge(page, NULL, gfp);
897 if (error)
898 goto error;
899 charged = true;
900 }
901
902 gfp &= GFP_RECLAIM_MASK;
903
904 do {
905 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
906 void *entry, *old = NULL;
907
908 if (order > thp_order(page))
909 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
910 order, gfp);
911 xas_lock_irq(&xas);
912 xas_for_each_conflict(&xas, entry) {
913 old = entry;
914 if (!xa_is_value(entry)) {
915 xas_set_err(&xas, -EEXIST);
916 goto unlock;
917 }
918 }
919
920 if (old) {
921 if (shadowp)
922 *shadowp = old;
923 /* entry may have been split before we acquired lock */
924 order = xa_get_order(xas.xa, xas.xa_index);
925 if (order > thp_order(page)) {
926 xas_split(&xas, old, order);
927 xas_reset(&xas);
928 }
929 }
930
931 xas_store(&xas, page);
932 if (xas_error(&xas))
933 goto unlock;
934
935 mapping->nrpages++;
936
937 /* hugetlb pages do not participate in page cache accounting */
938 if (!huge)
939 __inc_lruvec_page_state(page, NR_FILE_PAGES);
940 unlock:
941 xas_unlock_irq(&xas);
942 } while (xas_nomem(&xas, gfp));
943
944 if (xas_error(&xas)) {
945 error = xas_error(&xas);
946 if (charged)
947 mem_cgroup_uncharge(page);
948 goto error;
949 }
950
951 trace_mm_filemap_add_to_page_cache(page);
952 return 0;
953 error:
954 page->mapping = NULL;
955 /* Leave page->index set: truncation relies upon it */
956 put_page(page);
957 return error;
958 }
959 ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
960
961 /**
962 * add_to_page_cache_locked - add a locked page to the pagecache
963 * @page: page to add
964 * @mapping: the page's address_space
965 * @offset: page index
966 * @gfp_mask: page allocation mode
967 *
968 * This function is used to add a page to the pagecache. It must be locked.
969 * This function does not add the page to the LRU. The caller must do that.
970 *
971 * Return: %0 on success, negative error code otherwise.
972 */
add_to_page_cache_locked(struct page * page,struct address_space * mapping,pgoff_t offset,gfp_t gfp_mask)973 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
974 pgoff_t offset, gfp_t gfp_mask)
975 {
976 return __add_to_page_cache_locked(page, mapping, offset,
977 gfp_mask, NULL);
978 }
979 EXPORT_SYMBOL(add_to_page_cache_locked);
980
add_to_page_cache_lru(struct page * page,struct address_space * mapping,pgoff_t offset,gfp_t gfp_mask)981 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
982 pgoff_t offset, gfp_t gfp_mask)
983 {
984 void *shadow = NULL;
985 int ret;
986
987 __SetPageLocked(page);
988 ret = __add_to_page_cache_locked(page, mapping, offset,
989 gfp_mask, &shadow);
990 if (unlikely(ret))
991 __ClearPageLocked(page);
992 else {
993 /*
994 * The page might have been evicted from cache only
995 * recently, in which case it should be activated like
996 * any other repeatedly accessed page.
997 * The exception is pages getting rewritten; evicting other
998 * data from the working set, only to cache data that will
999 * get overwritten with something else, is a waste of memory.
1000 */
1001 WARN_ON_ONCE(PageActive(page));
1002 if (!(gfp_mask & __GFP_WRITE) && shadow)
1003 workingset_refault(page, shadow);
1004 lru_cache_add(page);
1005 }
1006 return ret;
1007 }
1008 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
1009
1010 #ifdef CONFIG_NUMA
__page_cache_alloc(gfp_t gfp)1011 struct page *__page_cache_alloc(gfp_t gfp)
1012 {
1013 int n;
1014 struct page *page;
1015
1016 if (cpuset_do_page_mem_spread()) {
1017 unsigned int cpuset_mems_cookie;
1018 do {
1019 cpuset_mems_cookie = read_mems_allowed_begin();
1020 n = cpuset_mem_spread_node();
1021 page = __alloc_pages_node(n, gfp, 0);
1022 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
1023
1024 return page;
1025 }
1026 return alloc_pages(gfp, 0);
1027 }
1028 EXPORT_SYMBOL(__page_cache_alloc);
1029 #endif
1030
1031 /*
1032 * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1033 *
1034 * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1035 *
1036 * @mapping1: the first mapping to lock
1037 * @mapping2: the second mapping to lock
1038 */
filemap_invalidate_lock_two(struct address_space * mapping1,struct address_space * mapping2)1039 void filemap_invalidate_lock_two(struct address_space *mapping1,
1040 struct address_space *mapping2)
1041 {
1042 if (mapping1 > mapping2)
1043 swap(mapping1, mapping2);
1044 if (mapping1)
1045 down_write(&mapping1->invalidate_lock);
1046 if (mapping2 && mapping1 != mapping2)
1047 down_write_nested(&mapping2->invalidate_lock, 1);
1048 }
1049 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1050
1051 /*
1052 * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1053 *
1054 * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1055 *
1056 * @mapping1: the first mapping to unlock
1057 * @mapping2: the second mapping to unlock
1058 */
filemap_invalidate_unlock_two(struct address_space * mapping1,struct address_space * mapping2)1059 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1060 struct address_space *mapping2)
1061 {
1062 if (mapping1)
1063 up_write(&mapping1->invalidate_lock);
1064 if (mapping2 && mapping1 != mapping2)
1065 up_write(&mapping2->invalidate_lock);
1066 }
1067 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1068
1069 /*
1070 * In order to wait for pages to become available there must be
1071 * waitqueues associated with pages. By using a hash table of
1072 * waitqueues where the bucket discipline is to maintain all
1073 * waiters on the same queue and wake all when any of the pages
1074 * become available, and for the woken contexts to check to be
1075 * sure the appropriate page became available, this saves space
1076 * at a cost of "thundering herd" phenomena during rare hash
1077 * collisions.
1078 */
1079 #define PAGE_WAIT_TABLE_BITS 8
1080 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1081 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1082
page_waitqueue(struct page * page)1083 static wait_queue_head_t *page_waitqueue(struct page *page)
1084 {
1085 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
1086 }
1087
pagecache_init(void)1088 void __init pagecache_init(void)
1089 {
1090 int i;
1091
1092 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1093 init_waitqueue_head(&page_wait_table[i]);
1094
1095 page_writeback_init();
1096 }
1097
1098 /*
1099 * The page wait code treats the "wait->flags" somewhat unusually, because
1100 * we have multiple different kinds of waits, not just the usual "exclusive"
1101 * one.
1102 *
1103 * We have:
1104 *
1105 * (a) no special bits set:
1106 *
1107 * We're just waiting for the bit to be released, and when a waker
1108 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1109 * and remove it from the wait queue.
1110 *
1111 * Simple and straightforward.
1112 *
1113 * (b) WQ_FLAG_EXCLUSIVE:
1114 *
1115 * The waiter is waiting to get the lock, and only one waiter should
1116 * be woken up to avoid any thundering herd behavior. We'll set the
1117 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1118 *
1119 * This is the traditional exclusive wait.
1120 *
1121 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1122 *
1123 * The waiter is waiting to get the bit, and additionally wants the
1124 * lock to be transferred to it for fair lock behavior. If the lock
1125 * cannot be taken, we stop walking the wait queue without waking
1126 * the waiter.
1127 *
1128 * This is the "fair lock handoff" case, and in addition to setting
1129 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1130 * that it now has the lock.
1131 */
wake_page_function(wait_queue_entry_t * wait,unsigned mode,int sync,void * arg)1132 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1133 {
1134 unsigned int flags;
1135 struct wait_page_key *key = arg;
1136 struct wait_page_queue *wait_page
1137 = container_of(wait, struct wait_page_queue, wait);
1138
1139 if (!wake_page_match(wait_page, key))
1140 return 0;
1141
1142 /*
1143 * If it's a lock handoff wait, we get the bit for it, and
1144 * stop walking (and do not wake it up) if we can't.
1145 */
1146 flags = wait->flags;
1147 if (flags & WQ_FLAG_EXCLUSIVE) {
1148 if (test_bit(key->bit_nr, &key->page->flags))
1149 return -1;
1150 if (flags & WQ_FLAG_CUSTOM) {
1151 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1152 return -1;
1153 flags |= WQ_FLAG_DONE;
1154 }
1155 }
1156
1157 /*
1158 * We are holding the wait-queue lock, but the waiter that
1159 * is waiting for this will be checking the flags without
1160 * any locking.
1161 *
1162 * So update the flags atomically, and wake up the waiter
1163 * afterwards to avoid any races. This store-release pairs
1164 * with the load-acquire in wait_on_page_bit_common().
1165 */
1166 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1167 wake_up_state(wait->private, mode);
1168
1169 /*
1170 * Ok, we have successfully done what we're waiting for,
1171 * and we can unconditionally remove the wait entry.
1172 *
1173 * Note that this pairs with the "finish_wait()" in the
1174 * waiter, and has to be the absolute last thing we do.
1175 * After this list_del_init(&wait->entry) the wait entry
1176 * might be de-allocated and the process might even have
1177 * exited.
1178 */
1179 list_del_init_careful(&wait->entry);
1180 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1181 }
1182
wake_up_page_bit(struct page * page,int bit_nr)1183 static void wake_up_page_bit(struct page *page, int bit_nr)
1184 {
1185 wait_queue_head_t *q = page_waitqueue(page);
1186 struct wait_page_key key;
1187 unsigned long flags;
1188 wait_queue_entry_t bookmark;
1189
1190 key.page = page;
1191 key.bit_nr = bit_nr;
1192 key.page_match = 0;
1193
1194 bookmark.flags = 0;
1195 bookmark.private = NULL;
1196 bookmark.func = NULL;
1197 INIT_LIST_HEAD(&bookmark.entry);
1198
1199 spin_lock_irqsave(&q->lock, flags);
1200 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1201
1202 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1203 /*
1204 * Take a breather from holding the lock,
1205 * allow pages that finish wake up asynchronously
1206 * to acquire the lock and remove themselves
1207 * from wait queue
1208 */
1209 spin_unlock_irqrestore(&q->lock, flags);
1210 cpu_relax();
1211 spin_lock_irqsave(&q->lock, flags);
1212 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1213 }
1214
1215 /*
1216 * It is possible for other pages to have collided on the waitqueue
1217 * hash, so in that case check for a page match. That prevents a long-
1218 * term waiter
1219 *
1220 * It is still possible to miss a case here, when we woke page waiters
1221 * and removed them from the waitqueue, but there are still other
1222 * page waiters.
1223 */
1224 if (!waitqueue_active(q) || !key.page_match) {
1225 ClearPageWaiters(page);
1226 /*
1227 * It's possible to miss clearing Waiters here, when we woke
1228 * our page waiters, but the hashed waitqueue has waiters for
1229 * other pages on it.
1230 *
1231 * That's okay, it's a rare case. The next waker will clear it.
1232 */
1233 }
1234 spin_unlock_irqrestore(&q->lock, flags);
1235 }
1236
wake_up_page(struct page * page,int bit)1237 static void wake_up_page(struct page *page, int bit)
1238 {
1239 if (!PageWaiters(page))
1240 return;
1241 wake_up_page_bit(page, bit);
1242 }
1243
1244 /*
1245 * A choice of three behaviors for wait_on_page_bit_common():
1246 */
1247 enum behavior {
1248 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1249 * __lock_page() waiting on then setting PG_locked.
1250 */
1251 SHARED, /* Hold ref to page and check the bit when woken, like
1252 * wait_on_page_writeback() waiting on PG_writeback.
1253 */
1254 DROP, /* Drop ref to page before wait, no check when woken,
1255 * like put_and_wait_on_page_locked() on PG_locked.
1256 */
1257 };
1258
1259 /*
1260 * Attempt to check (or get) the page bit, and mark us done
1261 * if successful.
1262 */
trylock_page_bit_common(struct page * page,int bit_nr,struct wait_queue_entry * wait)1263 static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1264 struct wait_queue_entry *wait)
1265 {
1266 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1267 if (test_and_set_bit(bit_nr, &page->flags))
1268 return false;
1269 } else if (test_bit(bit_nr, &page->flags))
1270 return false;
1271
1272 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1273 return true;
1274 }
1275
1276 /* How many times do we accept lock stealing from under a waiter? */
1277 int sysctl_page_lock_unfairness = 5;
1278
wait_on_page_bit_common(wait_queue_head_t * q,struct page * page,int bit_nr,int state,enum behavior behavior)1279 static inline __sched int wait_on_page_bit_common(wait_queue_head_t *q,
1280 struct page *page, int bit_nr, int state, enum behavior behavior)
1281 {
1282 int unfairness = sysctl_page_lock_unfairness;
1283 struct wait_page_queue wait_page;
1284 wait_queue_entry_t *wait = &wait_page.wait;
1285 bool thrashing = false;
1286 bool delayacct = false;
1287 unsigned long pflags;
1288
1289 if (bit_nr == PG_locked &&
1290 !PageUptodate(page) && PageWorkingset(page)) {
1291 if (!PageSwapBacked(page)) {
1292 delayacct_thrashing_start();
1293 delayacct = true;
1294 }
1295 psi_memstall_enter(&pflags);
1296 thrashing = true;
1297 }
1298
1299 init_wait(wait);
1300 wait->func = wake_page_function;
1301 wait_page.page = page;
1302 wait_page.bit_nr = bit_nr;
1303
1304 repeat:
1305 wait->flags = 0;
1306 if (behavior == EXCLUSIVE) {
1307 wait->flags = WQ_FLAG_EXCLUSIVE;
1308 if (--unfairness < 0)
1309 wait->flags |= WQ_FLAG_CUSTOM;
1310 }
1311
1312 /*
1313 * Do one last check whether we can get the
1314 * page bit synchronously.
1315 *
1316 * Do the SetPageWaiters() marking before that
1317 * to let any waker we _just_ missed know they
1318 * need to wake us up (otherwise they'll never
1319 * even go to the slow case that looks at the
1320 * page queue), and add ourselves to the wait
1321 * queue if we need to sleep.
1322 *
1323 * This part needs to be done under the queue
1324 * lock to avoid races.
1325 */
1326 spin_lock_irq(&q->lock);
1327 SetPageWaiters(page);
1328 if (!trylock_page_bit_common(page, bit_nr, wait))
1329 __add_wait_queue_entry_tail(q, wait);
1330 spin_unlock_irq(&q->lock);
1331
1332 /*
1333 * From now on, all the logic will be based on
1334 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1335 * see whether the page bit testing has already
1336 * been done by the wake function.
1337 *
1338 * We can drop our reference to the page.
1339 */
1340 if (behavior == DROP)
1341 put_page(page);
1342
1343 /*
1344 * Note that until the "finish_wait()", or until
1345 * we see the WQ_FLAG_WOKEN flag, we need to
1346 * be very careful with the 'wait->flags', because
1347 * we may race with a waker that sets them.
1348 */
1349 for (;;) {
1350 unsigned int flags;
1351
1352 set_current_state(state);
1353
1354 /* Loop until we've been woken or interrupted */
1355 flags = smp_load_acquire(&wait->flags);
1356 if (!(flags & WQ_FLAG_WOKEN)) {
1357 if (signal_pending_state(state, current))
1358 break;
1359
1360 io_schedule();
1361 continue;
1362 }
1363
1364 /* If we were non-exclusive, we're done */
1365 if (behavior != EXCLUSIVE)
1366 break;
1367
1368 /* If the waker got the lock for us, we're done */
1369 if (flags & WQ_FLAG_DONE)
1370 break;
1371
1372 /*
1373 * Otherwise, if we're getting the lock, we need to
1374 * try to get it ourselves.
1375 *
1376 * And if that fails, we'll have to retry this all.
1377 */
1378 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1379 goto repeat;
1380
1381 wait->flags |= WQ_FLAG_DONE;
1382 break;
1383 }
1384
1385 /*
1386 * If a signal happened, this 'finish_wait()' may remove the last
1387 * waiter from the wait-queues, but the PageWaiters bit will remain
1388 * set. That's ok. The next wakeup will take care of it, and trying
1389 * to do it here would be difficult and prone to races.
1390 */
1391 finish_wait(q, wait);
1392
1393 if (thrashing) {
1394 if (delayacct)
1395 delayacct_thrashing_end();
1396 psi_memstall_leave(&pflags);
1397 }
1398
1399 /*
1400 * NOTE! The wait->flags weren't stable until we've done the
1401 * 'finish_wait()', and we could have exited the loop above due
1402 * to a signal, and had a wakeup event happen after the signal
1403 * test but before the 'finish_wait()'.
1404 *
1405 * So only after the finish_wait() can we reliably determine
1406 * if we got woken up or not, so we can now figure out the final
1407 * return value based on that state without races.
1408 *
1409 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1410 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1411 */
1412 if (behavior == EXCLUSIVE)
1413 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1414
1415 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1416 }
1417
wait_on_page_bit(struct page * page,int bit_nr)1418 __sched void wait_on_page_bit(struct page *page, int bit_nr)
1419 {
1420 wait_queue_head_t *q = page_waitqueue(page);
1421 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1422 }
1423 EXPORT_SYMBOL(wait_on_page_bit);
1424
wait_on_page_bit_killable(struct page * page,int bit_nr)1425 __sched int wait_on_page_bit_killable(struct page *page, int bit_nr)
1426 {
1427 wait_queue_head_t *q = page_waitqueue(page);
1428 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
1429 }
1430 EXPORT_SYMBOL(wait_on_page_bit_killable);
1431
1432 /**
1433 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1434 * @page: The page to wait for.
1435 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1436 *
1437 * The caller should hold a reference on @page. They expect the page to
1438 * become unlocked relatively soon, but do not wish to hold up migration
1439 * (for example) by holding the reference while waiting for the page to
1440 * come unlocked. After this function returns, the caller should not
1441 * dereference @page.
1442 *
1443 * Return: 0 if the page was unlocked or -EINTR if interrupted by a signal.
1444 */
put_and_wait_on_page_locked(struct page * page,int state)1445 int put_and_wait_on_page_locked(struct page *page, int state)
1446 {
1447 wait_queue_head_t *q;
1448
1449 page = compound_head(page);
1450 q = page_waitqueue(page);
1451 return wait_on_page_bit_common(q, page, PG_locked, state, DROP);
1452 }
1453
1454 /**
1455 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1456 * @page: Page defining the wait queue of interest
1457 * @waiter: Waiter to add to the queue
1458 *
1459 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1460 */
add_page_wait_queue(struct page * page,wait_queue_entry_t * waiter)1461 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1462 {
1463 wait_queue_head_t *q = page_waitqueue(page);
1464 unsigned long flags;
1465
1466 spin_lock_irqsave(&q->lock, flags);
1467 __add_wait_queue_entry_tail(q, waiter);
1468 SetPageWaiters(page);
1469 spin_unlock_irqrestore(&q->lock, flags);
1470 }
1471 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1472
1473 #ifndef clear_bit_unlock_is_negative_byte
1474
1475 /*
1476 * PG_waiters is the high bit in the same byte as PG_lock.
1477 *
1478 * On x86 (and on many other architectures), we can clear PG_lock and
1479 * test the sign bit at the same time. But if the architecture does
1480 * not support that special operation, we just do this all by hand
1481 * instead.
1482 *
1483 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1484 * being cleared, but a memory barrier should be unnecessary since it is
1485 * in the same byte as PG_locked.
1486 */
clear_bit_unlock_is_negative_byte(long nr,volatile void * mem)1487 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1488 {
1489 clear_bit_unlock(nr, mem);
1490 /* smp_mb__after_atomic(); */
1491 return test_bit(PG_waiters, mem);
1492 }
1493
1494 #endif
1495
1496 /**
1497 * unlock_page - unlock a locked page
1498 * @page: the page
1499 *
1500 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
1501 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1502 * mechanism between PageLocked pages and PageWriteback pages is shared.
1503 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1504 *
1505 * Note that this depends on PG_waiters being the sign bit in the byte
1506 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1507 * clear the PG_locked bit and test PG_waiters at the same time fairly
1508 * portably (architectures that do LL/SC can test any bit, while x86 can
1509 * test the sign bit).
1510 */
unlock_page(struct page * page)1511 void unlock_page(struct page *page)
1512 {
1513 BUILD_BUG_ON(PG_waiters != 7);
1514 page = compound_head(page);
1515 VM_BUG_ON_PAGE(!PageLocked(page), page);
1516 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1517 wake_up_page_bit(page, PG_locked);
1518 }
1519 EXPORT_SYMBOL(unlock_page);
1520
1521 /**
1522 * end_page_private_2 - Clear PG_private_2 and release any waiters
1523 * @page: The page
1524 *
1525 * Clear the PG_private_2 bit on a page and wake up any sleepers waiting for
1526 * this. The page ref held for PG_private_2 being set is released.
1527 *
1528 * This is, for example, used when a netfs page is being written to a local
1529 * disk cache, thereby allowing writes to the cache for the same page to be
1530 * serialised.
1531 */
end_page_private_2(struct page * page)1532 void end_page_private_2(struct page *page)
1533 {
1534 page = compound_head(page);
1535 VM_BUG_ON_PAGE(!PagePrivate2(page), page);
1536 clear_bit_unlock(PG_private_2, &page->flags);
1537 wake_up_page_bit(page, PG_private_2);
1538 put_page(page);
1539 }
1540 EXPORT_SYMBOL(end_page_private_2);
1541
1542 /**
1543 * wait_on_page_private_2 - Wait for PG_private_2 to be cleared on a page
1544 * @page: The page to wait on
1545 *
1546 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page.
1547 */
wait_on_page_private_2(struct page * page)1548 void wait_on_page_private_2(struct page *page)
1549 {
1550 page = compound_head(page);
1551 while (PagePrivate2(page))
1552 wait_on_page_bit(page, PG_private_2);
1553 }
1554 EXPORT_SYMBOL(wait_on_page_private_2);
1555
1556 /**
1557 * wait_on_page_private_2_killable - Wait for PG_private_2 to be cleared on a page
1558 * @page: The page to wait on
1559 *
1560 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page or until a
1561 * fatal signal is received by the calling task.
1562 *
1563 * Return:
1564 * - 0 if successful.
1565 * - -EINTR if a fatal signal was encountered.
1566 */
wait_on_page_private_2_killable(struct page * page)1567 int wait_on_page_private_2_killable(struct page *page)
1568 {
1569 int ret = 0;
1570
1571 page = compound_head(page);
1572 while (PagePrivate2(page)) {
1573 ret = wait_on_page_bit_killable(page, PG_private_2);
1574 if (ret < 0)
1575 break;
1576 }
1577
1578 return ret;
1579 }
1580 EXPORT_SYMBOL(wait_on_page_private_2_killable);
1581
1582 /**
1583 * end_page_writeback - end writeback against a page
1584 * @page: the page
1585 */
end_page_writeback(struct page * page)1586 void end_page_writeback(struct page *page)
1587 {
1588 /*
1589 * TestClearPageReclaim could be used here but it is an atomic
1590 * operation and overkill in this particular case. Failing to
1591 * shuffle a page marked for immediate reclaim is too mild to
1592 * justify taking an atomic operation penalty at the end of
1593 * ever page writeback.
1594 */
1595 if (PageReclaim(page)) {
1596 ClearPageReclaim(page);
1597 rotate_reclaimable_page(page);
1598 }
1599
1600 /*
1601 * Writeback does not hold a page reference of its own, relying
1602 * on truncation to wait for the clearing of PG_writeback.
1603 * But here we must make sure that the page is not freed and
1604 * reused before the wake_up_page().
1605 */
1606 get_page(page);
1607 if (!test_clear_page_writeback(page))
1608 BUG();
1609
1610 smp_mb__after_atomic();
1611 wake_up_page(page, PG_writeback);
1612 put_page(page);
1613 }
1614 EXPORT_SYMBOL(end_page_writeback);
1615
1616 /*
1617 * After completing I/O on a page, call this routine to update the page
1618 * flags appropriately
1619 */
page_endio(struct page * page,bool is_write,int err)1620 void page_endio(struct page *page, bool is_write, int err)
1621 {
1622 if (!is_write) {
1623 if (!err) {
1624 SetPageUptodate(page);
1625 } else {
1626 ClearPageUptodate(page);
1627 SetPageError(page);
1628 }
1629 unlock_page(page);
1630 } else {
1631 if (err) {
1632 struct address_space *mapping;
1633
1634 SetPageError(page);
1635 mapping = page_mapping(page);
1636 if (mapping)
1637 mapping_set_error(mapping, err);
1638 }
1639 end_page_writeback(page);
1640 }
1641 }
1642 EXPORT_SYMBOL_GPL(page_endio);
1643
1644 /**
1645 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1646 * @__page: the page to lock
1647 */
__lock_page(struct page * __page)1648 __sched void __lock_page(struct page *__page)
1649 {
1650 struct page *page = compound_head(__page);
1651 wait_queue_head_t *q = page_waitqueue(page);
1652 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1653 EXCLUSIVE);
1654 }
1655 EXPORT_SYMBOL(__lock_page);
1656
__lock_page_killable(struct page * __page)1657 __sched int __lock_page_killable(struct page *__page)
1658 {
1659 struct page *page = compound_head(__page);
1660 wait_queue_head_t *q = page_waitqueue(page);
1661 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1662 EXCLUSIVE);
1663 }
1664 EXPORT_SYMBOL_GPL(__lock_page_killable);
1665
__lock_page_async(struct page * page,struct wait_page_queue * wait)1666 __sched int __lock_page_async(struct page *page, struct wait_page_queue *wait)
1667 {
1668 struct wait_queue_head *q = page_waitqueue(page);
1669 int ret = 0;
1670
1671 wait->page = page;
1672 wait->bit_nr = PG_locked;
1673
1674 spin_lock_irq(&q->lock);
1675 __add_wait_queue_entry_tail(q, &wait->wait);
1676 SetPageWaiters(page);
1677 ret = !trylock_page(page);
1678 /*
1679 * If we were successful now, we know we're still on the
1680 * waitqueue as we're still under the lock. This means it's
1681 * safe to remove and return success, we know the callback
1682 * isn't going to trigger.
1683 */
1684 if (!ret)
1685 __remove_wait_queue(q, &wait->wait);
1686 else
1687 ret = -EIOCBQUEUED;
1688 spin_unlock_irq(&q->lock);
1689 return ret;
1690 }
1691
1692 /*
1693 * Return values:
1694 * 1 - page is locked; mmap_lock is still held.
1695 * 0 - page is not locked.
1696 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
1697 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1698 * which case mmap_lock is still held.
1699 *
1700 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1701 * with the page locked and the mmap_lock unperturbed.
1702 */
__lock_page_or_retry(struct page * page,struct mm_struct * mm,unsigned int flags)1703 __sched int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1704 unsigned int flags)
1705 {
1706 if (fault_flag_allow_retry_first(flags)) {
1707 /*
1708 * CAUTION! In this case, mmap_lock is not released
1709 * even though return 0.
1710 */
1711 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1712 return 0;
1713
1714 mmap_read_unlock(mm);
1715 if (flags & FAULT_FLAG_KILLABLE)
1716 wait_on_page_locked_killable(page);
1717 else
1718 wait_on_page_locked(page);
1719 return 0;
1720 }
1721 if (flags & FAULT_FLAG_KILLABLE) {
1722 int ret;
1723
1724 ret = __lock_page_killable(page);
1725 if (ret) {
1726 mmap_read_unlock(mm);
1727 return 0;
1728 }
1729 } else {
1730 __lock_page(page);
1731 }
1732 return 1;
1733
1734 }
1735
1736 /**
1737 * page_cache_next_miss() - Find the next gap in the page cache.
1738 * @mapping: Mapping.
1739 * @index: Index.
1740 * @max_scan: Maximum range to search.
1741 *
1742 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1743 * gap with the lowest index.
1744 *
1745 * This function may be called under the rcu_read_lock. However, this will
1746 * not atomically search a snapshot of the cache at a single point in time.
1747 * For example, if a gap is created at index 5, then subsequently a gap is
1748 * created at index 10, page_cache_next_miss covering both indices may
1749 * return 10 if called under the rcu_read_lock.
1750 *
1751 * Return: The index of the gap if found, otherwise an index outside the
1752 * range specified (in which case 'return - index >= max_scan' will be true).
1753 * In the rare case of index wrap-around, 0 will be returned.
1754 */
page_cache_next_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)1755 pgoff_t page_cache_next_miss(struct address_space *mapping,
1756 pgoff_t index, unsigned long max_scan)
1757 {
1758 XA_STATE(xas, &mapping->i_pages, index);
1759
1760 while (max_scan--) {
1761 void *entry = xas_next(&xas);
1762 if (!entry || xa_is_value(entry))
1763 break;
1764 if (xas.xa_index == 0)
1765 break;
1766 }
1767
1768 return xas.xa_index;
1769 }
1770 EXPORT_SYMBOL(page_cache_next_miss);
1771
1772 /**
1773 * page_cache_prev_miss() - Find the previous gap in the page cache.
1774 * @mapping: Mapping.
1775 * @index: Index.
1776 * @max_scan: Maximum range to search.
1777 *
1778 * Search the range [max(index - max_scan + 1, 0), index] for the
1779 * gap with the highest index.
1780 *
1781 * This function may be called under the rcu_read_lock. However, this will
1782 * not atomically search a snapshot of the cache at a single point in time.
1783 * For example, if a gap is created at index 10, then subsequently a gap is
1784 * created at index 5, page_cache_prev_miss() covering both indices may
1785 * return 5 if called under the rcu_read_lock.
1786 *
1787 * Return: The index of the gap if found, otherwise an index outside the
1788 * range specified (in which case 'index - return >= max_scan' will be true).
1789 * In the rare case of wrap-around, ULONG_MAX will be returned.
1790 */
page_cache_prev_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)1791 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1792 pgoff_t index, unsigned long max_scan)
1793 {
1794 XA_STATE(xas, &mapping->i_pages, index);
1795
1796 while (max_scan--) {
1797 void *entry = xas_prev(&xas);
1798 if (!entry || xa_is_value(entry))
1799 break;
1800 if (xas.xa_index == ULONG_MAX)
1801 break;
1802 }
1803
1804 return xas.xa_index;
1805 }
1806 EXPORT_SYMBOL(page_cache_prev_miss);
1807
1808 /*
1809 * mapping_get_entry - Get a page cache entry.
1810 * @mapping: the address_space to search
1811 * @index: The page cache index.
1812 *
1813 * Looks up the page cache slot at @mapping & @index. If there is a
1814 * page cache page, the head page is returned with an increased refcount.
1815 *
1816 * If the slot holds a shadow entry of a previously evicted page, or a
1817 * swap entry from shmem/tmpfs, it is returned.
1818 *
1819 * Return: The head page or shadow entry, %NULL if nothing is found.
1820 */
mapping_get_entry(struct address_space * mapping,pgoff_t index)1821 static struct page *mapping_get_entry(struct address_space *mapping,
1822 pgoff_t index)
1823 {
1824 XA_STATE(xas, &mapping->i_pages, index);
1825 struct page *page;
1826
1827 rcu_read_lock();
1828 repeat:
1829 xas_reset(&xas);
1830 page = xas_load(&xas);
1831 if (xas_retry(&xas, page))
1832 goto repeat;
1833 /*
1834 * A shadow entry of a recently evicted page, or a swap entry from
1835 * shmem/tmpfs. Return it without attempting to raise page count.
1836 */
1837 if (!page || xa_is_value(page))
1838 goto out;
1839
1840 if (!page_cache_get_speculative(page))
1841 goto repeat;
1842
1843 /*
1844 * Has the page moved or been split?
1845 * This is part of the lockless pagecache protocol. See
1846 * include/linux/pagemap.h for details.
1847 */
1848 if (unlikely(page != xas_reload(&xas))) {
1849 put_page(page);
1850 goto repeat;
1851 }
1852 out:
1853 rcu_read_unlock();
1854
1855 return page;
1856 }
1857
1858 /**
1859 * pagecache_get_page - Find and get a reference to a page.
1860 * @mapping: The address_space to search.
1861 * @index: The page index.
1862 * @fgp_flags: %FGP flags modify how the page is returned.
1863 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
1864 *
1865 * Looks up the page cache entry at @mapping & @index.
1866 *
1867 * @fgp_flags can be zero or more of these flags:
1868 *
1869 * * %FGP_ACCESSED - The page will be marked accessed.
1870 * * %FGP_LOCK - The page is returned locked.
1871 * * %FGP_HEAD - If the page is present and a THP, return the head page
1872 * rather than the exact page specified by the index.
1873 * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1874 * instead of allocating a new page to replace it.
1875 * * %FGP_CREAT - If no page is present then a new page is allocated using
1876 * @gfp_mask and added to the page cache and the VM's LRU list.
1877 * The page is returned locked and with an increased refcount.
1878 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1879 * page is already in cache. If the page was allocated, unlock it before
1880 * returning so the caller can do the same dance.
1881 * * %FGP_WRITE - The page will be written
1882 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1883 * * %FGP_NOWAIT - Don't get blocked by page lock
1884 *
1885 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1886 * if the %GFP flags specified for %FGP_CREAT are atomic.
1887 *
1888 * If there is a page cache page, it is returned with an increased refcount.
1889 *
1890 * Return: The found page or %NULL otherwise.
1891 */
pagecache_get_page(struct address_space * mapping,pgoff_t index,int fgp_flags,gfp_t gfp_mask)1892 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1893 int fgp_flags, gfp_t gfp_mask)
1894 {
1895 struct page *page;
1896
1897 repeat:
1898 page = mapping_get_entry(mapping, index);
1899 if (xa_is_value(page)) {
1900 if (fgp_flags & FGP_ENTRY)
1901 return page;
1902 page = NULL;
1903 }
1904 if (!page)
1905 goto no_page;
1906
1907 if (fgp_flags & FGP_LOCK) {
1908 if (fgp_flags & FGP_NOWAIT) {
1909 if (!trylock_page(page)) {
1910 put_page(page);
1911 return NULL;
1912 }
1913 } else {
1914 lock_page(page);
1915 }
1916
1917 /* Has the page been truncated? */
1918 if (unlikely(page->mapping != mapping)) {
1919 unlock_page(page);
1920 put_page(page);
1921 goto repeat;
1922 }
1923 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
1924 }
1925
1926 if (fgp_flags & FGP_ACCESSED)
1927 mark_page_accessed(page);
1928 else if (fgp_flags & FGP_WRITE) {
1929 /* Clear idle flag for buffer write */
1930 if (page_is_idle(page))
1931 clear_page_idle(page);
1932 }
1933 if (!(fgp_flags & FGP_HEAD))
1934 page = find_subpage(page, index);
1935
1936 no_page:
1937 if (!page && (fgp_flags & FGP_CREAT)) {
1938 int err;
1939 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1940 gfp_mask |= __GFP_WRITE;
1941 if (fgp_flags & FGP_NOFS)
1942 gfp_mask &= ~__GFP_FS;
1943
1944 page = __page_cache_alloc(gfp_mask);
1945 if (!page)
1946 return NULL;
1947
1948 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1949 fgp_flags |= FGP_LOCK;
1950
1951 /* Init accessed so avoid atomic mark_page_accessed later */
1952 if (fgp_flags & FGP_ACCESSED)
1953 __SetPageReferenced(page);
1954
1955 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
1956 if (unlikely(err)) {
1957 put_page(page);
1958 page = NULL;
1959 if (err == -EEXIST)
1960 goto repeat;
1961 }
1962
1963 /*
1964 * add_to_page_cache_lru locks the page, and for mmap we expect
1965 * an unlocked page.
1966 */
1967 if (page && (fgp_flags & FGP_FOR_MMAP))
1968 unlock_page(page);
1969 }
1970
1971 return page;
1972 }
1973 EXPORT_SYMBOL(pagecache_get_page);
1974
find_get_entry(struct xa_state * xas,pgoff_t max,xa_mark_t mark)1975 static inline struct page *find_get_entry(struct xa_state *xas, pgoff_t max,
1976 xa_mark_t mark)
1977 {
1978 struct page *page;
1979
1980 retry:
1981 if (mark == XA_PRESENT)
1982 page = xas_find(xas, max);
1983 else
1984 page = xas_find_marked(xas, max, mark);
1985
1986 if (xas_retry(xas, page))
1987 goto retry;
1988 /*
1989 * A shadow entry of a recently evicted page, a swap
1990 * entry from shmem/tmpfs or a DAX entry. Return it
1991 * without attempting to raise page count.
1992 */
1993 if (!page || xa_is_value(page))
1994 return page;
1995
1996 if (!page_cache_get_speculative(page))
1997 goto reset;
1998
1999 /* Has the page moved or been split? */
2000 if (unlikely(page != xas_reload(xas))) {
2001 put_page(page);
2002 goto reset;
2003 }
2004
2005 return page;
2006 reset:
2007 xas_reset(xas);
2008 goto retry;
2009 }
2010
2011 /**
2012 * find_get_entries - gang pagecache lookup
2013 * @mapping: The address_space to search
2014 * @start: The starting page cache index
2015 * @end: The final page index (inclusive).
2016 * @pvec: Where the resulting entries are placed.
2017 * @indices: The cache indices corresponding to the entries in @entries
2018 *
2019 * find_get_entries() will search for and return a batch of entries in
2020 * the mapping. The entries are placed in @pvec. find_get_entries()
2021 * takes a reference on any actual pages it returns.
2022 *
2023 * The search returns a group of mapping-contiguous page cache entries
2024 * with ascending indexes. There may be holes in the indices due to
2025 * not-present pages.
2026 *
2027 * Any shadow entries of evicted pages, or swap entries from
2028 * shmem/tmpfs, are included in the returned array.
2029 *
2030 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
2031 * stops at that page: the caller is likely to have a better way to handle
2032 * the compound page as a whole, and then skip its extent, than repeatedly
2033 * calling find_get_entries() to return all its tails.
2034 *
2035 * Return: the number of pages and shadow entries which were found.
2036 */
find_get_entries(struct address_space * mapping,pgoff_t start,pgoff_t end,struct pagevec * pvec,pgoff_t * indices)2037 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
2038 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2039 {
2040 XA_STATE(xas, &mapping->i_pages, start);
2041 struct page *page;
2042 unsigned int ret = 0;
2043 unsigned nr_entries = PAGEVEC_SIZE;
2044
2045 rcu_read_lock();
2046 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2047 /*
2048 * Terminate early on finding a THP, to allow the caller to
2049 * handle it all at once; but continue if this is hugetlbfs.
2050 */
2051 if (!xa_is_value(page) && PageTransHuge(page) &&
2052 !PageHuge(page)) {
2053 page = find_subpage(page, xas.xa_index);
2054 nr_entries = ret + 1;
2055 }
2056
2057 indices[ret] = xas.xa_index;
2058 pvec->pages[ret] = page;
2059 if (++ret == nr_entries)
2060 break;
2061 }
2062 rcu_read_unlock();
2063
2064 pvec->nr = ret;
2065 return ret;
2066 }
2067
2068 /**
2069 * find_lock_entries - Find a batch of pagecache entries.
2070 * @mapping: The address_space to search.
2071 * @start: The starting page cache index.
2072 * @end: The final page index (inclusive).
2073 * @pvec: Where the resulting entries are placed.
2074 * @indices: The cache indices of the entries in @pvec.
2075 *
2076 * find_lock_entries() will return a batch of entries from @mapping.
2077 * Swap, shadow and DAX entries are included. Pages are returned
2078 * locked and with an incremented refcount. Pages which are locked by
2079 * somebody else or under writeback are skipped. Only the head page of
2080 * a THP is returned. Pages which are partially outside the range are
2081 * not returned.
2082 *
2083 * The entries have ascending indexes. The indices may not be consecutive
2084 * due to not-present entries, THP pages, pages which could not be locked
2085 * or pages under writeback.
2086 *
2087 * Return: The number of entries which were found.
2088 */
find_lock_entries(struct address_space * mapping,pgoff_t start,pgoff_t end,struct pagevec * pvec,pgoff_t * indices)2089 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2090 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2091 {
2092 XA_STATE(xas, &mapping->i_pages, start);
2093 struct page *page;
2094
2095 rcu_read_lock();
2096 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2097 unsigned long next_idx = xas.xa_index + 1;
2098
2099 if (!xa_is_value(page)) {
2100 if (PageTransHuge(page))
2101 next_idx = page->index + thp_nr_pages(page);
2102 if (page->index < start)
2103 goto put;
2104 if (page->index + thp_nr_pages(page) - 1 > end)
2105 goto put;
2106 if (!trylock_page(page))
2107 goto put;
2108 if (page->mapping != mapping || PageWriteback(page))
2109 goto unlock;
2110 VM_BUG_ON_PAGE(!thp_contains(page, xas.xa_index),
2111 page);
2112 }
2113 indices[pvec->nr] = xas.xa_index;
2114 if (!pagevec_add(pvec, page))
2115 break;
2116 goto next;
2117 unlock:
2118 unlock_page(page);
2119 put:
2120 put_page(page);
2121 next:
2122 if (next_idx != xas.xa_index + 1) {
2123 /* Final THP may cross MAX_LFS_FILESIZE on 32-bit */
2124 if (next_idx < xas.xa_index)
2125 break;
2126 xas_set(&xas, next_idx);
2127 }
2128 }
2129 rcu_read_unlock();
2130
2131 return pagevec_count(pvec);
2132 }
2133
2134 /**
2135 * find_get_pages_range - gang pagecache lookup
2136 * @mapping: The address_space to search
2137 * @start: The starting page index
2138 * @end: The final page index (inclusive)
2139 * @nr_pages: The maximum number of pages
2140 * @pages: Where the resulting pages are placed
2141 *
2142 * find_get_pages_range() will search for and return a group of up to @nr_pages
2143 * pages in the mapping starting at index @start and up to index @end
2144 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
2145 * a reference against the returned pages.
2146 *
2147 * The search returns a group of mapping-contiguous pages with ascending
2148 * indexes. There may be holes in the indices due to not-present pages.
2149 * We also update @start to index the next page for the traversal.
2150 *
2151 * Return: the number of pages which were found. If this number is
2152 * smaller than @nr_pages, the end of specified range has been
2153 * reached.
2154 */
find_get_pages_range(struct address_space * mapping,pgoff_t * start,pgoff_t end,unsigned int nr_pages,struct page ** pages)2155 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2156 pgoff_t end, unsigned int nr_pages,
2157 struct page **pages)
2158 {
2159 XA_STATE(xas, &mapping->i_pages, *start);
2160 struct page *page;
2161 unsigned ret = 0;
2162
2163 if (unlikely(!nr_pages))
2164 return 0;
2165
2166 rcu_read_lock();
2167 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2168 /* Skip over shadow, swap and DAX entries */
2169 if (xa_is_value(page))
2170 continue;
2171
2172 pages[ret] = find_subpage(page, xas.xa_index);
2173 if (++ret == nr_pages) {
2174 *start = xas.xa_index + 1;
2175 goto out;
2176 }
2177 }
2178
2179 /*
2180 * We come here when there is no page beyond @end. We take care to not
2181 * overflow the index @start as it confuses some of the callers. This
2182 * breaks the iteration when there is a page at index -1 but that is
2183 * already broken anyway.
2184 */
2185 if (end == (pgoff_t)-1)
2186 *start = (pgoff_t)-1;
2187 else
2188 *start = end + 1;
2189 out:
2190 rcu_read_unlock();
2191
2192 return ret;
2193 }
2194
2195 /**
2196 * find_get_pages_contig - gang contiguous pagecache lookup
2197 * @mapping: The address_space to search
2198 * @index: The starting page index
2199 * @nr_pages: The maximum number of pages
2200 * @pages: Where the resulting pages are placed
2201 *
2202 * find_get_pages_contig() works exactly like find_get_pages(), except
2203 * that the returned number of pages are guaranteed to be contiguous.
2204 *
2205 * Return: the number of pages which were found.
2206 */
find_get_pages_contig(struct address_space * mapping,pgoff_t index,unsigned int nr_pages,struct page ** pages)2207 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2208 unsigned int nr_pages, struct page **pages)
2209 {
2210 XA_STATE(xas, &mapping->i_pages, index);
2211 struct page *page;
2212 unsigned int ret = 0;
2213
2214 if (unlikely(!nr_pages))
2215 return 0;
2216
2217 rcu_read_lock();
2218 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
2219 if (xas_retry(&xas, page))
2220 continue;
2221 /*
2222 * If the entry has been swapped out, we can stop looking.
2223 * No current caller is looking for DAX entries.
2224 */
2225 if (xa_is_value(page))
2226 break;
2227
2228 if (!page_cache_get_speculative(page))
2229 goto retry;
2230
2231 /* Has the page moved or been split? */
2232 if (unlikely(page != xas_reload(&xas)))
2233 goto put_page;
2234
2235 pages[ret] = find_subpage(page, xas.xa_index);
2236 if (++ret == nr_pages)
2237 break;
2238 continue;
2239 put_page:
2240 put_page(page);
2241 retry:
2242 xas_reset(&xas);
2243 }
2244 rcu_read_unlock();
2245 return ret;
2246 }
2247 EXPORT_SYMBOL(find_get_pages_contig);
2248
2249 /**
2250 * find_get_pages_range_tag - Find and return head pages matching @tag.
2251 * @mapping: the address_space to search
2252 * @index: the starting page index
2253 * @end: The final page index (inclusive)
2254 * @tag: the tag index
2255 * @nr_pages: the maximum number of pages
2256 * @pages: where the resulting pages are placed
2257 *
2258 * Like find_get_pages(), except we only return head pages which are tagged
2259 * with @tag. @index is updated to the index immediately after the last
2260 * page we return, ready for the next iteration.
2261 *
2262 * Return: the number of pages which were found.
2263 */
find_get_pages_range_tag(struct address_space * mapping,pgoff_t * index,pgoff_t end,xa_mark_t tag,unsigned int nr_pages,struct page ** pages)2264 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2265 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2266 struct page **pages)
2267 {
2268 XA_STATE(xas, &mapping->i_pages, *index);
2269 struct page *page;
2270 unsigned ret = 0;
2271
2272 if (unlikely(!nr_pages))
2273 return 0;
2274
2275 rcu_read_lock();
2276 while ((page = find_get_entry(&xas, end, tag))) {
2277 /*
2278 * Shadow entries should never be tagged, but this iteration
2279 * is lockless so there is a window for page reclaim to evict
2280 * a page we saw tagged. Skip over it.
2281 */
2282 if (xa_is_value(page))
2283 continue;
2284
2285 pages[ret] = page;
2286 if (++ret == nr_pages) {
2287 *index = page->index + thp_nr_pages(page);
2288 goto out;
2289 }
2290 }
2291
2292 /*
2293 * We come here when we got to @end. We take care to not overflow the
2294 * index @index as it confuses some of the callers. This breaks the
2295 * iteration when there is a page at index -1 but that is already
2296 * broken anyway.
2297 */
2298 if (end == (pgoff_t)-1)
2299 *index = (pgoff_t)-1;
2300 else
2301 *index = end + 1;
2302 out:
2303 rcu_read_unlock();
2304
2305 return ret;
2306 }
2307 EXPORT_SYMBOL(find_get_pages_range_tag);
2308
2309 /*
2310 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2311 * a _large_ part of the i/o request. Imagine the worst scenario:
2312 *
2313 * ---R__________________________________________B__________
2314 * ^ reading here ^ bad block(assume 4k)
2315 *
2316 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2317 * => failing the whole request => read(R) => read(R+1) =>
2318 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2319 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2320 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2321 *
2322 * It is going insane. Fix it by quickly scaling down the readahead size.
2323 */
shrink_readahead_size_eio(struct file_ra_state * ra)2324 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2325 {
2326 ra->ra_pages /= 4;
2327 }
2328
2329 /*
2330 * filemap_get_read_batch - Get a batch of pages for read
2331 *
2332 * Get a batch of pages which represent a contiguous range of bytes
2333 * in the file. No tail pages will be returned. If @index is in the
2334 * middle of a THP, the entire THP will be returned. The last page in
2335 * the batch may have Readahead set or be not Uptodate so that the
2336 * caller can take the appropriate action.
2337 */
filemap_get_read_batch(struct address_space * mapping,pgoff_t index,pgoff_t max,struct pagevec * pvec)2338 static void filemap_get_read_batch(struct address_space *mapping,
2339 pgoff_t index, pgoff_t max, struct pagevec *pvec)
2340 {
2341 XA_STATE(xas, &mapping->i_pages, index);
2342 struct page *head;
2343
2344 rcu_read_lock();
2345 for (head = xas_load(&xas); head; head = xas_next(&xas)) {
2346 if (xas_retry(&xas, head))
2347 continue;
2348 if (xas.xa_index > max || xa_is_value(head))
2349 break;
2350 if (!page_cache_get_speculative(head))
2351 goto retry;
2352
2353 /* Has the page moved or been split? */
2354 if (unlikely(head != xas_reload(&xas)))
2355 goto put_page;
2356
2357 if (!pagevec_add(pvec, head))
2358 break;
2359 if (!PageUptodate(head))
2360 break;
2361 if (PageReadahead(head))
2362 break;
2363 if (PageHead(head)) {
2364 xas_set(&xas, head->index + thp_nr_pages(head));
2365 /* Handle wrap correctly */
2366 if (xas.xa_index - 1 >= max)
2367 break;
2368 }
2369 continue;
2370 put_page:
2371 put_page(head);
2372 retry:
2373 xas_reset(&xas);
2374 }
2375 rcu_read_unlock();
2376 }
2377
filemap_read_page(struct file * file,struct address_space * mapping,struct page * page)2378 static int filemap_read_page(struct file *file, struct address_space *mapping,
2379 struct page *page)
2380 {
2381 int error;
2382
2383 /*
2384 * A previous I/O error may have been due to temporary failures,
2385 * eg. multipath errors. PG_error will be set again if readpage
2386 * fails.
2387 */
2388 ClearPageError(page);
2389 /* Start the actual read. The read will unlock the page. */
2390 error = mapping->a_ops->readpage(file, page);
2391 if (error)
2392 return error;
2393
2394 error = wait_on_page_locked_killable(page);
2395 if (error)
2396 return error;
2397 if (PageUptodate(page))
2398 return 0;
2399 shrink_readahead_size_eio(&file->f_ra);
2400 return -EIO;
2401 }
2402
filemap_range_uptodate(struct address_space * mapping,loff_t pos,struct iov_iter * iter,struct page * page)2403 static bool filemap_range_uptodate(struct address_space *mapping,
2404 loff_t pos, struct iov_iter *iter, struct page *page)
2405 {
2406 int count;
2407
2408 if (PageUptodate(page))
2409 return true;
2410 /* pipes can't handle partially uptodate pages */
2411 if (iov_iter_is_pipe(iter))
2412 return false;
2413 if (!mapping->a_ops->is_partially_uptodate)
2414 return false;
2415 if (mapping->host->i_blkbits >= (PAGE_SHIFT + thp_order(page)))
2416 return false;
2417
2418 count = iter->count;
2419 if (page_offset(page) > pos) {
2420 count -= page_offset(page) - pos;
2421 pos = 0;
2422 } else {
2423 pos -= page_offset(page);
2424 }
2425
2426 return mapping->a_ops->is_partially_uptodate(page, pos, count);
2427 }
2428
filemap_update_page(struct kiocb * iocb,struct address_space * mapping,struct iov_iter * iter,struct page * page)2429 static int filemap_update_page(struct kiocb *iocb,
2430 struct address_space *mapping, struct iov_iter *iter,
2431 struct page *page)
2432 {
2433 int error;
2434
2435 if (iocb->ki_flags & IOCB_NOWAIT) {
2436 if (!filemap_invalidate_trylock_shared(mapping))
2437 return -EAGAIN;
2438 } else {
2439 filemap_invalidate_lock_shared(mapping);
2440 }
2441
2442 if (!trylock_page(page)) {
2443 error = -EAGAIN;
2444 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2445 goto unlock_mapping;
2446 if (!(iocb->ki_flags & IOCB_WAITQ)) {
2447 filemap_invalidate_unlock_shared(mapping);
2448 put_and_wait_on_page_locked(page, TASK_KILLABLE);
2449 return AOP_TRUNCATED_PAGE;
2450 }
2451 error = __lock_page_async(page, iocb->ki_waitq);
2452 if (error)
2453 goto unlock_mapping;
2454 }
2455
2456 error = AOP_TRUNCATED_PAGE;
2457 if (!page->mapping)
2458 goto unlock;
2459
2460 error = 0;
2461 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, page))
2462 goto unlock;
2463
2464 error = -EAGAIN;
2465 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2466 goto unlock;
2467
2468 error = filemap_read_page(iocb->ki_filp, mapping, page);
2469 goto unlock_mapping;
2470 unlock:
2471 unlock_page(page);
2472 unlock_mapping:
2473 filemap_invalidate_unlock_shared(mapping);
2474 if (error == AOP_TRUNCATED_PAGE)
2475 put_page(page);
2476 return error;
2477 }
2478
filemap_create_page(struct file * file,struct address_space * mapping,pgoff_t index,struct pagevec * pvec)2479 static int filemap_create_page(struct file *file,
2480 struct address_space *mapping, pgoff_t index,
2481 struct pagevec *pvec)
2482 {
2483 struct page *page;
2484 int error;
2485
2486 page = page_cache_alloc(mapping);
2487 if (!page)
2488 return -ENOMEM;
2489
2490 /*
2491 * Protect against truncate / hole punch. Grabbing invalidate_lock here
2492 * assures we cannot instantiate and bring uptodate new pagecache pages
2493 * after evicting page cache during truncate and before actually
2494 * freeing blocks. Note that we could release invalidate_lock after
2495 * inserting the page into page cache as the locked page would then be
2496 * enough to synchronize with hole punching. But there are code paths
2497 * such as filemap_update_page() filling in partially uptodate pages or
2498 * ->readpages() that need to hold invalidate_lock while mapping blocks
2499 * for IO so let's hold the lock here as well to keep locking rules
2500 * simple.
2501 */
2502 filemap_invalidate_lock_shared(mapping);
2503 error = add_to_page_cache_lru(page, mapping, index,
2504 mapping_gfp_constraint(mapping, GFP_KERNEL));
2505 if (error == -EEXIST)
2506 error = AOP_TRUNCATED_PAGE;
2507 if (error)
2508 goto error;
2509
2510 error = filemap_read_page(file, mapping, page);
2511 if (error)
2512 goto error;
2513
2514 filemap_invalidate_unlock_shared(mapping);
2515 pagevec_add(pvec, page);
2516 return 0;
2517 error:
2518 filemap_invalidate_unlock_shared(mapping);
2519 put_page(page);
2520 return error;
2521 }
2522
filemap_readahead(struct kiocb * iocb,struct file * file,struct address_space * mapping,struct page * page,pgoff_t last_index)2523 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2524 struct address_space *mapping, struct page *page,
2525 pgoff_t last_index)
2526 {
2527 if (iocb->ki_flags & IOCB_NOIO)
2528 return -EAGAIN;
2529 page_cache_async_readahead(mapping, &file->f_ra, file, page,
2530 page->index, last_index - page->index);
2531 return 0;
2532 }
2533
filemap_get_pages(struct kiocb * iocb,struct iov_iter * iter,struct pagevec * pvec)2534 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2535 struct pagevec *pvec)
2536 {
2537 struct file *filp = iocb->ki_filp;
2538 struct address_space *mapping = filp->f_mapping;
2539 struct file_ra_state *ra = &filp->f_ra;
2540 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2541 pgoff_t last_index;
2542 struct page *page;
2543 int err = 0;
2544
2545 /* "last_index" is the index of the page beyond the end of the read */
2546 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2547 retry:
2548 if (fatal_signal_pending(current))
2549 return -EINTR;
2550
2551 filemap_get_read_batch(mapping, index, last_index - 1, pvec);
2552 if (!pagevec_count(pvec)) {
2553 if (iocb->ki_flags & IOCB_NOIO)
2554 return -EAGAIN;
2555 page_cache_sync_readahead(mapping, ra, filp, index,
2556 last_index - index);
2557 filemap_get_read_batch(mapping, index, last_index - 1, pvec);
2558 }
2559 if (!pagevec_count(pvec)) {
2560 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2561 return -EAGAIN;
2562 err = filemap_create_page(filp, mapping,
2563 iocb->ki_pos >> PAGE_SHIFT, pvec);
2564 if (err == AOP_TRUNCATED_PAGE)
2565 goto retry;
2566 return err;
2567 }
2568
2569 page = pvec->pages[pagevec_count(pvec) - 1];
2570 if (PageReadahead(page)) {
2571 err = filemap_readahead(iocb, filp, mapping, page, last_index);
2572 if (err)
2573 goto err;
2574 }
2575 if (!PageUptodate(page)) {
2576 if ((iocb->ki_flags & IOCB_WAITQ) && pagevec_count(pvec) > 1)
2577 iocb->ki_flags |= IOCB_NOWAIT;
2578 err = filemap_update_page(iocb, mapping, iter, page);
2579 if (err)
2580 goto err;
2581 }
2582
2583 return 0;
2584 err:
2585 if (err < 0)
2586 put_page(page);
2587 if (likely(--pvec->nr))
2588 return 0;
2589 if (err == AOP_TRUNCATED_PAGE)
2590 goto retry;
2591 return err;
2592 }
2593
2594 /**
2595 * filemap_read - Read data from the page cache.
2596 * @iocb: The iocb to read.
2597 * @iter: Destination for the data.
2598 * @already_read: Number of bytes already read by the caller.
2599 *
2600 * Copies data from the page cache. If the data is not currently present,
2601 * uses the readahead and readpage address_space operations to fetch it.
2602 *
2603 * Return: Total number of bytes copied, including those already read by
2604 * the caller. If an error happens before any bytes are copied, returns
2605 * a negative error number.
2606 */
filemap_read(struct kiocb * iocb,struct iov_iter * iter,ssize_t already_read)2607 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2608 ssize_t already_read)
2609 {
2610 struct file *filp = iocb->ki_filp;
2611 struct file_ra_state *ra = &filp->f_ra;
2612 struct address_space *mapping = filp->f_mapping;
2613 struct inode *inode = mapping->host;
2614 struct pagevec pvec;
2615 int i, error = 0;
2616 bool writably_mapped;
2617 loff_t isize, end_offset;
2618 loff_t last_pos = ra->prev_pos;
2619
2620 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2621 return 0;
2622 if (unlikely(!iov_iter_count(iter)))
2623 return 0;
2624
2625 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2626 pagevec_init(&pvec);
2627
2628 do {
2629 cond_resched();
2630
2631 /*
2632 * If we've already successfully copied some data, then we
2633 * can no longer safely return -EIOCBQUEUED. Hence mark
2634 * an async read NOWAIT at that point.
2635 */
2636 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2637 iocb->ki_flags |= IOCB_NOWAIT;
2638
2639 error = filemap_get_pages(iocb, iter, &pvec);
2640 if (error < 0)
2641 break;
2642
2643 /*
2644 * i_size must be checked after we know the pages are Uptodate.
2645 *
2646 * Checking i_size after the check allows us to calculate
2647 * the correct value for "nr", which means the zero-filled
2648 * part of the page is not copied back to userspace (unless
2649 * another truncate extends the file - this is desired though).
2650 */
2651 isize = i_size_read(inode);
2652 if (unlikely(iocb->ki_pos >= isize))
2653 goto put_pages;
2654 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2655
2656 /*
2657 * Pairs with a barrier in
2658 * block_write_end()->mark_buffer_dirty() or other page
2659 * dirtying routines like iomap_write_end() to ensure
2660 * changes to page contents are visible before we see
2661 * increased inode size.
2662 */
2663 smp_rmb();
2664
2665 /*
2666 * Once we start copying data, we don't want to be touching any
2667 * cachelines that might be contended:
2668 */
2669 writably_mapped = mapping_writably_mapped(mapping);
2670
2671 /*
2672 * When a sequential read accesses a page several times, only
2673 * mark it as accessed the first time.
2674 */
2675 if (iocb->ki_pos >> PAGE_SHIFT !=
2676 last_pos >> PAGE_SHIFT)
2677 mark_page_accessed(pvec.pages[0]);
2678
2679 for (i = 0; i < pagevec_count(&pvec); i++) {
2680 struct page *page = pvec.pages[i];
2681 size_t page_size = thp_size(page);
2682 size_t offset = iocb->ki_pos & (page_size - 1);
2683 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2684 page_size - offset);
2685 size_t copied;
2686
2687 if (end_offset < page_offset(page))
2688 break;
2689 if (i > 0)
2690 mark_page_accessed(page);
2691 /*
2692 * If users can be writing to this page using arbitrary
2693 * virtual addresses, take care about potential aliasing
2694 * before reading the page on the kernel side.
2695 */
2696 if (writably_mapped) {
2697 int j;
2698
2699 for (j = 0; j < thp_nr_pages(page); j++)
2700 flush_dcache_page(page + j);
2701 }
2702
2703 copied = copy_page_to_iter(page, offset, bytes, iter);
2704
2705 already_read += copied;
2706 iocb->ki_pos += copied;
2707 last_pos = iocb->ki_pos;
2708
2709 if (copied < bytes) {
2710 error = -EFAULT;
2711 break;
2712 }
2713 }
2714 put_pages:
2715 for (i = 0; i < pagevec_count(&pvec); i++)
2716 put_page(pvec.pages[i]);
2717 pagevec_reinit(&pvec);
2718 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2719
2720 file_accessed(filp);
2721 ra->prev_pos = last_pos;
2722 return already_read ? already_read : error;
2723 }
2724 EXPORT_SYMBOL_GPL(filemap_read);
2725
2726 /**
2727 * generic_file_read_iter - generic filesystem read routine
2728 * @iocb: kernel I/O control block
2729 * @iter: destination for the data read
2730 *
2731 * This is the "read_iter()" routine for all filesystems
2732 * that can use the page cache directly.
2733 *
2734 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2735 * be returned when no data can be read without waiting for I/O requests
2736 * to complete; it doesn't prevent readahead.
2737 *
2738 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2739 * requests shall be made for the read or for readahead. When no data
2740 * can be read, -EAGAIN shall be returned. When readahead would be
2741 * triggered, a partial, possibly empty read shall be returned.
2742 *
2743 * Return:
2744 * * number of bytes copied, even for partial reads
2745 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2746 */
2747 ssize_t
generic_file_read_iter(struct kiocb * iocb,struct iov_iter * iter)2748 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2749 {
2750 size_t count = iov_iter_count(iter);
2751 ssize_t retval = 0;
2752
2753 if (!count)
2754 return 0; /* skip atime */
2755
2756 if (iocb->ki_flags & IOCB_DIRECT) {
2757 struct file *file = iocb->ki_filp;
2758 struct address_space *mapping = file->f_mapping;
2759 struct inode *inode = mapping->host;
2760 loff_t size;
2761
2762 size = i_size_read(inode);
2763 if (iocb->ki_flags & IOCB_NOWAIT) {
2764 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2765 iocb->ki_pos + count - 1))
2766 return -EAGAIN;
2767 } else {
2768 retval = filemap_write_and_wait_range(mapping,
2769 iocb->ki_pos,
2770 iocb->ki_pos + count - 1);
2771 if (retval < 0)
2772 return retval;
2773 }
2774
2775 file_accessed(file);
2776
2777 retval = mapping->a_ops->direct_IO(iocb, iter);
2778 if (retval >= 0) {
2779 iocb->ki_pos += retval;
2780 count -= retval;
2781 }
2782 if (retval != -EIOCBQUEUED)
2783 iov_iter_revert(iter, count - iov_iter_count(iter));
2784
2785 /*
2786 * Btrfs can have a short DIO read if we encounter
2787 * compressed extents, so if there was an error, or if
2788 * we've already read everything we wanted to, or if
2789 * there was a short read because we hit EOF, go ahead
2790 * and return. Otherwise fallthrough to buffered io for
2791 * the rest of the read. Buffered reads will not work for
2792 * DAX files, so don't bother trying.
2793 */
2794 if (retval < 0 || !count || iocb->ki_pos >= size ||
2795 IS_DAX(inode))
2796 return retval;
2797 }
2798
2799 return filemap_read(iocb, iter, retval);
2800 }
2801 EXPORT_SYMBOL(generic_file_read_iter);
2802
page_seek_hole_data(struct xa_state * xas,struct address_space * mapping,struct page * page,loff_t start,loff_t end,bool seek_data)2803 static inline loff_t page_seek_hole_data(struct xa_state *xas,
2804 struct address_space *mapping, struct page *page,
2805 loff_t start, loff_t end, bool seek_data)
2806 {
2807 const struct address_space_operations *ops = mapping->a_ops;
2808 size_t offset, bsz = i_blocksize(mapping->host);
2809
2810 if (xa_is_value(page) || PageUptodate(page))
2811 return seek_data ? start : end;
2812 if (!ops->is_partially_uptodate)
2813 return seek_data ? end : start;
2814
2815 xas_pause(xas);
2816 rcu_read_unlock();
2817 lock_page(page);
2818 if (unlikely(page->mapping != mapping))
2819 goto unlock;
2820
2821 offset = offset_in_thp(page, start) & ~(bsz - 1);
2822
2823 do {
2824 if (ops->is_partially_uptodate(page, offset, bsz) == seek_data)
2825 break;
2826 start = (start + bsz) & ~(bsz - 1);
2827 offset += bsz;
2828 } while (offset < thp_size(page));
2829 unlock:
2830 unlock_page(page);
2831 rcu_read_lock();
2832 return start;
2833 }
2834
2835 static inline
seek_page_size(struct xa_state * xas,struct page * page)2836 unsigned int seek_page_size(struct xa_state *xas, struct page *page)
2837 {
2838 if (xa_is_value(page))
2839 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2840 return thp_size(page);
2841 }
2842
2843 /**
2844 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2845 * @mapping: Address space to search.
2846 * @start: First byte to consider.
2847 * @end: Limit of search (exclusive).
2848 * @whence: Either SEEK_HOLE or SEEK_DATA.
2849 *
2850 * If the page cache knows which blocks contain holes and which blocks
2851 * contain data, your filesystem can use this function to implement
2852 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
2853 * entirely memory-based such as tmpfs, and filesystems which support
2854 * unwritten extents.
2855 *
2856 * Return: The requested offset on success, or -ENXIO if @whence specifies
2857 * SEEK_DATA and there is no data after @start. There is an implicit hole
2858 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2859 * and @end contain data.
2860 */
mapping_seek_hole_data(struct address_space * mapping,loff_t start,loff_t end,int whence)2861 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2862 loff_t end, int whence)
2863 {
2864 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
2865 pgoff_t max = (end - 1) >> PAGE_SHIFT;
2866 bool seek_data = (whence == SEEK_DATA);
2867 struct page *page;
2868
2869 if (end <= start)
2870 return -ENXIO;
2871
2872 rcu_read_lock();
2873 while ((page = find_get_entry(&xas, max, XA_PRESENT))) {
2874 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2875 unsigned int seek_size;
2876
2877 if (start < pos) {
2878 if (!seek_data)
2879 goto unlock;
2880 start = pos;
2881 }
2882
2883 seek_size = seek_page_size(&xas, page);
2884 pos = round_up(pos + 1, seek_size);
2885 start = page_seek_hole_data(&xas, mapping, page, start, pos,
2886 seek_data);
2887 if (start < pos)
2888 goto unlock;
2889 if (start >= end)
2890 break;
2891 if (seek_size > PAGE_SIZE)
2892 xas_set(&xas, pos >> PAGE_SHIFT);
2893 if (!xa_is_value(page))
2894 put_page(page);
2895 }
2896 if (seek_data)
2897 start = -ENXIO;
2898 unlock:
2899 rcu_read_unlock();
2900 if (page && !xa_is_value(page))
2901 put_page(page);
2902 if (start > end)
2903 return end;
2904 return start;
2905 }
2906
2907 #ifdef CONFIG_MMU
2908 #define MMAP_LOTSAMISS (100)
2909 /*
2910 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2911 * @vmf - the vm_fault for this fault.
2912 * @page - the page to lock.
2913 * @fpin - the pointer to the file we may pin (or is already pinned).
2914 *
2915 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
2916 * It differs in that it actually returns the page locked if it returns 1 and 0
2917 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
2918 * will point to the pinned file and needs to be fput()'ed at a later point.
2919 */
lock_page_maybe_drop_mmap(struct vm_fault * vmf,struct page * page,struct file ** fpin)2920 static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2921 struct file **fpin)
2922 {
2923 if (trylock_page(page))
2924 return 1;
2925
2926 /*
2927 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2928 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2929 * is supposed to work. We have way too many special cases..
2930 */
2931 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2932 return 0;
2933
2934 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2935 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2936 if (__lock_page_killable(page)) {
2937 /*
2938 * We didn't have the right flags to drop the mmap_lock,
2939 * but all fault_handlers only check for fatal signals
2940 * if we return VM_FAULT_RETRY, so we need to drop the
2941 * mmap_lock here and return 0 if we don't have a fpin.
2942 */
2943 if (*fpin == NULL)
2944 mmap_read_unlock(vmf->vma->vm_mm);
2945 return 0;
2946 }
2947 } else
2948 __lock_page(page);
2949 return 1;
2950 }
2951
2952
2953 /*
2954 * Synchronous readahead happens when we don't even find a page in the page
2955 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2956 * to drop the mmap sem we return the file that was pinned in order for us to do
2957 * that. If we didn't pin a file then we return NULL. The file that is
2958 * returned needs to be fput()'ed when we're done with it.
2959 */
do_sync_mmap_readahead(struct vm_fault * vmf)2960 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2961 {
2962 struct file *file = vmf->vma->vm_file;
2963 struct file_ra_state *ra = &file->f_ra;
2964 struct address_space *mapping = file->f_mapping;
2965 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
2966 struct file *fpin = NULL;
2967 unsigned int mmap_miss;
2968
2969 /* If we don't want any read-ahead, don't bother */
2970 if (vmf->vma->vm_flags & VM_RAND_READ)
2971 return fpin;
2972 if (!ra->ra_pages)
2973 return fpin;
2974
2975 if (vmf->vma->vm_flags & VM_SEQ_READ) {
2976 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2977 page_cache_sync_ra(&ractl, ra->ra_pages);
2978 return fpin;
2979 }
2980
2981 /* Avoid banging the cache line if not needed */
2982 mmap_miss = READ_ONCE(ra->mmap_miss);
2983 if (mmap_miss < MMAP_LOTSAMISS * 10)
2984 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
2985
2986 /*
2987 * Do we miss much more than hit in this file? If so,
2988 * stop bothering with read-ahead. It will only hurt.
2989 */
2990 if (mmap_miss > MMAP_LOTSAMISS)
2991 return fpin;
2992
2993 /*
2994 * mmap read-around
2995 */
2996 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2997 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
2998 ra->size = ra->ra_pages;
2999 ra->async_size = ra->ra_pages / 4;
3000 trace_android_vh_tune_mmap_readaround(ra->ra_pages, vmf->pgoff,
3001 &ra->start, &ra->size, &ra->async_size);
3002 ractl._index = ra->start;
3003 do_page_cache_ra(&ractl, ra->size, ra->async_size);
3004 return fpin;
3005 }
3006
3007 /*
3008 * Asynchronous readahead happens when we find the page and PG_readahead,
3009 * so we want to possibly extend the readahead further. We return the file that
3010 * was pinned if we have to drop the mmap_lock in order to do IO.
3011 */
do_async_mmap_readahead(struct vm_fault * vmf,struct page * page)3012 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
3013 struct page *page)
3014 {
3015 struct file *file = vmf->vma->vm_file;
3016 struct file_ra_state *ra = &file->f_ra;
3017 struct address_space *mapping = file->f_mapping;
3018 struct file *fpin = NULL;
3019 unsigned int mmap_miss;
3020 pgoff_t offset = vmf->pgoff;
3021
3022 /* If we don't want any read-ahead, don't bother */
3023 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
3024 return fpin;
3025 mmap_miss = READ_ONCE(ra->mmap_miss);
3026 if (mmap_miss)
3027 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
3028 if (PageReadahead(page)) {
3029 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3030 page_cache_async_readahead(mapping, ra, file,
3031 page, offset, ra->ra_pages);
3032 }
3033 return fpin;
3034 }
3035
3036 /**
3037 * filemap_fault - read in file data for page fault handling
3038 * @vmf: struct vm_fault containing details of the fault
3039 *
3040 * filemap_fault() is invoked via the vma operations vector for a
3041 * mapped memory region to read in file data during a page fault.
3042 *
3043 * The goto's are kind of ugly, but this streamlines the normal case of having
3044 * it in the page cache, and handles the special cases reasonably without
3045 * having a lot of duplicated code.
3046 *
3047 * If FAULT_FLAG_SPECULATIVE is set, this function runs within an rcu
3048 * read locked section and with mmap lock not held.
3049 * Otherwise, vma->vm_mm->mmap_lock must be held on entry.
3050 *
3051 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
3052 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
3053 *
3054 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
3055 * has not been released.
3056 *
3057 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3058 *
3059 * Return: bitwise-OR of %VM_FAULT_ codes.
3060 */
filemap_fault(struct vm_fault * vmf)3061 vm_fault_t filemap_fault(struct vm_fault *vmf)
3062 {
3063 int error;
3064 struct file *file = vmf->vma->vm_file;
3065 struct file *fpin = NULL;
3066 struct address_space *mapping = file->f_mapping;
3067 struct file_ra_state *ra = &file->f_ra;
3068 struct inode *inode = mapping->host;
3069 pgoff_t offset = vmf->pgoff;
3070 pgoff_t max_off;
3071 struct page *page;
3072 vm_fault_t ret = 0;
3073 bool mapping_locked = false;
3074
3075 if (vmf->flags & FAULT_FLAG_SPECULATIVE) {
3076 page = find_get_page(mapping, offset);
3077 if (unlikely(!page))
3078 return VM_FAULT_RETRY;
3079
3080 if (unlikely(PageReadahead(page)))
3081 goto page_put;
3082
3083 if (!trylock_page(page))
3084 goto page_put;
3085
3086 if (unlikely(compound_head(page)->mapping != mapping))
3087 goto page_unlock;
3088 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
3089 if (unlikely(!PageUptodate(page)))
3090 goto page_unlock;
3091
3092 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3093 if (unlikely(offset >= max_off))
3094 goto page_unlock;
3095
3096 /*
3097 * Update readahead mmap_miss statistic.
3098 *
3099 * Note that we are not sure if finish_fault() will
3100 * manage to complete the transaction. If it fails,
3101 * we'll come back to filemap_fault() non-speculative
3102 * case which will update mmap_miss a second time.
3103 * This is not ideal, we would prefer to guarantee the
3104 * update will happen exactly once.
3105 */
3106 if (!(vmf->vma->vm_flags & VM_RAND_READ) && ra->ra_pages) {
3107 unsigned int mmap_miss = READ_ONCE(ra->mmap_miss);
3108 if (mmap_miss)
3109 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
3110 }
3111
3112 vmf->page = page;
3113 return VM_FAULT_LOCKED;
3114 page_unlock:
3115 unlock_page(page);
3116 page_put:
3117 put_page(page);
3118 return VM_FAULT_RETRY;
3119 }
3120
3121 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3122 if (unlikely(offset >= max_off))
3123 return VM_FAULT_SIGBUS;
3124
3125 /*
3126 * Do we have something in the page cache already?
3127 */
3128 page = find_get_page(mapping, offset);
3129 if (likely(page)) {
3130 /*
3131 * We found the page, so try async readahead before waiting for
3132 * the lock.
3133 */
3134 if (!(vmf->flags & FAULT_FLAG_TRIED))
3135 fpin = do_async_mmap_readahead(vmf, page);
3136 if (unlikely(!PageUptodate(page))) {
3137 filemap_invalidate_lock_shared(mapping);
3138 mapping_locked = true;
3139 }
3140 } else {
3141 /* No page in the page cache at all */
3142 count_vm_event(PGMAJFAULT);
3143 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3144 ret = VM_FAULT_MAJOR;
3145 fpin = do_sync_mmap_readahead(vmf);
3146 retry_find:
3147 /*
3148 * See comment in filemap_create_page() why we need
3149 * invalidate_lock
3150 */
3151 if (!mapping_locked) {
3152 filemap_invalidate_lock_shared(mapping);
3153 mapping_locked = true;
3154 }
3155 page = pagecache_get_page(mapping, offset,
3156 FGP_CREAT|FGP_FOR_MMAP,
3157 vmf->gfp_mask);
3158 if (!page) {
3159 if (fpin)
3160 goto out_retry;
3161 filemap_invalidate_unlock_shared(mapping);
3162 return VM_FAULT_OOM;
3163 }
3164 }
3165
3166 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
3167 goto out_retry;
3168
3169 /* Did it get truncated? */
3170 if (unlikely(compound_head(page)->mapping != mapping)) {
3171 unlock_page(page);
3172 put_page(page);
3173 goto retry_find;
3174 }
3175 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
3176
3177 /*
3178 * We have a locked page in the page cache, now we need to check
3179 * that it's up-to-date. If not, it is going to be due to an error.
3180 */
3181 if (unlikely(!PageUptodate(page))) {
3182 /*
3183 * The page was in cache and uptodate and now it is not.
3184 * Strange but possible since we didn't hold the page lock all
3185 * the time. Let's drop everything get the invalidate lock and
3186 * try again.
3187 */
3188 if (!mapping_locked) {
3189 unlock_page(page);
3190 put_page(page);
3191 goto retry_find;
3192 }
3193 goto page_not_uptodate;
3194 }
3195
3196 /*
3197 * We've made it this far and we had to drop our mmap_lock, now is the
3198 * time to return to the upper layer and have it re-find the vma and
3199 * redo the fault.
3200 */
3201 if (fpin) {
3202 unlock_page(page);
3203 goto out_retry;
3204 }
3205 if (mapping_locked)
3206 filemap_invalidate_unlock_shared(mapping);
3207
3208 /*
3209 * Found the page and have a reference on it.
3210 * We must recheck i_size under page lock.
3211 */
3212 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3213 if (unlikely(offset >= max_off)) {
3214 unlock_page(page);
3215 put_page(page);
3216 return VM_FAULT_SIGBUS;
3217 }
3218
3219 vmf->page = page;
3220 return ret | VM_FAULT_LOCKED;
3221
3222 page_not_uptodate:
3223 /*
3224 * Umm, take care of errors if the page isn't up-to-date.
3225 * Try to re-read it _once_. We do this synchronously,
3226 * because there really aren't any performance issues here
3227 * and we need to check for errors.
3228 */
3229 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3230 error = filemap_read_page(file, mapping, page);
3231 if (fpin)
3232 goto out_retry;
3233 put_page(page);
3234
3235 if (!error || error == AOP_TRUNCATED_PAGE)
3236 goto retry_find;
3237 filemap_invalidate_unlock_shared(mapping);
3238
3239 return VM_FAULT_SIGBUS;
3240
3241 out_retry:
3242 /*
3243 * We dropped the mmap_lock, we need to return to the fault handler to
3244 * re-find the vma and come back and find our hopefully still populated
3245 * page.
3246 */
3247 if (page)
3248 put_page(page);
3249 if (mapping_locked)
3250 filemap_invalidate_unlock_shared(mapping);
3251 if (fpin)
3252 fput(fpin);
3253 return ret | VM_FAULT_RETRY;
3254 }
3255 EXPORT_SYMBOL(filemap_fault);
3256
filemap_map_pmd(struct vm_fault * vmf,struct page * page)3257 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3258 {
3259 struct mm_struct *mm = vmf->vma->vm_mm;
3260
3261 /* Huge page is mapped? No need to proceed. */
3262 if (pmd_trans_huge(*vmf->pmd)) {
3263 unlock_page(page);
3264 put_page(page);
3265 return true;
3266 }
3267
3268 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3269 vm_fault_t ret = do_set_pmd(vmf, page);
3270 if (!ret) {
3271 /* The page is mapped successfully, reference consumed. */
3272 unlock_page(page);
3273 return true;
3274 }
3275 }
3276
3277 if (pmd_none(*vmf->pmd) && vmf->prealloc_pte) {
3278 vmf->ptl = pmd_lock(mm, vmf->pmd);
3279 if (likely(pmd_none(*vmf->pmd))) {
3280 mm_inc_nr_ptes(mm);
3281 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
3282 vmf->prealloc_pte = NULL;
3283 }
3284 spin_unlock(vmf->ptl);
3285 }
3286
3287 /* See comment in handle_pte_fault() */
3288 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3289 unlock_page(page);
3290 put_page(page);
3291 return true;
3292 }
3293
3294 return false;
3295 }
3296
next_uptodate_page(struct page * page,struct address_space * mapping,struct xa_state * xas,pgoff_t end_pgoff)3297 static struct page *next_uptodate_page(struct page *page,
3298 struct address_space *mapping,
3299 struct xa_state *xas, pgoff_t end_pgoff)
3300 {
3301 unsigned long max_idx;
3302
3303 do {
3304 if (!page)
3305 return NULL;
3306 if (xas_retry(xas, page))
3307 continue;
3308 if (xa_is_value(page))
3309 continue;
3310 if (PageLocked(page))
3311 continue;
3312 if (!page_cache_get_speculative(page))
3313 continue;
3314 /* Has the page moved or been split? */
3315 if (unlikely(page != xas_reload(xas)))
3316 goto skip;
3317 if (!PageUptodate(page) || PageReadahead(page))
3318 goto skip;
3319 if (PageHWPoison(page))
3320 goto skip;
3321 if (!trylock_page(page))
3322 goto skip;
3323 if (page->mapping != mapping)
3324 goto unlock;
3325 if (!PageUptodate(page))
3326 goto unlock;
3327 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3328 if (xas->xa_index >= max_idx)
3329 goto unlock;
3330 return page;
3331 unlock:
3332 unlock_page(page);
3333 skip:
3334 put_page(page);
3335 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
3336
3337 return NULL;
3338 }
3339
first_map_page(struct address_space * mapping,struct xa_state * xas,pgoff_t end_pgoff)3340 static inline struct page *first_map_page(struct address_space *mapping,
3341 struct xa_state *xas,
3342 pgoff_t end_pgoff)
3343 {
3344 return next_uptodate_page(xas_find(xas, end_pgoff),
3345 mapping, xas, end_pgoff);
3346 }
3347
next_map_page(struct address_space * mapping,struct xa_state * xas,pgoff_t end_pgoff)3348 static inline struct page *next_map_page(struct address_space *mapping,
3349 struct xa_state *xas,
3350 pgoff_t end_pgoff)
3351 {
3352 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3353 mapping, xas, end_pgoff);
3354 }
3355
filemap_map_pages(struct vm_fault * vmf,pgoff_t start_pgoff,pgoff_t end_pgoff)3356 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3357 pgoff_t start_pgoff, pgoff_t end_pgoff)
3358 {
3359 struct vm_area_struct *vma = vmf->vma;
3360 struct file *file = vma->vm_file;
3361 struct address_space *mapping = file->f_mapping;
3362 pgoff_t last_pgoff;
3363 unsigned long addr;
3364 XA_STATE(xas, &mapping->i_pages, start_pgoff);
3365 struct page *head, *page;
3366 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3367 vm_fault_t ret = (vmf->flags & FAULT_FLAG_SPECULATIVE) ?
3368 VM_FAULT_RETRY : 0;
3369
3370 /* filemap_map_pages() is called within an rcu read lock already. */
3371 head = first_map_page(mapping, &xas, end_pgoff);
3372 if (!head)
3373 return ret;
3374
3375 if (!(vmf->flags & FAULT_FLAG_SPECULATIVE) &&
3376 filemap_map_pmd(vmf, head))
3377 return VM_FAULT_NOPAGE;
3378
3379 if (!pte_map_lock(vmf)) {
3380 unlock_page(head);
3381 put_page(head);
3382 return VM_FAULT_RETRY;
3383 }
3384 addr = vmf->address;
3385 last_pgoff = vmf->pgoff;
3386
3387 do {
3388 page = find_subpage(head, xas.xa_index);
3389 if (PageHWPoison(page))
3390 goto unlock;
3391
3392 if (mmap_miss > 0)
3393 mmap_miss--;
3394
3395 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3396 vmf->pte += xas.xa_index - last_pgoff;
3397 last_pgoff = xas.xa_index;
3398
3399 if (!pte_none(*vmf->pte))
3400 goto unlock;
3401
3402 /* We're about to handle the fault */
3403 if (vmf->address == addr)
3404 ret = VM_FAULT_NOPAGE;
3405
3406 do_set_pte(vmf, page, addr);
3407 /* no need to invalidate: a not-present page won't be cached */
3408 update_mmu_cache(vma, addr, vmf->pte);
3409 unlock_page(head);
3410 continue;
3411 unlock:
3412 unlock_page(head);
3413 put_page(head);
3414 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3415 pte_unmap_unlock(vmf->pte, vmf->ptl);
3416 vmf->pte = NULL;
3417 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3418 return ret;
3419 }
3420 EXPORT_SYMBOL(filemap_map_pages);
3421
filemap_page_mkwrite(struct vm_fault * vmf)3422 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3423 {
3424 struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3425 struct page *page = vmf->page;
3426 vm_fault_t ret = VM_FAULT_LOCKED;
3427
3428 sb_start_pagefault(mapping->host->i_sb);
3429 file_update_time(vmf->vma->vm_file);
3430 lock_page(page);
3431 if (page->mapping != mapping) {
3432 unlock_page(page);
3433 ret = VM_FAULT_NOPAGE;
3434 goto out;
3435 }
3436 /*
3437 * We mark the page dirty already here so that when freeze is in
3438 * progress, we are guaranteed that writeback during freezing will
3439 * see the dirty page and writeprotect it again.
3440 */
3441 set_page_dirty(page);
3442 wait_for_stable_page(page);
3443 out:
3444 sb_end_pagefault(mapping->host->i_sb);
3445 return ret;
3446 }
3447
3448 const struct vm_operations_struct generic_file_vm_ops = {
3449 .fault = filemap_fault,
3450 .map_pages = filemap_map_pages,
3451 .page_mkwrite = filemap_page_mkwrite,
3452 .speculative = true,
3453 };
3454
3455 /* This is used for a general mmap of a disk file */
3456
generic_file_mmap(struct file * file,struct vm_area_struct * vma)3457 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3458 {
3459 struct address_space *mapping = file->f_mapping;
3460
3461 if (!mapping->a_ops->readpage)
3462 return -ENOEXEC;
3463 file_accessed(file);
3464 vma->vm_ops = &generic_file_vm_ops;
3465 return 0;
3466 }
3467
3468 /*
3469 * This is for filesystems which do not implement ->writepage.
3470 */
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)3471 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3472 {
3473 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3474 return -EINVAL;
3475 return generic_file_mmap(file, vma);
3476 }
3477 #else
filemap_page_mkwrite(struct vm_fault * vmf)3478 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3479 {
3480 return VM_FAULT_SIGBUS;
3481 }
generic_file_mmap(struct file * file,struct vm_area_struct * vma)3482 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3483 {
3484 return -ENOSYS;
3485 }
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)3486 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3487 {
3488 return -ENOSYS;
3489 }
3490 #endif /* CONFIG_MMU */
3491
3492 EXPORT_SYMBOL(filemap_page_mkwrite);
3493 EXPORT_SYMBOL(generic_file_mmap);
3494 EXPORT_SYMBOL(generic_file_readonly_mmap);
3495
wait_on_page_read(struct page * page)3496 static struct page *wait_on_page_read(struct page *page)
3497 {
3498 if (!IS_ERR(page)) {
3499 wait_on_page_locked(page);
3500 if (!PageUptodate(page)) {
3501 put_page(page);
3502 page = ERR_PTR(-EIO);
3503 }
3504 }
3505 return page;
3506 }
3507
do_read_cache_page(struct address_space * mapping,pgoff_t index,int (* filler)(void *,struct page *),void * data,gfp_t gfp)3508 static struct page *do_read_cache_page(struct address_space *mapping,
3509 pgoff_t index,
3510 int (*filler)(void *, struct page *),
3511 void *data,
3512 gfp_t gfp)
3513 {
3514 struct page *page;
3515 int err;
3516 repeat:
3517 page = find_get_page(mapping, index);
3518 if (!page) {
3519 page = __page_cache_alloc(gfp);
3520 if (!page)
3521 return ERR_PTR(-ENOMEM);
3522 err = add_to_page_cache_lru(page, mapping, index, gfp);
3523 if (unlikely(err)) {
3524 put_page(page);
3525 if (err == -EEXIST)
3526 goto repeat;
3527 /* Presumably ENOMEM for xarray node */
3528 return ERR_PTR(err);
3529 }
3530
3531 filler:
3532 if (filler)
3533 err = filler(data, page);
3534 else
3535 err = mapping->a_ops->readpage(data, page);
3536
3537 if (err < 0) {
3538 put_page(page);
3539 return ERR_PTR(err);
3540 }
3541
3542 page = wait_on_page_read(page);
3543 if (IS_ERR(page))
3544 return page;
3545 goto out;
3546 }
3547 if (PageUptodate(page))
3548 goto out;
3549
3550 /*
3551 * Page is not up to date and may be locked due to one of the following
3552 * case a: Page is being filled and the page lock is held
3553 * case b: Read/write error clearing the page uptodate status
3554 * case c: Truncation in progress (page locked)
3555 * case d: Reclaim in progress
3556 *
3557 * Case a, the page will be up to date when the page is unlocked.
3558 * There is no need to serialise on the page lock here as the page
3559 * is pinned so the lock gives no additional protection. Even if the
3560 * page is truncated, the data is still valid if PageUptodate as
3561 * it's a race vs truncate race.
3562 * Case b, the page will not be up to date
3563 * Case c, the page may be truncated but in itself, the data may still
3564 * be valid after IO completes as it's a read vs truncate race. The
3565 * operation must restart if the page is not uptodate on unlock but
3566 * otherwise serialising on page lock to stabilise the mapping gives
3567 * no additional guarantees to the caller as the page lock is
3568 * released before return.
3569 * Case d, similar to truncation. If reclaim holds the page lock, it
3570 * will be a race with remove_mapping that determines if the mapping
3571 * is valid on unlock but otherwise the data is valid and there is
3572 * no need to serialise with page lock.
3573 *
3574 * As the page lock gives no additional guarantee, we optimistically
3575 * wait on the page to be unlocked and check if it's up to date and
3576 * use the page if it is. Otherwise, the page lock is required to
3577 * distinguish between the different cases. The motivation is that we
3578 * avoid spurious serialisations and wakeups when multiple processes
3579 * wait on the same page for IO to complete.
3580 */
3581 wait_on_page_locked(page);
3582 if (PageUptodate(page))
3583 goto out;
3584
3585 /* Distinguish between all the cases under the safety of the lock */
3586 lock_page(page);
3587
3588 /* Case c or d, restart the operation */
3589 if (!page->mapping) {
3590 unlock_page(page);
3591 put_page(page);
3592 goto repeat;
3593 }
3594
3595 /* Someone else locked and filled the page in a very small window */
3596 if (PageUptodate(page)) {
3597 unlock_page(page);
3598 goto out;
3599 }
3600
3601 /*
3602 * A previous I/O error may have been due to temporary
3603 * failures.
3604 * Clear page error before actual read, PG_error will be
3605 * set again if read page fails.
3606 */
3607 ClearPageError(page);
3608 goto filler;
3609
3610 out:
3611 mark_page_accessed(page);
3612 return page;
3613 }
3614
3615 /**
3616 * read_cache_page - read into page cache, fill it if needed
3617 * @mapping: the page's address_space
3618 * @index: the page index
3619 * @filler: function to perform the read
3620 * @data: first arg to filler(data, page) function, often left as NULL
3621 *
3622 * Read into the page cache. If a page already exists, and PageUptodate() is
3623 * not set, try to fill the page and wait for it to become unlocked.
3624 *
3625 * If the page does not get brought uptodate, return -EIO.
3626 *
3627 * The function expects mapping->invalidate_lock to be already held.
3628 *
3629 * Return: up to date page on success, ERR_PTR() on failure.
3630 */
read_cache_page(struct address_space * mapping,pgoff_t index,int (* filler)(void *,struct page *),void * data)3631 struct page *read_cache_page(struct address_space *mapping,
3632 pgoff_t index,
3633 int (*filler)(void *, struct page *),
3634 void *data)
3635 {
3636 return do_read_cache_page(mapping, index, filler, data,
3637 mapping_gfp_mask(mapping));
3638 }
3639 EXPORT_SYMBOL(read_cache_page);
3640
3641 /**
3642 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3643 * @mapping: the page's address_space
3644 * @index: the page index
3645 * @gfp: the page allocator flags to use if allocating
3646 *
3647 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3648 * any new page allocations done using the specified allocation flags.
3649 *
3650 * If the page does not get brought uptodate, return -EIO.
3651 *
3652 * The function expects mapping->invalidate_lock to be already held.
3653 *
3654 * Return: up to date page on success, ERR_PTR() on failure.
3655 */
read_cache_page_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)3656 struct page *read_cache_page_gfp(struct address_space *mapping,
3657 pgoff_t index,
3658 gfp_t gfp)
3659 {
3660 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3661 }
3662 EXPORT_SYMBOL(read_cache_page_gfp);
3663
pagecache_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)3664 int pagecache_write_begin(struct file *file, struct address_space *mapping,
3665 loff_t pos, unsigned len, unsigned flags,
3666 struct page **pagep, void **fsdata)
3667 {
3668 const struct address_space_operations *aops = mapping->a_ops;
3669
3670 return aops->write_begin(file, mapping, pos, len, flags,
3671 pagep, fsdata);
3672 }
3673 EXPORT_SYMBOL(pagecache_write_begin);
3674
pagecache_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)3675 int pagecache_write_end(struct file *file, struct address_space *mapping,
3676 loff_t pos, unsigned len, unsigned copied,
3677 struct page *page, void *fsdata)
3678 {
3679 const struct address_space_operations *aops = mapping->a_ops;
3680
3681 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3682 }
3683 EXPORT_SYMBOL(pagecache_write_end);
3684
3685 /*
3686 * Warn about a page cache invalidation failure during a direct I/O write.
3687 */
dio_warn_stale_pagecache(struct file * filp)3688 void dio_warn_stale_pagecache(struct file *filp)
3689 {
3690 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3691 char pathname[128];
3692 char *path;
3693
3694 errseq_set(&filp->f_mapping->wb_err, -EIO);
3695 if (__ratelimit(&_rs)) {
3696 path = file_path(filp, pathname, sizeof(pathname));
3697 if (IS_ERR(path))
3698 path = "(unknown)";
3699 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3700 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3701 current->comm);
3702 }
3703 }
3704
3705 ssize_t
generic_file_direct_write(struct kiocb * iocb,struct iov_iter * from)3706 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3707 {
3708 struct file *file = iocb->ki_filp;
3709 struct address_space *mapping = file->f_mapping;
3710 struct inode *inode = mapping->host;
3711 loff_t pos = iocb->ki_pos;
3712 ssize_t written;
3713 size_t write_len;
3714 pgoff_t end;
3715
3716 write_len = iov_iter_count(from);
3717 end = (pos + write_len - 1) >> PAGE_SHIFT;
3718
3719 if (iocb->ki_flags & IOCB_NOWAIT) {
3720 /* If there are pages to writeback, return */
3721 if (filemap_range_has_page(file->f_mapping, pos,
3722 pos + write_len - 1))
3723 return -EAGAIN;
3724 } else {
3725 written = filemap_write_and_wait_range(mapping, pos,
3726 pos + write_len - 1);
3727 if (written)
3728 goto out;
3729 }
3730
3731 /*
3732 * After a write we want buffered reads to be sure to go to disk to get
3733 * the new data. We invalidate clean cached page from the region we're
3734 * about to write. We do this *before* the write so that we can return
3735 * without clobbering -EIOCBQUEUED from ->direct_IO().
3736 */
3737 written = invalidate_inode_pages2_range(mapping,
3738 pos >> PAGE_SHIFT, end);
3739 /*
3740 * If a page can not be invalidated, return 0 to fall back
3741 * to buffered write.
3742 */
3743 if (written) {
3744 if (written == -EBUSY)
3745 return 0;
3746 goto out;
3747 }
3748
3749 written = mapping->a_ops->direct_IO(iocb, from);
3750
3751 /*
3752 * Finally, try again to invalidate clean pages which might have been
3753 * cached by non-direct readahead, or faulted in by get_user_pages()
3754 * if the source of the write was an mmap'ed region of the file
3755 * we're writing. Either one is a pretty crazy thing to do,
3756 * so we don't support it 100%. If this invalidation
3757 * fails, tough, the write still worked...
3758 *
3759 * Most of the time we do not need this since dio_complete() will do
3760 * the invalidation for us. However there are some file systems that
3761 * do not end up with dio_complete() being called, so let's not break
3762 * them by removing it completely.
3763 *
3764 * Noticeable example is a blkdev_direct_IO().
3765 *
3766 * Skip invalidation for async writes or if mapping has no pages.
3767 */
3768 if (written > 0 && mapping->nrpages &&
3769 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3770 dio_warn_stale_pagecache(file);
3771
3772 if (written > 0) {
3773 pos += written;
3774 write_len -= written;
3775 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3776 i_size_write(inode, pos);
3777 mark_inode_dirty(inode);
3778 }
3779 iocb->ki_pos = pos;
3780 }
3781 if (written != -EIOCBQUEUED)
3782 iov_iter_revert(from, write_len - iov_iter_count(from));
3783 out:
3784 return written;
3785 }
3786 EXPORT_SYMBOL(generic_file_direct_write);
3787
3788 /*
3789 * Find or create a page at the given pagecache position. Return the locked
3790 * page. This function is specifically for buffered writes.
3791 */
grab_cache_page_write_begin(struct address_space * mapping,pgoff_t index,unsigned flags)3792 struct page *grab_cache_page_write_begin(struct address_space *mapping,
3793 pgoff_t index, unsigned flags)
3794 {
3795 struct page *page;
3796 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3797
3798 if (flags & AOP_FLAG_NOFS)
3799 fgp_flags |= FGP_NOFS;
3800
3801 page = pagecache_get_page(mapping, index, fgp_flags,
3802 mapping_gfp_mask(mapping));
3803 if (page)
3804 wait_for_stable_page(page);
3805
3806 return page;
3807 }
3808 EXPORT_SYMBOL(grab_cache_page_write_begin);
3809
generic_perform_write(struct file * file,struct iov_iter * i,loff_t pos)3810 ssize_t generic_perform_write(struct file *file,
3811 struct iov_iter *i, loff_t pos)
3812 {
3813 struct address_space *mapping = file->f_mapping;
3814 const struct address_space_operations *a_ops = mapping->a_ops;
3815 long status = 0;
3816 ssize_t written = 0;
3817 unsigned int flags = 0;
3818
3819 do {
3820 struct page *page;
3821 unsigned long offset; /* Offset into pagecache page */
3822 unsigned long bytes; /* Bytes to write to page */
3823 size_t copied; /* Bytes copied from user */
3824 void *fsdata = NULL;
3825
3826 offset = (pos & (PAGE_SIZE - 1));
3827 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3828 iov_iter_count(i));
3829
3830 again:
3831 /*
3832 * Bring in the user page that we will copy from _first_.
3833 * Otherwise there's a nasty deadlock on copying from the
3834 * same page as we're writing to, without it being marked
3835 * up-to-date.
3836 */
3837 if (unlikely(fault_in_iov_iter_readable(i, bytes))) {
3838 status = -EFAULT;
3839 break;
3840 }
3841
3842 if (fatal_signal_pending(current)) {
3843 status = -EINTR;
3844 break;
3845 }
3846
3847 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3848 &page, &fsdata);
3849 if (unlikely(status < 0))
3850 break;
3851
3852 if (mapping_writably_mapped(mapping))
3853 flush_dcache_page(page);
3854
3855 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3856 flush_dcache_page(page);
3857
3858 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3859 page, fsdata);
3860 if (unlikely(status != copied)) {
3861 iov_iter_revert(i, copied - max(status, 0L));
3862 if (unlikely(status < 0))
3863 break;
3864 }
3865 cond_resched();
3866
3867 if (unlikely(status == 0)) {
3868 /*
3869 * A short copy made ->write_end() reject the
3870 * thing entirely. Might be memory poisoning
3871 * halfway through, might be a race with munmap,
3872 * might be severe memory pressure.
3873 */
3874 if (copied)
3875 bytes = copied;
3876 goto again;
3877 }
3878 pos += status;
3879 written += status;
3880
3881 balance_dirty_pages_ratelimited(mapping);
3882 } while (iov_iter_count(i));
3883
3884 return written ? written : status;
3885 }
3886 EXPORT_SYMBOL(generic_perform_write);
3887
3888 /**
3889 * __generic_file_write_iter - write data to a file
3890 * @iocb: IO state structure (file, offset, etc.)
3891 * @from: iov_iter with data to write
3892 *
3893 * This function does all the work needed for actually writing data to a
3894 * file. It does all basic checks, removes SUID from the file, updates
3895 * modification times and calls proper subroutines depending on whether we
3896 * do direct IO or a standard buffered write.
3897 *
3898 * It expects i_rwsem to be grabbed unless we work on a block device or similar
3899 * object which does not need locking at all.
3900 *
3901 * This function does *not* take care of syncing data in case of O_SYNC write.
3902 * A caller has to handle it. This is mainly due to the fact that we want to
3903 * avoid syncing under i_rwsem.
3904 *
3905 * Return:
3906 * * number of bytes written, even for truncated writes
3907 * * negative error code if no data has been written at all
3908 */
__generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)3909 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3910 {
3911 struct file *file = iocb->ki_filp;
3912 struct address_space *mapping = file->f_mapping;
3913 struct inode *inode = mapping->host;
3914 ssize_t written = 0;
3915 ssize_t err;
3916 ssize_t status;
3917
3918 /* We can write back this queue in page reclaim */
3919 current->backing_dev_info = inode_to_bdi(inode);
3920 err = file_remove_privs(file);
3921 if (err)
3922 goto out;
3923
3924 err = file_update_time(file);
3925 if (err)
3926 goto out;
3927
3928 if (iocb->ki_flags & IOCB_DIRECT) {
3929 loff_t pos, endbyte;
3930
3931 written = generic_file_direct_write(iocb, from);
3932 /*
3933 * If the write stopped short of completing, fall back to
3934 * buffered writes. Some filesystems do this for writes to
3935 * holes, for example. For DAX files, a buffered write will
3936 * not succeed (even if it did, DAX does not handle dirty
3937 * page-cache pages correctly).
3938 */
3939 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3940 goto out;
3941
3942 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3943 /*
3944 * If generic_perform_write() returned a synchronous error
3945 * then we want to return the number of bytes which were
3946 * direct-written, or the error code if that was zero. Note
3947 * that this differs from normal direct-io semantics, which
3948 * will return -EFOO even if some bytes were written.
3949 */
3950 if (unlikely(status < 0)) {
3951 err = status;
3952 goto out;
3953 }
3954 /*
3955 * We need to ensure that the page cache pages are written to
3956 * disk and invalidated to preserve the expected O_DIRECT
3957 * semantics.
3958 */
3959 endbyte = pos + status - 1;
3960 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3961 if (err == 0) {
3962 iocb->ki_pos = endbyte + 1;
3963 written += status;
3964 invalidate_mapping_pages(mapping,
3965 pos >> PAGE_SHIFT,
3966 endbyte >> PAGE_SHIFT);
3967 } else {
3968 /*
3969 * We don't know how much we wrote, so just return
3970 * the number of bytes which were direct-written
3971 */
3972 }
3973 } else {
3974 written = generic_perform_write(file, from, iocb->ki_pos);
3975 if (likely(written > 0))
3976 iocb->ki_pos += written;
3977 }
3978 out:
3979 current->backing_dev_info = NULL;
3980 return written ? written : err;
3981 }
3982 EXPORT_SYMBOL(__generic_file_write_iter);
3983
3984 /**
3985 * generic_file_write_iter - write data to a file
3986 * @iocb: IO state structure
3987 * @from: iov_iter with data to write
3988 *
3989 * This is a wrapper around __generic_file_write_iter() to be used by most
3990 * filesystems. It takes care of syncing the file in case of O_SYNC file
3991 * and acquires i_rwsem as needed.
3992 * Return:
3993 * * negative error code if no data has been written at all of
3994 * vfs_fsync_range() failed for a synchronous write
3995 * * number of bytes written, even for truncated writes
3996 */
generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)3997 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3998 {
3999 struct file *file = iocb->ki_filp;
4000 struct inode *inode = file->f_mapping->host;
4001 ssize_t ret;
4002
4003 inode_lock(inode);
4004 ret = generic_write_checks(iocb, from);
4005 if (ret > 0)
4006 ret = __generic_file_write_iter(iocb, from);
4007 inode_unlock(inode);
4008
4009 if (ret > 0)
4010 ret = generic_write_sync(iocb, ret);
4011 return ret;
4012 }
4013 EXPORT_SYMBOL(generic_file_write_iter);
4014
4015 /**
4016 * try_to_release_page() - release old fs-specific metadata on a page
4017 *
4018 * @page: the page which the kernel is trying to free
4019 * @gfp_mask: memory allocation flags (and I/O mode)
4020 *
4021 * The address_space is to try to release any data against the page
4022 * (presumably at page->private).
4023 *
4024 * This may also be called if PG_fscache is set on a page, indicating that the
4025 * page is known to the local caching routines.
4026 *
4027 * The @gfp_mask argument specifies whether I/O may be performed to release
4028 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
4029 *
4030 * Return: %1 if the release was successful, otherwise return zero.
4031 */
try_to_release_page(struct page * page,gfp_t gfp_mask)4032 int try_to_release_page(struct page *page, gfp_t gfp_mask)
4033 {
4034 struct address_space * const mapping = page->mapping;
4035
4036 BUG_ON(!PageLocked(page));
4037 if (PageWriteback(page))
4038 return 0;
4039
4040 if (mapping && mapping->a_ops->releasepage)
4041 return mapping->a_ops->releasepage(page, gfp_mask);
4042 return try_to_free_buffers(page);
4043 }
4044
4045 EXPORT_SYMBOL(try_to_release_page);
4046