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