• 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/swapops.h>
25 #include <linux/syscalls.h>
26 #include <linux/mman.h>
27 #include <linux/pagemap.h>
28 #include <linux/file.h>
29 #include <linux/uio.h>
30 #include <linux/error-injection.h>
31 #include <linux/hash.h>
32 #include <linux/writeback.h>
33 #include <linux/backing-dev.h>
34 #include <linux/pagevec.h>
35 #include <linux/security.h>
36 #include <linux/cpuset.h>
37 #include <linux/hugetlb.h>
38 #include <linux/memcontrol.h>
39 #include <linux/cleancache.h>
40 #include <linux/shmem_fs.h>
41 #include <linux/rmap.h>
42 #include <linux/delayacct.h>
43 #include <linux/psi.h>
44 #include <linux/ramfs.h>
45 #include <linux/page_idle.h>
46 #include <linux/page_size_compat.h>
47 #include <linux/migrate.h>
48 #include <linux/pipe_fs_i.h>
49 #include <linux/splice.h>
50 #include <linux/rcupdate_wait.h>
51 #include <linux/sched/mm.h>
52 #include <asm/pgalloc.h>
53 #include <asm/tlbflush.h>
54 #include "internal.h"
55 
56 #define CREATE_TRACE_POINTS
57 #include <trace/events/filemap.h>
58 
59 #undef CREATE_TRACE_POINTS
60 #include <trace/hooks/mm.h>
61 
62 /*
63  * FIXME: remove all knowledge of the buffer layer from the core VM
64  */
65 #include <linux/buffer_head.h> /* for try_to_free_buffers */
66 
67 #include <asm/mman.h>
68 
69 #include "swap.h"
70 
_trace_android_rvh_mapping_shrinkable(bool * shrinkable)71 void _trace_android_rvh_mapping_shrinkable(bool *shrinkable)
72 {
73 	trace_android_rvh_mapping_shrinkable(shrinkable);
74 }
75 EXPORT_SYMBOL_GPL(_trace_android_rvh_mapping_shrinkable);
76 
77 /*
78  * Shared mappings implemented 30.11.1994. It's not fully working yet,
79  * though.
80  *
81  * Shared mappings now work. 15.8.1995  Bruno.
82  *
83  * finished 'unifying' the page and buffer cache and SMP-threaded the
84  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
85  *
86  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
87  */
88 
89 /*
90  * Lock ordering:
91  *
92  *  ->i_mmap_rwsem		(truncate_pagecache)
93  *    ->private_lock		(__free_pte->block_dirty_folio)
94  *      ->swap_lock		(exclusive_swap_page, others)
95  *        ->i_pages lock
96  *
97  *  ->i_rwsem
98  *    ->invalidate_lock		(acquired by fs in truncate path)
99  *      ->i_mmap_rwsem		(truncate->unmap_mapping_range)
100  *
101  *  ->mmap_lock
102  *    ->i_mmap_rwsem
103  *      ->page_table_lock or pte_lock	(various, mainly in memory.c)
104  *        ->i_pages lock	(arch-dependent flush_dcache_mmap_lock)
105  *
106  *  ->mmap_lock
107  *    ->invalidate_lock		(filemap_fault)
108  *      ->lock_page		(filemap_fault, access_process_vm)
109  *
110  *  ->i_rwsem			(generic_perform_write)
111  *    ->mmap_lock		(fault_in_readable->do_page_fault)
112  *
113  *  bdi->wb.list_lock
114  *    sb_lock			(fs/fs-writeback.c)
115  *    ->i_pages lock		(__sync_single_inode)
116  *
117  *  ->i_mmap_rwsem
118  *    ->anon_vma.lock		(vma_merge)
119  *
120  *  ->anon_vma.lock
121  *    ->page_table_lock or pte_lock	(anon_vma_prepare and various)
122  *
123  *  ->page_table_lock or pte_lock
124  *    ->swap_lock		(try_to_unmap_one)
125  *    ->private_lock		(try_to_unmap_one)
126  *    ->i_pages lock		(try_to_unmap_one)
127  *    ->lruvec->lru_lock	(follow_page_mask->mark_page_accessed)
128  *    ->lruvec->lru_lock	(check_pte_range->folio_isolate_lru)
129  *    ->private_lock		(folio_remove_rmap_pte->set_page_dirty)
130  *    ->i_pages lock		(folio_remove_rmap_pte->set_page_dirty)
131  *    bdi.wb->list_lock		(folio_remove_rmap_pte->set_page_dirty)
132  *    ->inode->i_lock		(folio_remove_rmap_pte->set_page_dirty)
133  *    ->memcg->move_lock	(folio_remove_rmap_pte->folio_memcg_lock)
134  *    bdi.wb->list_lock		(zap_pte_range->set_page_dirty)
135  *    ->inode->i_lock		(zap_pte_range->set_page_dirty)
136  *    ->private_lock		(zap_pte_range->block_dirty_folio)
137  */
138 
139 /* Export tracepoints that act as a bare tracehook */
140 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_filemap_delete_from_page_cache);
141 EXPORT_TRACEPOINT_SYMBOL_GPL(mm_filemap_add_to_page_cache);
142 
mapping_set_update(struct xa_state * xas,struct address_space * mapping)143 static void mapping_set_update(struct xa_state *xas,
144 		struct address_space *mapping)
145 {
146 	if (dax_mapping(mapping) || shmem_mapping(mapping))
147 		return;
148 	xas_set_update(xas, workingset_update_node);
149 	xas_set_lru(xas, &shadow_nodes);
150 }
151 
page_cache_delete(struct address_space * mapping,struct folio * folio,void * shadow)152 static void page_cache_delete(struct address_space *mapping,
153 				   struct folio *folio, void *shadow)
154 {
155 	XA_STATE(xas, &mapping->i_pages, folio->index);
156 	long nr = 1;
157 
158 	mapping_set_update(&xas, mapping);
159 
160 	xas_set_order(&xas, folio->index, folio_order(folio));
161 	nr = folio_nr_pages(folio);
162 
163 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
164 
165 	xas_store(&xas, shadow);
166 	xas_init_marks(&xas);
167 
168 	folio->mapping = NULL;
169 	/* Leave page->index set: truncation lookup relies upon it */
170 	mapping->nrpages -= nr;
171 }
172 
filemap_unaccount_folio(struct address_space * mapping,struct folio * folio)173 static void filemap_unaccount_folio(struct address_space *mapping,
174 		struct folio *folio)
175 {
176 	long nr;
177 
178 	/*
179 	 * if we're uptodate, flush out into the cleancache, otherwise
180 	 * invalidate any existing cleancache entries.  We can't leave
181 	 * stale data around in the cleancache once our page is gone
182 	 */
183 	if (folio_test_uptodate(folio) && folio_test_mappedtodisk(folio))
184 		cleancache_put_page(&folio->page);
185 	else
186 		cleancache_invalidate_page(mapping, &folio->page);
187 
188 	VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
189 	if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
190 		pr_alert("BUG: Bad page cache in process %s  pfn:%05lx\n",
191 			 current->comm, folio_pfn(folio));
192 		dump_page(&folio->page, "still mapped when deleted");
193 		dump_stack();
194 		add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
195 
196 		if (mapping_exiting(mapping) && !folio_test_large(folio)) {
197 			int mapcount = folio_mapcount(folio);
198 
199 			if (folio_ref_count(folio) >= mapcount + 2) {
200 				/*
201 				 * All vmas have already been torn down, so it's
202 				 * a good bet that actually the page is unmapped
203 				 * and we'd rather not leak it: if we're wrong,
204 				 * another bad page check should catch it later.
205 				 */
206 				atomic_set(&folio->_mapcount, -1);
207 				folio_ref_sub(folio, mapcount);
208 			}
209 		}
210 	}
211 
212 	/* hugetlb folios do not participate in page cache accounting. */
213 	if (folio_test_hugetlb(folio))
214 		return;
215 
216 	nr = folio_nr_pages(folio);
217 
218 	__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
219 	if (folio_test_swapbacked(folio)) {
220 		__lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
221 		trace_android_vh_shmem_mod_shmem(folio->mapping, -nr);
222 		if (folio_test_pmd_mappable(folio))
223 			__lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr);
224 	} else if (folio_test_pmd_mappable(folio)) {
225 		__lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr);
226 		filemap_nr_thps_dec(mapping);
227 	}
228 
229 	/*
230 	 * At this point folio must be either written or cleaned by
231 	 * truncate.  Dirty folio here signals a bug and loss of
232 	 * unwritten data - on ordinary filesystems.
233 	 *
234 	 * But it's harmless on in-memory filesystems like tmpfs; and can
235 	 * occur when a driver which did get_user_pages() sets page dirty
236 	 * before putting it, while the inode is being finally evicted.
237 	 *
238 	 * Below fixes dirty accounting after removing the folio entirely
239 	 * but leaves the dirty flag set: it has no effect for truncated
240 	 * folio and anyway will be cleared before returning folio to
241 	 * buddy allocator.
242 	 */
243 	if (WARN_ON_ONCE(folio_test_dirty(folio) &&
244 			 mapping_can_writeback(mapping)))
245 		folio_account_cleaned(folio, inode_to_wb(mapping->host));
246 }
247 
248 /*
249  * Delete a page from the page cache and free it. Caller has to make
250  * sure the page is locked and that nobody else uses it - or that usage
251  * is safe.  The caller must hold the i_pages lock.
252  */
__filemap_remove_folio(struct folio * folio,void * shadow)253 void __filemap_remove_folio(struct folio *folio, void *shadow)
254 {
255 	struct address_space *mapping = folio->mapping;
256 
257 	trace_mm_filemap_delete_from_page_cache(folio);
258 	filemap_unaccount_folio(mapping, folio);
259 	page_cache_delete(mapping, folio, shadow);
260 }
261 
filemap_free_folio(struct address_space * mapping,struct folio * folio)262 void filemap_free_folio(struct address_space *mapping, struct folio *folio)
263 {
264 	void (*free_folio)(struct folio *);
265 	int refs = 1;
266 
267 	free_folio = mapping->a_ops->free_folio;
268 	if (free_folio)
269 		free_folio(folio);
270 
271 	if (folio_test_large(folio))
272 		refs = folio_nr_pages(folio);
273 	folio_put_refs(folio, refs);
274 }
275 
276 /**
277  * filemap_remove_folio - Remove folio from page cache.
278  * @folio: The folio.
279  *
280  * This must be called only on folios that are locked and have been
281  * verified to be in the page cache.  It will never put the folio into
282  * the free list because the caller has a reference on the page.
283  */
filemap_remove_folio(struct folio * folio)284 void filemap_remove_folio(struct folio *folio)
285 {
286 	struct address_space *mapping = folio->mapping;
287 
288 	BUG_ON(!folio_test_locked(folio));
289 	spin_lock(&mapping->host->i_lock);
290 	xa_lock_irq(&mapping->i_pages);
291 	__filemap_remove_folio(folio, NULL);
292 	xa_unlock_irq(&mapping->i_pages);
293 	if (mapping_shrinkable(mapping))
294 		inode_add_lru(mapping->host);
295 	spin_unlock(&mapping->host->i_lock);
296 
297 	filemap_free_folio(mapping, folio);
298 }
299 
300 /*
301  * page_cache_delete_batch - delete several folios from page cache
302  * @mapping: the mapping to which folios belong
303  * @fbatch: batch of folios to delete
304  *
305  * The function walks over mapping->i_pages and removes folios passed in
306  * @fbatch from the mapping. The function expects @fbatch to be sorted
307  * by page index and is optimised for it to be dense.
308  * It tolerates holes in @fbatch (mapping entries at those indices are not
309  * modified).
310  *
311  * The function expects the i_pages lock to be held.
312  */
page_cache_delete_batch(struct address_space * mapping,struct folio_batch * fbatch)313 static void page_cache_delete_batch(struct address_space *mapping,
314 			     struct folio_batch *fbatch)
315 {
316 	XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
317 	long total_pages = 0;
318 	int i = 0;
319 	struct folio *folio;
320 
321 	mapping_set_update(&xas, mapping);
322 	xas_for_each(&xas, folio, ULONG_MAX) {
323 		if (i >= folio_batch_count(fbatch))
324 			break;
325 
326 		/* A swap/dax/shadow entry got inserted? Skip it. */
327 		if (xa_is_value(folio))
328 			continue;
329 		/*
330 		 * A page got inserted in our range? Skip it. We have our
331 		 * pages locked so they are protected from being removed.
332 		 * If we see a page whose index is higher than ours, it
333 		 * means our page has been removed, which shouldn't be
334 		 * possible because we're holding the PageLock.
335 		 */
336 		if (folio != fbatch->folios[i]) {
337 			VM_BUG_ON_FOLIO(folio->index >
338 					fbatch->folios[i]->index, folio);
339 			continue;
340 		}
341 
342 		WARN_ON_ONCE(!folio_test_locked(folio));
343 
344 		folio->mapping = NULL;
345 		/* Leave folio->index set: truncation lookup relies on it */
346 
347 		i++;
348 		xas_store(&xas, NULL);
349 		total_pages += folio_nr_pages(folio);
350 	}
351 	mapping->nrpages -= total_pages;
352 }
353 
delete_from_page_cache_batch(struct address_space * mapping,struct folio_batch * fbatch)354 void delete_from_page_cache_batch(struct address_space *mapping,
355 				  struct folio_batch *fbatch)
356 {
357 	int i;
358 
359 	if (!folio_batch_count(fbatch))
360 		return;
361 
362 	spin_lock(&mapping->host->i_lock);
363 	xa_lock_irq(&mapping->i_pages);
364 	for (i = 0; i < folio_batch_count(fbatch); i++) {
365 		struct folio *folio = fbatch->folios[i];
366 
367 		trace_mm_filemap_delete_from_page_cache(folio);
368 		filemap_unaccount_folio(mapping, folio);
369 	}
370 	page_cache_delete_batch(mapping, fbatch);
371 	xa_unlock_irq(&mapping->i_pages);
372 	if (mapping_shrinkable(mapping))
373 		inode_add_lru(mapping->host);
374 	spin_unlock(&mapping->host->i_lock);
375 
376 	for (i = 0; i < folio_batch_count(fbatch); i++)
377 		filemap_free_folio(mapping, fbatch->folios[i]);
378 }
379 
filemap_check_errors(struct address_space * mapping)380 int filemap_check_errors(struct address_space *mapping)
381 {
382 	int ret = 0;
383 	/* Check for outstanding write errors */
384 	if (test_bit(AS_ENOSPC, &mapping->flags) &&
385 	    test_and_clear_bit(AS_ENOSPC, &mapping->flags))
386 		ret = -ENOSPC;
387 	if (test_bit(AS_EIO, &mapping->flags) &&
388 	    test_and_clear_bit(AS_EIO, &mapping->flags))
389 		ret = -EIO;
390 	return ret;
391 }
392 EXPORT_SYMBOL(filemap_check_errors);
393 
filemap_check_and_keep_errors(struct address_space * mapping)394 static int filemap_check_and_keep_errors(struct address_space *mapping)
395 {
396 	/* Check for outstanding write errors */
397 	if (test_bit(AS_EIO, &mapping->flags))
398 		return -EIO;
399 	if (test_bit(AS_ENOSPC, &mapping->flags))
400 		return -ENOSPC;
401 	return 0;
402 }
403 
404 /**
405  * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
406  * @mapping:	address space structure to write
407  * @wbc:	the writeback_control controlling the writeout
408  *
409  * Call writepages on the mapping using the provided wbc to control the
410  * writeout.
411  *
412  * Return: %0 on success, negative error code otherwise.
413  */
filemap_fdatawrite_wbc(struct address_space * mapping,struct writeback_control * wbc)414 int filemap_fdatawrite_wbc(struct address_space *mapping,
415 			   struct writeback_control *wbc)
416 {
417 	int ret;
418 
419 	if (!mapping_can_writeback(mapping) ||
420 	    !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
421 		return 0;
422 
423 	wbc_attach_fdatawrite_inode(wbc, mapping->host);
424 	ret = do_writepages(mapping, wbc);
425 	wbc_detach_inode(wbc);
426 	return ret;
427 }
428 EXPORT_SYMBOL(filemap_fdatawrite_wbc);
429 
430 /**
431  * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
432  * @mapping:	address space structure to write
433  * @start:	offset in bytes where the range starts
434  * @end:	offset in bytes where the range ends (inclusive)
435  * @sync_mode:	enable synchronous operation
436  *
437  * Start writeback against all of a mapping's dirty pages that lie
438  * within the byte offsets <start, end> inclusive.
439  *
440  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
441  * opposed to a regular memory cleansing writeback.  The difference between
442  * these two operations is that if a dirty page/buffer is encountered, it must
443  * be waited upon, and not just skipped over.
444  *
445  * Return: %0 on success, negative error code otherwise.
446  */
__filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end,int sync_mode)447 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
448 				loff_t end, int sync_mode)
449 {
450 	struct writeback_control wbc = {
451 		.sync_mode = sync_mode,
452 		.nr_to_write = LONG_MAX,
453 		.range_start = start,
454 		.range_end = end,
455 	};
456 
457 	return filemap_fdatawrite_wbc(mapping, &wbc);
458 }
459 
__filemap_fdatawrite(struct address_space * mapping,int sync_mode)460 static inline int __filemap_fdatawrite(struct address_space *mapping,
461 	int sync_mode)
462 {
463 	return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
464 }
465 
filemap_fdatawrite(struct address_space * mapping)466 int filemap_fdatawrite(struct address_space *mapping)
467 {
468 	return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
469 }
470 EXPORT_SYMBOL(filemap_fdatawrite);
471 
filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end)472 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
473 				loff_t end)
474 {
475 	return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
476 }
477 EXPORT_SYMBOL(filemap_fdatawrite_range);
478 
479 /**
480  * filemap_fdatawrite_range_kick - start writeback on a range
481  * @mapping:	target address_space
482  * @start:	index to start writeback on
483  * @end:	last (inclusive) index for writeback
484  *
485  * This is a non-integrity writeback helper, to start writing back folios
486  * for the indicated range.
487  *
488  * Return: %0 on success, negative error code otherwise.
489  */
filemap_fdatawrite_range_kick(struct address_space * mapping,loff_t start,loff_t end)490 int filemap_fdatawrite_range_kick(struct address_space *mapping, loff_t start,
491 				  loff_t end)
492 {
493 	return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_NONE);
494 }
495 EXPORT_SYMBOL_GPL(filemap_fdatawrite_range_kick);
496 
497 /**
498  * filemap_flush - mostly a non-blocking flush
499  * @mapping:	target address_space
500  *
501  * This is a mostly non-blocking flush.  Not suitable for data-integrity
502  * purposes - I/O may not be started against all dirty pages.
503  *
504  * Return: %0 on success, negative error code otherwise.
505  */
filemap_flush(struct address_space * mapping)506 int filemap_flush(struct address_space *mapping)
507 {
508 	return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
509 }
510 EXPORT_SYMBOL(filemap_flush);
511 
512 /**
513  * filemap_range_has_page - check if a page exists in range.
514  * @mapping:           address space within which to check
515  * @start_byte:        offset in bytes where the range starts
516  * @end_byte:          offset in bytes where the range ends (inclusive)
517  *
518  * Find at least one page in the range supplied, usually used to check if
519  * direct writing in this range will trigger a writeback.
520  *
521  * Return: %true if at least one page exists in the specified range,
522  * %false otherwise.
523  */
filemap_range_has_page(struct address_space * mapping,loff_t start_byte,loff_t end_byte)524 bool filemap_range_has_page(struct address_space *mapping,
525 			   loff_t start_byte, loff_t end_byte)
526 {
527 	struct folio *folio;
528 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
529 	pgoff_t max = end_byte >> PAGE_SHIFT;
530 
531 	if (end_byte < start_byte)
532 		return false;
533 
534 	rcu_read_lock();
535 	for (;;) {
536 		folio = xas_find(&xas, max);
537 		if (xas_retry(&xas, folio))
538 			continue;
539 		/* Shadow entries don't count */
540 		if (xa_is_value(folio))
541 			continue;
542 		/*
543 		 * We don't need to try to pin this page; we're about to
544 		 * release the RCU lock anyway.  It is enough to know that
545 		 * there was a page here recently.
546 		 */
547 		break;
548 	}
549 	rcu_read_unlock();
550 
551 	return folio != NULL;
552 }
553 EXPORT_SYMBOL(filemap_range_has_page);
554 
__filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)555 static void __filemap_fdatawait_range(struct address_space *mapping,
556 				     loff_t start_byte, loff_t end_byte)
557 {
558 	pgoff_t index = start_byte >> PAGE_SHIFT;
559 	pgoff_t end = end_byte >> PAGE_SHIFT;
560 	struct folio_batch fbatch;
561 	unsigned nr_folios;
562 
563 	folio_batch_init(&fbatch);
564 
565 	while (index <= end) {
566 		unsigned i;
567 
568 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
569 				PAGECACHE_TAG_WRITEBACK, &fbatch);
570 
571 		if (!nr_folios)
572 			break;
573 
574 		for (i = 0; i < nr_folios; i++) {
575 			struct folio *folio = fbatch.folios[i];
576 
577 			folio_wait_writeback(folio);
578 		}
579 		folio_batch_release(&fbatch);
580 		cond_resched();
581 	}
582 }
583 
584 /**
585  * filemap_fdatawait_range - wait for writeback to complete
586  * @mapping:		address space structure to wait for
587  * @start_byte:		offset in bytes where the range starts
588  * @end_byte:		offset in bytes where the range ends (inclusive)
589  *
590  * Walk the list of under-writeback pages of the given address space
591  * in the given range and wait for all of them.  Check error status of
592  * the address space and return it.
593  *
594  * Since the error status of the address space is cleared by this function,
595  * callers are responsible for checking the return value and handling and/or
596  * reporting the error.
597  *
598  * Return: error status of the address space.
599  */
filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)600 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
601 			    loff_t end_byte)
602 {
603 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
604 	return filemap_check_errors(mapping);
605 }
606 EXPORT_SYMBOL(filemap_fdatawait_range);
607 
608 /**
609  * filemap_fdatawait_range_keep_errors - wait for writeback to complete
610  * @mapping:		address space structure to wait for
611  * @start_byte:		offset in bytes where the range starts
612  * @end_byte:		offset in bytes where the range ends (inclusive)
613  *
614  * Walk the list of under-writeback pages of the given address space in the
615  * given range and wait for all of them.  Unlike filemap_fdatawait_range(),
616  * this function does not clear error status of the address space.
617  *
618  * Use this function if callers don't handle errors themselves.  Expected
619  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
620  * fsfreeze(8)
621  */
filemap_fdatawait_range_keep_errors(struct address_space * mapping,loff_t start_byte,loff_t end_byte)622 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
623 		loff_t start_byte, loff_t end_byte)
624 {
625 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
626 	return filemap_check_and_keep_errors(mapping);
627 }
628 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
629 
630 /**
631  * file_fdatawait_range - wait for writeback to complete
632  * @file:		file pointing to address space structure to wait for
633  * @start_byte:		offset in bytes where the range starts
634  * @end_byte:		offset in bytes where the range ends (inclusive)
635  *
636  * Walk the list of under-writeback pages of the address space that file
637  * refers to, in the given range and wait for all of them.  Check error
638  * status of the address space vs. the file->f_wb_err cursor and return it.
639  *
640  * Since the error status of the file is advanced by this function,
641  * callers are responsible for checking the return value and handling and/or
642  * reporting the error.
643  *
644  * Return: error status of the address space vs. the file->f_wb_err cursor.
645  */
file_fdatawait_range(struct file * file,loff_t start_byte,loff_t end_byte)646 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
647 {
648 	struct address_space *mapping = file->f_mapping;
649 
650 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
651 	return file_check_and_advance_wb_err(file);
652 }
653 EXPORT_SYMBOL(file_fdatawait_range);
654 
655 /**
656  * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
657  * @mapping: address space structure to wait for
658  *
659  * Walk the list of under-writeback pages of the given address space
660  * and wait for all of them.  Unlike filemap_fdatawait(), this function
661  * does not clear error status of the address space.
662  *
663  * Use this function if callers don't handle errors themselves.  Expected
664  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
665  * fsfreeze(8)
666  *
667  * Return: error status of the address space.
668  */
filemap_fdatawait_keep_errors(struct address_space * mapping)669 int filemap_fdatawait_keep_errors(struct address_space *mapping)
670 {
671 	__filemap_fdatawait_range(mapping, 0, LLONG_MAX);
672 	return filemap_check_and_keep_errors(mapping);
673 }
674 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
675 
676 /* Returns true if writeback might be needed or already in progress. */
mapping_needs_writeback(struct address_space * mapping)677 static bool mapping_needs_writeback(struct address_space *mapping)
678 {
679 	return mapping->nrpages;
680 }
681 
filemap_range_has_writeback(struct address_space * mapping,loff_t start_byte,loff_t end_byte)682 bool filemap_range_has_writeback(struct address_space *mapping,
683 				 loff_t start_byte, loff_t end_byte)
684 {
685 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
686 	pgoff_t max = end_byte >> PAGE_SHIFT;
687 	struct folio *folio;
688 
689 	if (end_byte < start_byte)
690 		return false;
691 
692 	rcu_read_lock();
693 	xas_for_each(&xas, folio, max) {
694 		if (xas_retry(&xas, folio))
695 			continue;
696 		if (xa_is_value(folio))
697 			continue;
698 		if (folio_test_dirty(folio) || folio_test_locked(folio) ||
699 				folio_test_writeback(folio))
700 			break;
701 	}
702 	rcu_read_unlock();
703 	return folio != NULL;
704 }
705 EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
706 
707 /**
708  * filemap_write_and_wait_range - write out & wait on a file range
709  * @mapping:	the address_space for the pages
710  * @lstart:	offset in bytes where the range starts
711  * @lend:	offset in bytes where the range ends (inclusive)
712  *
713  * Write out and wait upon file offsets lstart->lend, inclusive.
714  *
715  * Note that @lend is inclusive (describes the last byte to be written) so
716  * that this function can be used to write to the very end-of-file (end = -1).
717  *
718  * Return: error status of the address space.
719  */
filemap_write_and_wait_range(struct address_space * mapping,loff_t lstart,loff_t lend)720 int filemap_write_and_wait_range(struct address_space *mapping,
721 				 loff_t lstart, loff_t lend)
722 {
723 	int err = 0, err2;
724 
725 	if (lend < lstart)
726 		return 0;
727 
728 	if (mapping_needs_writeback(mapping)) {
729 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
730 						 WB_SYNC_ALL);
731 		/*
732 		 * Even if the above returned error, the pages may be
733 		 * written partially (e.g. -ENOSPC), so we wait for it.
734 		 * But the -EIO is special case, it may indicate the worst
735 		 * thing (e.g. bug) happened, so we avoid waiting for it.
736 		 */
737 		if (err != -EIO)
738 			__filemap_fdatawait_range(mapping, lstart, lend);
739 	}
740 	err2 = filemap_check_errors(mapping);
741 	if (!err)
742 		err = err2;
743 	return err;
744 }
745 EXPORT_SYMBOL(filemap_write_and_wait_range);
746 
__filemap_set_wb_err(struct address_space * mapping,int err)747 void __filemap_set_wb_err(struct address_space *mapping, int err)
748 {
749 	errseq_t eseq = errseq_set(&mapping->wb_err, err);
750 
751 	trace_filemap_set_wb_err(mapping, eseq);
752 }
753 EXPORT_SYMBOL(__filemap_set_wb_err);
754 
755 /**
756  * file_check_and_advance_wb_err - report wb error (if any) that was previously
757  * 				   and advance wb_err to current one
758  * @file: struct file on which the error is being reported
759  *
760  * When userland calls fsync (or something like nfsd does the equivalent), we
761  * want to report any writeback errors that occurred since the last fsync (or
762  * since the file was opened if there haven't been any).
763  *
764  * Grab the wb_err from the mapping. If it matches what we have in the file,
765  * then just quickly return 0. The file is all caught up.
766  *
767  * If it doesn't match, then take the mapping value, set the "seen" flag in
768  * it and try to swap it into place. If it works, or another task beat us
769  * to it with the new value, then update the f_wb_err and return the error
770  * portion. The error at this point must be reported via proper channels
771  * (a'la fsync, or NFS COMMIT operation, etc.).
772  *
773  * While we handle mapping->wb_err with atomic operations, the f_wb_err
774  * value is protected by the f_lock since we must ensure that it reflects
775  * the latest value swapped in for this file descriptor.
776  *
777  * Return: %0 on success, negative error code otherwise.
778  */
file_check_and_advance_wb_err(struct file * file)779 int file_check_and_advance_wb_err(struct file *file)
780 {
781 	int err = 0;
782 	errseq_t old = READ_ONCE(file->f_wb_err);
783 	struct address_space *mapping = file->f_mapping;
784 
785 	/* Locklessly handle the common case where nothing has changed */
786 	if (errseq_check(&mapping->wb_err, old)) {
787 		/* Something changed, must use slow path */
788 		spin_lock(&file->f_lock);
789 		old = file->f_wb_err;
790 		err = errseq_check_and_advance(&mapping->wb_err,
791 						&file->f_wb_err);
792 		trace_file_check_and_advance_wb_err(file, old);
793 		spin_unlock(&file->f_lock);
794 	}
795 
796 	/*
797 	 * We're mostly using this function as a drop in replacement for
798 	 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
799 	 * that the legacy code would have had on these flags.
800 	 */
801 	clear_bit(AS_EIO, &mapping->flags);
802 	clear_bit(AS_ENOSPC, &mapping->flags);
803 	return err;
804 }
805 EXPORT_SYMBOL(file_check_and_advance_wb_err);
806 
807 /**
808  * file_write_and_wait_range - write out & wait on a file range
809  * @file:	file pointing to address_space with pages
810  * @lstart:	offset in bytes where the range starts
811  * @lend:	offset in bytes where the range ends (inclusive)
812  *
813  * Write out and wait upon file offsets lstart->lend, inclusive.
814  *
815  * Note that @lend is inclusive (describes the last byte to be written) so
816  * that this function can be used to write to the very end-of-file (end = -1).
817  *
818  * After writing out and waiting on the data, we check and advance the
819  * f_wb_err cursor to the latest value, and return any errors detected there.
820  *
821  * Return: %0 on success, negative error code otherwise.
822  */
file_write_and_wait_range(struct file * file,loff_t lstart,loff_t lend)823 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
824 {
825 	int err = 0, err2;
826 	struct address_space *mapping = file->f_mapping;
827 
828 	if (lend < lstart)
829 		return 0;
830 
831 	if (mapping_needs_writeback(mapping)) {
832 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
833 						 WB_SYNC_ALL);
834 		/* See comment of filemap_write_and_wait() */
835 		if (err != -EIO)
836 			__filemap_fdatawait_range(mapping, lstart, lend);
837 	}
838 	err2 = file_check_and_advance_wb_err(file);
839 	if (!err)
840 		err = err2;
841 	return err;
842 }
843 EXPORT_SYMBOL(file_write_and_wait_range);
844 
845 /**
846  * replace_page_cache_folio - replace a pagecache folio with a new one
847  * @old:	folio to be replaced
848  * @new:	folio to replace with
849  *
850  * This function replaces a folio in the pagecache with a new one.  On
851  * success it acquires the pagecache reference for the new folio and
852  * drops it for the old folio.  Both the old and new folios must be
853  * locked.  This function does not add the new folio to the LRU, the
854  * caller must do that.
855  *
856  * The remove + add is atomic.  This function cannot fail.
857  */
replace_page_cache_folio(struct folio * old,struct folio * new)858 void replace_page_cache_folio(struct folio *old, struct folio *new)
859 {
860 	struct address_space *mapping = old->mapping;
861 	void (*free_folio)(struct folio *) = mapping->a_ops->free_folio;
862 	pgoff_t offset = old->index;
863 	XA_STATE(xas, &mapping->i_pages, offset);
864 
865 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
866 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
867 	VM_BUG_ON_FOLIO(new->mapping, new);
868 
869 	folio_get(new);
870 	new->mapping = mapping;
871 	new->index = offset;
872 
873 	mem_cgroup_replace_folio(old, new);
874 
875 	xas_lock_irq(&xas);
876 	xas_store(&xas, new);
877 
878 	old->mapping = NULL;
879 	/* hugetlb pages do not participate in page cache accounting. */
880 	if (!folio_test_hugetlb(old))
881 		__lruvec_stat_sub_folio(old, NR_FILE_PAGES);
882 	if (!folio_test_hugetlb(new))
883 		__lruvec_stat_add_folio(new, NR_FILE_PAGES);
884 	if (folio_test_swapbacked(old))
885 		__lruvec_stat_sub_folio(old, NR_SHMEM);
886 	if (folio_test_swapbacked(new))
887 		__lruvec_stat_add_folio(new, NR_SHMEM);
888 	xas_unlock_irq(&xas);
889 	if (free_folio)
890 		free_folio(old);
891 	folio_put(old);
892 }
893 EXPORT_SYMBOL_GPL(replace_page_cache_folio);
894 
__filemap_add_folio(struct address_space * mapping,struct folio * folio,pgoff_t index,gfp_t gfp,void ** shadowp)895 noinline int __filemap_add_folio(struct address_space *mapping,
896 		struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
897 {
898 	XA_STATE(xas, &mapping->i_pages, index);
899 	void *alloced_shadow = NULL;
900 	int alloced_order = 0;
901 	bool huge;
902 	long nr;
903 
904 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
905 	VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
906 	VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping),
907 			folio);
908 	mapping_set_update(&xas, mapping);
909 
910 	VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
911 	xas_set_order(&xas, index, folio_order(folio));
912 	huge = folio_test_hugetlb(folio);
913 	nr = folio_nr_pages(folio);
914 
915 	gfp &= GFP_RECLAIM_MASK;
916 	folio_ref_add(folio, nr);
917 	folio->mapping = mapping;
918 	folio->index = xas.xa_index;
919 
920 	for (;;) {
921 		int order = -1, split_order = 0;
922 		void *entry, *old = NULL;
923 
924 		xas_lock_irq(&xas);
925 		xas_for_each_conflict(&xas, entry) {
926 			old = entry;
927 			if (!xa_is_value(entry)) {
928 				xas_set_err(&xas, -EEXIST);
929 				goto unlock;
930 			}
931 			/*
932 			 * If a larger entry exists,
933 			 * it will be the first and only entry iterated.
934 			 */
935 			if (order == -1)
936 				order = xas_get_order(&xas);
937 		}
938 
939 		/* entry may have changed before we re-acquire the lock */
940 		if (alloced_order && (old != alloced_shadow || order != alloced_order)) {
941 			xas_destroy(&xas);
942 			alloced_order = 0;
943 		}
944 
945 		if (old) {
946 			if (order > 0 && order > folio_order(folio)) {
947 				/* How to handle large swap entries? */
948 				BUG_ON(shmem_mapping(mapping));
949 				if (!alloced_order) {
950 					split_order = order;
951 					goto unlock;
952 				}
953 				xas_split(&xas, old, order);
954 				xas_reset(&xas);
955 			}
956 			if (shadowp)
957 				*shadowp = old;
958 		}
959 
960 		xas_store(&xas, folio);
961 		if (xas_error(&xas))
962 			goto unlock;
963 
964 		mapping->nrpages += nr;
965 
966 		/* hugetlb pages do not participate in page cache accounting */
967 		if (!huge) {
968 			__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
969 			if (folio_test_pmd_mappable(folio))
970 				__lruvec_stat_mod_folio(folio,
971 						NR_FILE_THPS, nr);
972 		}
973 
974 unlock:
975 		xas_unlock_irq(&xas);
976 
977 		/* split needed, alloc here and retry. */
978 		if (split_order) {
979 			xas_split_alloc(&xas, old, split_order, gfp);
980 			if (xas_error(&xas))
981 				goto error;
982 			alloced_shadow = old;
983 			alloced_order = split_order;
984 			xas_reset(&xas);
985 			continue;
986 		}
987 
988 		if (!xas_nomem(&xas, gfp))
989 			break;
990 	}
991 
992 	if (xas_error(&xas))
993 		goto error;
994 
995 	trace_mm_filemap_add_to_page_cache(folio);
996 	return 0;
997 error:
998 	folio->mapping = NULL;
999 	/* Leave page->index set: truncation relies upon it */
1000 	folio_put_refs(folio, nr);
1001 	return xas_error(&xas);
1002 }
1003 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
1004 
filemap_add_folio(struct address_space * mapping,struct folio * folio,pgoff_t index,gfp_t gfp)1005 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
1006 				pgoff_t index, gfp_t gfp)
1007 {
1008 	void *shadow = NULL;
1009 	int ret;
1010 
1011 	trace_android_vh_filemap_add_folio(mapping, folio, index);
1012 	ret = mem_cgroup_charge(folio, NULL, gfp);
1013 	if (ret)
1014 		return ret;
1015 
1016 	__folio_set_locked(folio);
1017 	ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
1018 	if (unlikely(ret)) {
1019 		mem_cgroup_uncharge(folio);
1020 		__folio_clear_locked(folio);
1021 	} else {
1022 		/*
1023 		 * The folio might have been evicted from cache only
1024 		 * recently, in which case it should be activated like
1025 		 * any other repeatedly accessed folio.
1026 		 * The exception is folios getting rewritten; evicting other
1027 		 * data from the working set, only to cache data that will
1028 		 * get overwritten with something else, is a waste of memory.
1029 		 */
1030 		WARN_ON_ONCE(folio_test_active(folio));
1031 		if (!(gfp & __GFP_WRITE) && shadow)
1032 			workingset_refault(folio, shadow);
1033 		folio_add_lru(folio);
1034 	}
1035 	return ret;
1036 }
1037 EXPORT_SYMBOL_GPL(filemap_add_folio);
1038 
1039 #ifdef CONFIG_NUMA
filemap_alloc_folio_noprof(gfp_t gfp,unsigned int order)1040 struct folio *filemap_alloc_folio_noprof(gfp_t gfp, unsigned int order)
1041 {
1042 	int n;
1043 	struct folio *folio;
1044 
1045 	if (cpuset_do_page_mem_spread()) {
1046 		unsigned int cpuset_mems_cookie;
1047 		do {
1048 			cpuset_mems_cookie = read_mems_allowed_begin();
1049 			n = cpuset_mem_spread_node();
1050 			folio = __folio_alloc_node_noprof(gfp, order, n);
1051 		} while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
1052 
1053 		return folio;
1054 	}
1055 	return folio_alloc_noprof(gfp, order);
1056 }
1057 EXPORT_SYMBOL(filemap_alloc_folio_noprof);
1058 #endif
1059 
1060 /*
1061  * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
1062  *
1063  * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
1064  *
1065  * @mapping1: the first mapping to lock
1066  * @mapping2: the second mapping to lock
1067  */
filemap_invalidate_lock_two(struct address_space * mapping1,struct address_space * mapping2)1068 void filemap_invalidate_lock_two(struct address_space *mapping1,
1069 				 struct address_space *mapping2)
1070 {
1071 	if (mapping1 > mapping2)
1072 		swap(mapping1, mapping2);
1073 	if (mapping1)
1074 		down_write(&mapping1->invalidate_lock);
1075 	if (mapping2 && mapping1 != mapping2)
1076 		down_write_nested(&mapping2->invalidate_lock, 1);
1077 }
1078 EXPORT_SYMBOL(filemap_invalidate_lock_two);
1079 
1080 /*
1081  * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
1082  *
1083  * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
1084  *
1085  * @mapping1: the first mapping to unlock
1086  * @mapping2: the second mapping to unlock
1087  */
filemap_invalidate_unlock_two(struct address_space * mapping1,struct address_space * mapping2)1088 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1089 				   struct address_space *mapping2)
1090 {
1091 	if (mapping1)
1092 		up_write(&mapping1->invalidate_lock);
1093 	if (mapping2 && mapping1 != mapping2)
1094 		up_write(&mapping2->invalidate_lock);
1095 }
1096 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1097 
1098 /*
1099  * In order to wait for pages to become available there must be
1100  * waitqueues associated with pages. By using a hash table of
1101  * waitqueues where the bucket discipline is to maintain all
1102  * waiters on the same queue and wake all when any of the pages
1103  * become available, and for the woken contexts to check to be
1104  * sure the appropriate page became available, this saves space
1105  * at a cost of "thundering herd" phenomena during rare hash
1106  * collisions.
1107  */
1108 #define PAGE_WAIT_TABLE_BITS 8
1109 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1110 static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1111 
folio_waitqueue(struct folio * folio)1112 static wait_queue_head_t *folio_waitqueue(struct folio *folio)
1113 {
1114 	return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
1115 }
1116 
pagecache_init(void)1117 void __init pagecache_init(void)
1118 {
1119 	int i;
1120 
1121 	for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1122 		init_waitqueue_head(&folio_wait_table[i]);
1123 
1124 	page_writeback_init();
1125 }
1126 
1127 /*
1128  * The page wait code treats the "wait->flags" somewhat unusually, because
1129  * we have multiple different kinds of waits, not just the usual "exclusive"
1130  * one.
1131  *
1132  * We have:
1133  *
1134  *  (a) no special bits set:
1135  *
1136  *	We're just waiting for the bit to be released, and when a waker
1137  *	calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1138  *	and remove it from the wait queue.
1139  *
1140  *	Simple and straightforward.
1141  *
1142  *  (b) WQ_FLAG_EXCLUSIVE:
1143  *
1144  *	The waiter is waiting to get the lock, and only one waiter should
1145  *	be woken up to avoid any thundering herd behavior. We'll set the
1146  *	WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1147  *
1148  *	This is the traditional exclusive wait.
1149  *
1150  *  (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1151  *
1152  *	The waiter is waiting to get the bit, and additionally wants the
1153  *	lock to be transferred to it for fair lock behavior. If the lock
1154  *	cannot be taken, we stop walking the wait queue without waking
1155  *	the waiter.
1156  *
1157  *	This is the "fair lock handoff" case, and in addition to setting
1158  *	WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1159  *	that it now has the lock.
1160  */
wake_page_function(wait_queue_entry_t * wait,unsigned mode,int sync,void * arg)1161 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1162 {
1163 	unsigned int flags;
1164 	struct wait_page_key *key = arg;
1165 	struct wait_page_queue *wait_page
1166 		= container_of(wait, struct wait_page_queue, wait);
1167 
1168 	if (!wake_page_match(wait_page, key))
1169 		return 0;
1170 
1171 	/*
1172 	 * If it's a lock handoff wait, we get the bit for it, and
1173 	 * stop walking (and do not wake it up) if we can't.
1174 	 */
1175 	flags = wait->flags;
1176 	if (flags & WQ_FLAG_EXCLUSIVE) {
1177 		if (test_bit(key->bit_nr, &key->folio->flags))
1178 			return -1;
1179 		if (flags & WQ_FLAG_CUSTOM) {
1180 			if (test_and_set_bit(key->bit_nr, &key->folio->flags))
1181 				return -1;
1182 			flags |= WQ_FLAG_DONE;
1183 		}
1184 	}
1185 
1186 	/*
1187 	 * We are holding the wait-queue lock, but the waiter that
1188 	 * is waiting for this will be checking the flags without
1189 	 * any locking.
1190 	 *
1191 	 * So update the flags atomically, and wake up the waiter
1192 	 * afterwards to avoid any races. This store-release pairs
1193 	 * with the load-acquire in folio_wait_bit_common().
1194 	 */
1195 	smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1196 	wake_up_state(wait->private, mode);
1197 
1198 	/*
1199 	 * Ok, we have successfully done what we're waiting for,
1200 	 * and we can unconditionally remove the wait entry.
1201 	 *
1202 	 * Note that this pairs with the "finish_wait()" in the
1203 	 * waiter, and has to be the absolute last thing we do.
1204 	 * After this list_del_init(&wait->entry) the wait entry
1205 	 * might be de-allocated and the process might even have
1206 	 * exited.
1207 	 */
1208 	list_del_init_careful(&wait->entry);
1209 	return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1210 }
1211 
folio_wake_bit(struct folio * folio,int bit_nr)1212 static void folio_wake_bit(struct folio *folio, int bit_nr)
1213 {
1214 	wait_queue_head_t *q = folio_waitqueue(folio);
1215 	struct wait_page_key key;
1216 	unsigned long flags;
1217 
1218 	key.folio = folio;
1219 	key.bit_nr = bit_nr;
1220 	key.page_match = 0;
1221 
1222 	spin_lock_irqsave(&q->lock, flags);
1223 	__wake_up_locked_key(q, TASK_NORMAL, &key);
1224 
1225 	/*
1226 	 * It's possible to miss clearing waiters here, when we woke our page
1227 	 * waiters, but the hashed waitqueue has waiters for other pages on it.
1228 	 * That's okay, it's a rare case. The next waker will clear it.
1229 	 *
1230 	 * Note that, depending on the page pool (buddy, hugetlb, ZONE_DEVICE,
1231 	 * other), the flag may be cleared in the course of freeing the page;
1232 	 * but that is not required for correctness.
1233 	 */
1234 	if (!waitqueue_active(q) || !key.page_match)
1235 		folio_clear_waiters(folio);
1236 
1237 	spin_unlock_irqrestore(&q->lock, flags);
1238 }
1239 
1240 /*
1241  * A choice of three behaviors for folio_wait_bit_common():
1242  */
1243 enum behavior {
1244 	EXCLUSIVE,	/* Hold ref to page and take the bit when woken, like
1245 			 * __folio_lock() waiting on then setting PG_locked.
1246 			 */
1247 	SHARED,		/* Hold ref to page and check the bit when woken, like
1248 			 * folio_wait_writeback() waiting on PG_writeback.
1249 			 */
1250 	DROP,		/* Drop ref to page before wait, no check when woken,
1251 			 * like folio_put_wait_locked() on PG_locked.
1252 			 */
1253 };
1254 
1255 /*
1256  * Attempt to check (or get) the folio flag, and mark us done
1257  * if successful.
1258  */
folio_trylock_flag(struct folio * folio,int bit_nr,struct wait_queue_entry * wait)1259 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
1260 					struct wait_queue_entry *wait)
1261 {
1262 	if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1263 		if (test_and_set_bit(bit_nr, &folio->flags))
1264 			return false;
1265 	} else if (test_bit(bit_nr, &folio->flags))
1266 		return false;
1267 
1268 	wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1269 	return true;
1270 }
1271 
1272 /* How many times do we accept lock stealing from under a waiter? */
1273 int sysctl_page_lock_unfairness = 5;
1274 
folio_wait_bit_common(struct folio * folio,int bit_nr,int state,enum behavior behavior)1275 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1276 		int state, enum behavior behavior)
1277 {
1278 	wait_queue_head_t *q = folio_waitqueue(folio);
1279 	int unfairness = sysctl_page_lock_unfairness;
1280 	struct wait_page_queue wait_page;
1281 	wait_queue_entry_t *wait = &wait_page.wait;
1282 	bool thrashing = false;
1283 	unsigned long pflags;
1284 	bool in_thrashing;
1285 
1286 	if (bit_nr == PG_locked &&
1287 	    !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1288 		delayacct_thrashing_start(&in_thrashing);
1289 		psi_memstall_enter(&pflags);
1290 		thrashing = true;
1291 	}
1292 
1293 	init_wait(wait);
1294 	wait->func = wake_page_function;
1295 	wait_page.folio = folio;
1296 	wait_page.bit_nr = bit_nr;
1297 
1298 repeat:
1299 	wait->flags = 0;
1300 	if (behavior == EXCLUSIVE) {
1301 		wait->flags = WQ_FLAG_EXCLUSIVE;
1302 		if (--unfairness < 0)
1303 			wait->flags |= WQ_FLAG_CUSTOM;
1304 	}
1305 
1306 	/*
1307 	 * Do one last check whether we can get the
1308 	 * page bit synchronously.
1309 	 *
1310 	 * Do the folio_set_waiters() marking before that
1311 	 * to let any waker we _just_ missed know they
1312 	 * need to wake us up (otherwise they'll never
1313 	 * even go to the slow case that looks at the
1314 	 * page queue), and add ourselves to the wait
1315 	 * queue if we need to sleep.
1316 	 *
1317 	 * This part needs to be done under the queue
1318 	 * lock to avoid races.
1319 	 */
1320 	spin_lock_irq(&q->lock);
1321 	folio_set_waiters(folio);
1322 	if (!folio_trylock_flag(folio, bit_nr, wait))
1323 		__add_wait_queue_entry_tail(q, wait);
1324 	spin_unlock_irq(&q->lock);
1325 
1326 	/*
1327 	 * From now on, all the logic will be based on
1328 	 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1329 	 * see whether the page bit testing has already
1330 	 * been done by the wake function.
1331 	 *
1332 	 * We can drop our reference to the folio.
1333 	 */
1334 	if (behavior == DROP)
1335 		folio_put(folio);
1336 
1337 	/*
1338 	 * Note that until the "finish_wait()", or until
1339 	 * we see the WQ_FLAG_WOKEN flag, we need to
1340 	 * be very careful with the 'wait->flags', because
1341 	 * we may race with a waker that sets them.
1342 	 */
1343 	for (;;) {
1344 		unsigned int flags;
1345 
1346 		set_current_state(state);
1347 
1348 		/* Loop until we've been woken or interrupted */
1349 		flags = smp_load_acquire(&wait->flags);
1350 		if (!(flags & WQ_FLAG_WOKEN)) {
1351 			if (signal_pending_state(state, current))
1352 				break;
1353 
1354 			io_schedule();
1355 			continue;
1356 		}
1357 
1358 		/* If we were non-exclusive, we're done */
1359 		if (behavior != EXCLUSIVE)
1360 			break;
1361 
1362 		/* If the waker got the lock for us, we're done */
1363 		if (flags & WQ_FLAG_DONE)
1364 			break;
1365 
1366 		/*
1367 		 * Otherwise, if we're getting the lock, we need to
1368 		 * try to get it ourselves.
1369 		 *
1370 		 * And if that fails, we'll have to retry this all.
1371 		 */
1372 		if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
1373 			goto repeat;
1374 
1375 		wait->flags |= WQ_FLAG_DONE;
1376 		break;
1377 	}
1378 
1379 	/*
1380 	 * If a signal happened, this 'finish_wait()' may remove the last
1381 	 * waiter from the wait-queues, but the folio waiters bit will remain
1382 	 * set. That's ok. The next wakeup will take care of it, and trying
1383 	 * to do it here would be difficult and prone to races.
1384 	 */
1385 	finish_wait(q, wait);
1386 
1387 	if (thrashing) {
1388 		delayacct_thrashing_end(&in_thrashing);
1389 		psi_memstall_leave(&pflags);
1390 	}
1391 
1392 	/*
1393 	 * NOTE! The wait->flags weren't stable until we've done the
1394 	 * 'finish_wait()', and we could have exited the loop above due
1395 	 * to a signal, and had a wakeup event happen after the signal
1396 	 * test but before the 'finish_wait()'.
1397 	 *
1398 	 * So only after the finish_wait() can we reliably determine
1399 	 * if we got woken up or not, so we can now figure out the final
1400 	 * return value based on that state without races.
1401 	 *
1402 	 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1403 	 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1404 	 */
1405 	if (behavior == EXCLUSIVE)
1406 		return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1407 
1408 	return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1409 }
1410 
1411 #ifdef CONFIG_MIGRATION
1412 /**
1413  * migration_entry_wait_on_locked - Wait for a migration entry to be removed
1414  * @entry: migration swap entry.
1415  * @ptl: already locked ptl. This function will drop the lock.
1416  *
1417  * Wait for a migration entry referencing the given page to be removed. This is
1418  * equivalent to put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE) except
1419  * this can be called without taking a reference on the page. Instead this
1420  * should be called while holding the ptl for the migration entry referencing
1421  * the page.
1422  *
1423  * Returns after unlocking the ptl.
1424  *
1425  * This follows the same logic as folio_wait_bit_common() so see the comments
1426  * there.
1427  */
migration_entry_wait_on_locked(swp_entry_t entry,spinlock_t * ptl)1428 void migration_entry_wait_on_locked(swp_entry_t entry, spinlock_t *ptl)
1429 	__releases(ptl)
1430 {
1431 	struct wait_page_queue wait_page;
1432 	wait_queue_entry_t *wait = &wait_page.wait;
1433 	bool thrashing = false;
1434 	unsigned long pflags;
1435 	bool in_thrashing;
1436 	wait_queue_head_t *q;
1437 	struct folio *folio = pfn_swap_entry_folio(entry);
1438 
1439 	q = folio_waitqueue(folio);
1440 	if (!folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1441 		delayacct_thrashing_start(&in_thrashing);
1442 		psi_memstall_enter(&pflags);
1443 		thrashing = true;
1444 	}
1445 
1446 	init_wait(wait);
1447 	wait->func = wake_page_function;
1448 	wait_page.folio = folio;
1449 	wait_page.bit_nr = PG_locked;
1450 	wait->flags = 0;
1451 
1452 	spin_lock_irq(&q->lock);
1453 	folio_set_waiters(folio);
1454 	if (!folio_trylock_flag(folio, PG_locked, wait))
1455 		__add_wait_queue_entry_tail(q, wait);
1456 	spin_unlock_irq(&q->lock);
1457 
1458 	/*
1459 	 * If a migration entry exists for the page the migration path must hold
1460 	 * a valid reference to the page, and it must take the ptl to remove the
1461 	 * migration entry. So the page is valid until the ptl is dropped.
1462 	 */
1463 	spin_unlock(ptl);
1464 
1465 	for (;;) {
1466 		unsigned int flags;
1467 
1468 		set_current_state(TASK_UNINTERRUPTIBLE);
1469 
1470 		/* Loop until we've been woken or interrupted */
1471 		flags = smp_load_acquire(&wait->flags);
1472 		if (!(flags & WQ_FLAG_WOKEN)) {
1473 			if (signal_pending_state(TASK_UNINTERRUPTIBLE, current))
1474 				break;
1475 
1476 			io_schedule();
1477 			continue;
1478 		}
1479 		break;
1480 	}
1481 
1482 	finish_wait(q, wait);
1483 
1484 	if (thrashing) {
1485 		delayacct_thrashing_end(&in_thrashing);
1486 		psi_memstall_leave(&pflags);
1487 	}
1488 }
1489 #endif
1490 
folio_wait_bit(struct folio * folio,int bit_nr)1491 void folio_wait_bit(struct folio *folio, int bit_nr)
1492 {
1493 	folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1494 }
1495 EXPORT_SYMBOL(folio_wait_bit);
1496 
folio_wait_bit_killable(struct folio * folio,int bit_nr)1497 int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1498 {
1499 	return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1500 }
1501 EXPORT_SYMBOL(folio_wait_bit_killable);
1502 
1503 /**
1504  * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
1505  * @folio: The folio to wait for.
1506  * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1507  *
1508  * The caller should hold a reference on @folio.  They expect the page to
1509  * become unlocked relatively soon, but do not wish to hold up migration
1510  * (for example) by holding the reference while waiting for the folio to
1511  * come unlocked.  After this function returns, the caller should not
1512  * dereference @folio.
1513  *
1514  * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
1515  */
folio_put_wait_locked(struct folio * folio,int state)1516 static int folio_put_wait_locked(struct folio *folio, int state)
1517 {
1518 	return folio_wait_bit_common(folio, PG_locked, state, DROP);
1519 }
1520 
1521 /**
1522  * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
1523  * @folio: Folio defining the wait queue of interest
1524  * @waiter: Waiter to add to the queue
1525  *
1526  * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1527  */
folio_add_wait_queue(struct folio * folio,wait_queue_entry_t * waiter)1528 void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1529 {
1530 	wait_queue_head_t *q = folio_waitqueue(folio);
1531 	unsigned long flags;
1532 
1533 	spin_lock_irqsave(&q->lock, flags);
1534 	__add_wait_queue_entry_tail(q, waiter);
1535 	folio_set_waiters(folio);
1536 	spin_unlock_irqrestore(&q->lock, flags);
1537 }
1538 EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1539 
1540 /**
1541  * folio_unlock - Unlock a locked folio.
1542  * @folio: The folio.
1543  *
1544  * Unlocks the folio and wakes up any thread sleeping on the page lock.
1545  *
1546  * Context: May be called from interrupt or process context.  May not be
1547  * called from NMI context.
1548  */
folio_unlock(struct folio * folio)1549 void folio_unlock(struct folio *folio)
1550 {
1551 	/* Bit 7 allows x86 to check the byte's sign bit */
1552 	BUILD_BUG_ON(PG_waiters != 7);
1553 	BUILD_BUG_ON(PG_locked > 7);
1554 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1555 	if (folio_xor_flags_has_waiters(folio, 1 << PG_locked))
1556 		folio_wake_bit(folio, PG_locked);
1557 }
1558 EXPORT_SYMBOL(folio_unlock);
1559 
1560 /**
1561  * folio_end_read - End read on a folio.
1562  * @folio: The folio.
1563  * @success: True if all reads completed successfully.
1564  *
1565  * When all reads against a folio have completed, filesystems should
1566  * call this function to let the pagecache know that no more reads
1567  * are outstanding.  This will unlock the folio and wake up any thread
1568  * sleeping on the lock.  The folio will also be marked uptodate if all
1569  * reads succeeded.
1570  *
1571  * Context: May be called from interrupt or process context.  May not be
1572  * called from NMI context.
1573  */
folio_end_read(struct folio * folio,bool success)1574 void folio_end_read(struct folio *folio, bool success)
1575 {
1576 	unsigned long mask = 1 << PG_locked;
1577 
1578 	/* Must be in bottom byte for x86 to work */
1579 	BUILD_BUG_ON(PG_uptodate > 7);
1580 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1581 	VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio);
1582 
1583 	if (likely(success))
1584 		mask |= 1 << PG_uptodate;
1585 	if (folio_xor_flags_has_waiters(folio, mask))
1586 		folio_wake_bit(folio, PG_locked);
1587 }
1588 EXPORT_SYMBOL(folio_end_read);
1589 
1590 /**
1591  * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1592  * @folio: The folio.
1593  *
1594  * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
1595  * it.  The folio reference held for PG_private_2 being set is released.
1596  *
1597  * This is, for example, used when a netfs folio is being written to a local
1598  * disk cache, thereby allowing writes to the cache for the same folio to be
1599  * serialised.
1600  */
folio_end_private_2(struct folio * folio)1601 void folio_end_private_2(struct folio *folio)
1602 {
1603 	VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
1604 	clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
1605 	folio_wake_bit(folio, PG_private_2);
1606 	folio_put(folio);
1607 }
1608 EXPORT_SYMBOL(folio_end_private_2);
1609 
1610 /**
1611  * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1612  * @folio: The folio to wait on.
1613  *
1614  * Wait for PG_private_2 to be cleared on a folio.
1615  */
folio_wait_private_2(struct folio * folio)1616 void folio_wait_private_2(struct folio *folio)
1617 {
1618 	while (folio_test_private_2(folio))
1619 		folio_wait_bit(folio, PG_private_2);
1620 }
1621 EXPORT_SYMBOL(folio_wait_private_2);
1622 
1623 /**
1624  * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1625  * @folio: The folio to wait on.
1626  *
1627  * Wait for PG_private_2 to be cleared on a folio or until a fatal signal is
1628  * received by the calling task.
1629  *
1630  * Return:
1631  * - 0 if successful.
1632  * - -EINTR if a fatal signal was encountered.
1633  */
folio_wait_private_2_killable(struct folio * folio)1634 int folio_wait_private_2_killable(struct folio *folio)
1635 {
1636 	int ret = 0;
1637 
1638 	while (folio_test_private_2(folio)) {
1639 		ret = folio_wait_bit_killable(folio, PG_private_2);
1640 		if (ret < 0)
1641 			break;
1642 	}
1643 
1644 	return ret;
1645 }
1646 EXPORT_SYMBOL(folio_wait_private_2_killable);
1647 
filemap_end_dropbehind(struct folio * folio)1648 static void filemap_end_dropbehind(struct folio *folio)
1649 {
1650 	struct address_space *mapping = folio->mapping;
1651 
1652 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1653 
1654 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
1655 		return;
1656 	if (!folio_test_clear_dropbehind(folio))
1657 		return;
1658 	if (mapping)
1659 		folio_unmap_invalidate(mapping, folio, 0);
1660 }
1661 
1662 /*
1663  * If folio was marked as dropbehind, then pages should be dropped when writeback
1664  * completes. Do that now. If we fail, it's likely because of a big folio -
1665  * just reset dropbehind for that case and latter completions should invalidate.
1666  */
filemap_end_dropbehind_write(struct folio * folio)1667 static void filemap_end_dropbehind_write(struct folio *folio)
1668 {
1669 	if (!folio_test_dropbehind(folio))
1670 		return;
1671 
1672 	/*
1673 	 * Hitting !in_task() should not happen off RWF_DONTCACHE writeback,
1674 	 * but can happen if normal writeback just happens to find dirty folios
1675 	 * that were created as part of uncached writeback, and that writeback
1676 	 * would otherwise not need non-IRQ handling. Just skip the
1677 	 * invalidation in that case.
1678 	 */
1679 	if (in_task() && folio_trylock(folio)) {
1680 		filemap_end_dropbehind(folio);
1681 		folio_unlock(folio);
1682 	}
1683 }
1684 
1685 /**
1686  * folio_end_writeback - End writeback against a folio.
1687  * @folio: The folio.
1688  *
1689  * The folio must actually be under writeback.
1690  *
1691  * Context: May be called from process or interrupt context.
1692  */
folio_end_writeback(struct folio * folio)1693 void folio_end_writeback(struct folio *folio)
1694 {
1695 	VM_BUG_ON_FOLIO(!folio_test_writeback(folio), folio);
1696 
1697 	/*
1698 	 * folio_test_clear_reclaim() could be used here but it is an
1699 	 * atomic operation and overkill in this particular case. Failing
1700 	 * to shuffle a folio marked for immediate reclaim is too mild
1701 	 * a gain to justify taking an atomic operation penalty at the
1702 	 * end of every folio writeback.
1703 	 */
1704 	if (folio_test_reclaim(folio)) {
1705 		folio_clear_reclaim(folio);
1706 		folio_rotate_reclaimable(folio);
1707 	}
1708 
1709 	/*
1710 	 * Writeback does not hold a folio reference of its own, relying
1711 	 * on truncation to wait for the clearing of PG_writeback.
1712 	 * But here we must make sure that the folio is not freed and
1713 	 * reused before the folio_wake_bit().
1714 	 */
1715 	folio_get(folio);
1716 	if (__folio_end_writeback(folio))
1717 		folio_wake_bit(folio, PG_writeback);
1718 
1719 	filemap_end_dropbehind_write(folio);
1720 	acct_reclaim_writeback(folio);
1721 	folio_put(folio);
1722 }
1723 EXPORT_SYMBOL(folio_end_writeback);
1724 
1725 /**
1726  * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
1727  * @folio: The folio to lock
1728  */
__folio_lock(struct folio * folio)1729 void __folio_lock(struct folio *folio)
1730 {
1731 	folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
1732 				EXCLUSIVE);
1733 }
1734 EXPORT_SYMBOL(__folio_lock);
1735 
__folio_lock_killable(struct folio * folio)1736 int __folio_lock_killable(struct folio *folio)
1737 {
1738 	return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
1739 					EXCLUSIVE);
1740 }
1741 EXPORT_SYMBOL_GPL(__folio_lock_killable);
1742 
__folio_lock_async(struct folio * folio,struct wait_page_queue * wait)1743 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1744 {
1745 	struct wait_queue_head *q = folio_waitqueue(folio);
1746 	int ret;
1747 
1748 	wait->folio = folio;
1749 	wait->bit_nr = PG_locked;
1750 
1751 	spin_lock_irq(&q->lock);
1752 	__add_wait_queue_entry_tail(q, &wait->wait);
1753 	folio_set_waiters(folio);
1754 	ret = !folio_trylock(folio);
1755 	/*
1756 	 * If we were successful now, we know we're still on the
1757 	 * waitqueue as we're still under the lock. This means it's
1758 	 * safe to remove and return success, we know the callback
1759 	 * isn't going to trigger.
1760 	 */
1761 	if (!ret)
1762 		__remove_wait_queue(q, &wait->wait);
1763 	else
1764 		ret = -EIOCBQUEUED;
1765 	spin_unlock_irq(&q->lock);
1766 	return ret;
1767 }
1768 
1769 /*
1770  * Return values:
1771  * 0 - folio is locked.
1772  * non-zero - folio is not locked.
1773  *     mmap_lock or per-VMA lock has been released (mmap_read_unlock() or
1774  *     vma_end_read()), unless flags had both FAULT_FLAG_ALLOW_RETRY and
1775  *     FAULT_FLAG_RETRY_NOWAIT set, in which case the lock is still held.
1776  *
1777  * If neither ALLOW_RETRY nor KILLABLE are set, will always return 0
1778  * with the folio locked and the mmap_lock/per-VMA lock is left unperturbed.
1779  */
__folio_lock_or_retry(struct folio * folio,struct vm_fault * vmf)1780 vm_fault_t __folio_lock_or_retry(struct folio *folio, struct vm_fault *vmf)
1781 {
1782 	unsigned int flags = vmf->flags;
1783 
1784 	if (fault_flag_allow_retry_first(flags)) {
1785 		/*
1786 		 * CAUTION! In this case, mmap_lock/per-VMA lock is not
1787 		 * released even though returning VM_FAULT_RETRY.
1788 		 */
1789 		if (flags & FAULT_FLAG_RETRY_NOWAIT)
1790 			return VM_FAULT_RETRY;
1791 
1792 		release_fault_lock(vmf);
1793 		if (flags & FAULT_FLAG_KILLABLE)
1794 			folio_wait_locked_killable(folio);
1795 		else
1796 			folio_wait_locked(folio);
1797 		return VM_FAULT_RETRY;
1798 	}
1799 	if (flags & FAULT_FLAG_KILLABLE) {
1800 		bool ret;
1801 
1802 		ret = __folio_lock_killable(folio);
1803 		if (ret) {
1804 			release_fault_lock(vmf);
1805 			return VM_FAULT_RETRY;
1806 		}
1807 	} else {
1808 		__folio_lock(folio);
1809 	}
1810 
1811 	return 0;
1812 }
1813 
1814 /**
1815  * page_cache_next_miss() - Find the next gap in the page cache.
1816  * @mapping: Mapping.
1817  * @index: Index.
1818  * @max_scan: Maximum range to search.
1819  *
1820  * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1821  * gap with the lowest index.
1822  *
1823  * This function may be called under the rcu_read_lock.  However, this will
1824  * not atomically search a snapshot of the cache at a single point in time.
1825  * For example, if a gap is created at index 5, then subsequently a gap is
1826  * created at index 10, page_cache_next_miss covering both indices may
1827  * return 10 if called under the rcu_read_lock.
1828  *
1829  * Return: The index of the gap if found, otherwise an index outside the
1830  * range specified (in which case 'return - index >= max_scan' will be true).
1831  * In the rare case of index wrap-around, 0 will be returned.
1832  */
page_cache_next_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)1833 pgoff_t page_cache_next_miss(struct address_space *mapping,
1834 			     pgoff_t index, unsigned long max_scan)
1835 {
1836 	XA_STATE(xas, &mapping->i_pages, index);
1837 	unsigned long nr = max_scan;
1838 
1839 	while (nr--) {
1840 		void *entry = xas_next(&xas);
1841 		if (!entry || xa_is_value(entry))
1842 			return xas.xa_index;
1843 		if (xas.xa_index == 0)
1844 			return 0;
1845 	}
1846 
1847 	return index + max_scan;
1848 }
1849 EXPORT_SYMBOL(page_cache_next_miss);
1850 
1851 /**
1852  * page_cache_prev_miss() - Find the previous gap in the page cache.
1853  * @mapping: Mapping.
1854  * @index: Index.
1855  * @max_scan: Maximum range to search.
1856  *
1857  * Search the range [max(index - max_scan + 1, 0), index] for the
1858  * gap with the highest index.
1859  *
1860  * This function may be called under the rcu_read_lock.  However, this will
1861  * not atomically search a snapshot of the cache at a single point in time.
1862  * For example, if a gap is created at index 10, then subsequently a gap is
1863  * created at index 5, page_cache_prev_miss() covering both indices may
1864  * return 5 if called under the rcu_read_lock.
1865  *
1866  * Return: The index of the gap if found, otherwise an index outside the
1867  * range specified (in which case 'index - return >= max_scan' will be true).
1868  * In the rare case of wrap-around, ULONG_MAX will be returned.
1869  */
page_cache_prev_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)1870 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1871 			     pgoff_t index, unsigned long max_scan)
1872 {
1873 	XA_STATE(xas, &mapping->i_pages, index);
1874 
1875 	while (max_scan--) {
1876 		void *entry = xas_prev(&xas);
1877 		if (!entry || xa_is_value(entry))
1878 			break;
1879 		if (xas.xa_index == ULONG_MAX)
1880 			break;
1881 	}
1882 
1883 	return xas.xa_index;
1884 }
1885 EXPORT_SYMBOL(page_cache_prev_miss);
1886 
1887 /*
1888  * Lockless page cache protocol:
1889  * On the lookup side:
1890  * 1. Load the folio from i_pages
1891  * 2. Increment the refcount if it's not zero
1892  * 3. If the folio is not found by xas_reload(), put the refcount and retry
1893  *
1894  * On the removal side:
1895  * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
1896  * B. Remove the page from i_pages
1897  * C. Return the page to the page allocator
1898  *
1899  * This means that any page may have its reference count temporarily
1900  * increased by a speculative page cache (or GUP-fast) lookup as it can
1901  * be allocated by another user before the RCU grace period expires.
1902  * Because the refcount temporarily acquired here may end up being the
1903  * last refcount on the page, any page allocation must be freeable by
1904  * folio_put().
1905  */
1906 
1907 /*
1908  * filemap_get_entry - Get a page cache entry.
1909  * @mapping: the address_space to search
1910  * @index: The page cache index.
1911  *
1912  * Looks up the page cache entry at @mapping & @index.  If it is a folio,
1913  * it is returned with an increased refcount.  If it is a shadow entry
1914  * of a previously evicted folio, or a swap entry from shmem/tmpfs,
1915  * it is returned without further action.
1916  *
1917  * Return: The folio, swap or shadow entry, %NULL if nothing is found.
1918  */
filemap_get_entry(struct address_space * mapping,pgoff_t index)1919 void *filemap_get_entry(struct address_space *mapping, pgoff_t index)
1920 {
1921 	XA_STATE(xas, &mapping->i_pages, index);
1922 	struct folio *folio;
1923 
1924 	rcu_read_lock();
1925 repeat:
1926 	xas_reset(&xas);
1927 	folio = xas_load(&xas);
1928 	if (xas_retry(&xas, folio))
1929 		goto repeat;
1930 	/*
1931 	 * A shadow entry of a recently evicted page, or a swap entry from
1932 	 * shmem/tmpfs.  Return it without attempting to raise page count.
1933 	 */
1934 	if (!folio || xa_is_value(folio))
1935 		goto out;
1936 
1937 	if (!folio_try_get(folio))
1938 		goto repeat;
1939 
1940 	if (unlikely(folio != xas_reload(&xas))) {
1941 		folio_put(folio);
1942 		goto repeat;
1943 	}
1944 out:
1945 	rcu_read_unlock();
1946 
1947 	return folio;
1948 }
1949 
1950 /**
1951  * __filemap_get_folio - Find and get a reference to a folio.
1952  * @mapping: The address_space to search.
1953  * @index: The page index.
1954  * @fgp_flags: %FGP flags modify how the folio is returned.
1955  * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
1956  *
1957  * Looks up the page cache entry at @mapping & @index.
1958  *
1959  * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1960  * if the %GFP flags specified for %FGP_CREAT are atomic.
1961  *
1962  * If this function returns a folio, it is returned with an increased refcount.
1963  *
1964  * Return: The found folio or an ERR_PTR() otherwise.
1965  */
__filemap_get_folio(struct address_space * mapping,pgoff_t index,fgf_t fgp_flags,gfp_t gfp)1966 struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1967 		fgf_t fgp_flags, gfp_t gfp)
1968 {
1969 	struct folio *folio;
1970 
1971 repeat:
1972 	folio = filemap_get_entry(mapping, index);
1973 	if (xa_is_value(folio))
1974 		folio = NULL;
1975 	trace_android_vh_filemap_get_folio(mapping, index, fgp_flags,
1976 					gfp, folio);
1977 	if (!folio)
1978 		goto no_page;
1979 
1980 	if (fgp_flags & FGP_LOCK) {
1981 		if (fgp_flags & FGP_NOWAIT) {
1982 			if (!folio_trylock(folio)) {
1983 				folio_put(folio);
1984 				return ERR_PTR(-EAGAIN);
1985 			}
1986 		} else {
1987 			folio_lock(folio);
1988 		}
1989 
1990 		/* Has the page been truncated? */
1991 		if (unlikely(folio->mapping != mapping)) {
1992 			folio_unlock(folio);
1993 			folio_put(folio);
1994 			goto repeat;
1995 		}
1996 		VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
1997 	}
1998 
1999 	if (fgp_flags & FGP_ACCESSED)
2000 		folio_mark_accessed(folio);
2001 	else if (fgp_flags & FGP_WRITE) {
2002 		/* Clear idle flag for buffer write */
2003 		if (folio_test_idle(folio))
2004 			folio_clear_idle(folio);
2005 	}
2006 
2007 	if (fgp_flags & FGP_STABLE)
2008 		folio_wait_stable(folio);
2009 no_page:
2010 	if (!folio && (fgp_flags & FGP_CREAT)) {
2011 		unsigned int min_order = mapping_min_folio_order(mapping);
2012 		unsigned int order = max(min_order, FGF_GET_ORDER(fgp_flags));
2013 		int err;
2014 		index = mapping_align_index(mapping, index);
2015 
2016 		if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
2017 			gfp |= __GFP_WRITE;
2018 		if (fgp_flags & FGP_NOFS)
2019 			gfp &= ~__GFP_FS;
2020 		if (fgp_flags & FGP_NOWAIT) {
2021 			gfp &= ~GFP_KERNEL;
2022 			gfp |= GFP_NOWAIT | __GFP_NOWARN;
2023 		}
2024 
2025 		trace_android_vh_filemap_get_folio_gfp(mapping, fgp_flags, &gfp);
2026 
2027 		if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
2028 			fgp_flags |= FGP_LOCK;
2029 
2030 		if (order > mapping_max_folio_order(mapping))
2031 			order = mapping_max_folio_order(mapping);
2032 		/* If we're not aligned, allocate a smaller folio */
2033 		if (index & ((1UL << order) - 1))
2034 			order = __ffs(index);
2035 
2036 		do {
2037 			gfp_t alloc_gfp = gfp;
2038 
2039 			err = -ENOMEM;
2040 			if (order > min_order)
2041 				alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN;
2042 			folio = filemap_alloc_folio(alloc_gfp, order);
2043 			if (!folio)
2044 				continue;
2045 
2046 			/* Init accessed so avoid atomic mark_page_accessed later */
2047 			if (fgp_flags & FGP_ACCESSED)
2048 				__folio_set_referenced(folio);
2049 			if (fgp_flags & FGP_DONTCACHE)
2050 				__folio_set_dropbehind(folio);
2051 
2052 			err = filemap_add_folio(mapping, folio, index, gfp);
2053 			if (!err)
2054 				break;
2055 			folio_put(folio);
2056 			folio = NULL;
2057 		} while (order-- > min_order);
2058 
2059 		if (err == -EEXIST)
2060 			goto repeat;
2061 		if (err) {
2062 			/*
2063 			 * When NOWAIT I/O fails to allocate folios this could
2064 			 * be due to a nonblocking memory allocation and not
2065 			 * because the system actually is out of memory.
2066 			 * Return -EAGAIN so that there caller retries in a
2067 			 * blocking fashion instead of propagating -ENOMEM
2068 			 * to the application.
2069 			 */
2070 			if ((fgp_flags & FGP_NOWAIT) && err == -ENOMEM)
2071 				err = -EAGAIN;
2072 			return ERR_PTR(err);
2073 		}
2074 		/*
2075 		 * filemap_add_folio locks the page, and for mmap
2076 		 * we expect an unlocked page.
2077 		 */
2078 		if (folio && (fgp_flags & FGP_FOR_MMAP))
2079 			folio_unlock(folio);
2080 	}
2081 
2082 	if (!folio)
2083 		return ERR_PTR(-ENOENT);
2084 	/* not an uncached lookup, clear uncached if set */
2085 	if (folio_test_dropbehind(folio) && !(fgp_flags & FGP_DONTCACHE))
2086 		folio_clear_dropbehind(folio);
2087 	return folio;
2088 }
2089 EXPORT_SYMBOL(__filemap_get_folio);
2090 
find_get_entry(struct xa_state * xas,pgoff_t max,xa_mark_t mark)2091 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
2092 		xa_mark_t mark)
2093 {
2094 	struct folio *folio;
2095 
2096 retry:
2097 	if (mark == XA_PRESENT)
2098 		folio = xas_find(xas, max);
2099 	else
2100 		folio = xas_find_marked(xas, max, mark);
2101 
2102 	if (xas_retry(xas, folio))
2103 		goto retry;
2104 	/*
2105 	 * A shadow entry of a recently evicted page, a swap
2106 	 * entry from shmem/tmpfs or a DAX entry.  Return it
2107 	 * without attempting to raise page count.
2108 	 */
2109 	if (!folio || xa_is_value(folio))
2110 		return folio;
2111 
2112 	if (!folio_try_get(folio))
2113 		goto reset;
2114 
2115 	if (unlikely(folio != xas_reload(xas))) {
2116 		folio_put(folio);
2117 		goto reset;
2118 	}
2119 
2120 	return folio;
2121 reset:
2122 	xas_reset(xas);
2123 	goto retry;
2124 }
2125 
2126 /**
2127  * find_get_entries - gang pagecache lookup
2128  * @mapping:	The address_space to search
2129  * @start:	The starting page cache index
2130  * @end:	The final page index (inclusive).
2131  * @fbatch:	Where the resulting entries are placed.
2132  * @indices:	The cache indices corresponding to the entries in @entries
2133  *
2134  * find_get_entries() will search for and return a batch of entries in
2135  * the mapping.  The entries are placed in @fbatch.  find_get_entries()
2136  * takes a reference on any actual folios it returns.
2137  *
2138  * The entries have ascending indexes.  The indices may not be consecutive
2139  * due to not-present entries or large folios.
2140  *
2141  * Any shadow entries of evicted folios, or swap entries from
2142  * shmem/tmpfs, are included in the returned array.
2143  *
2144  * Return: The number of entries which were found.
2145  */
find_get_entries(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch,pgoff_t * indices)2146 unsigned find_get_entries(struct address_space *mapping, pgoff_t *start,
2147 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2148 {
2149 	XA_STATE(xas, &mapping->i_pages, *start);
2150 	struct folio *folio;
2151 
2152 	rcu_read_lock();
2153 	while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2154 		indices[fbatch->nr] = xas.xa_index;
2155 		if (!folio_batch_add(fbatch, folio))
2156 			break;
2157 	}
2158 
2159 	if (folio_batch_count(fbatch)) {
2160 		unsigned long nr;
2161 		int idx = folio_batch_count(fbatch) - 1;
2162 
2163 		folio = fbatch->folios[idx];
2164 		if (!xa_is_value(folio))
2165 			nr = folio_nr_pages(folio);
2166 		else
2167 			nr = 1 << xa_get_order(&mapping->i_pages, indices[idx]);
2168 		*start = round_down(indices[idx] + nr, nr);
2169 	}
2170 	rcu_read_unlock();
2171 
2172 	return folio_batch_count(fbatch);
2173 }
2174 
2175 /**
2176  * find_lock_entries - Find a batch of pagecache entries.
2177  * @mapping:	The address_space to search.
2178  * @start:	The starting page cache index.
2179  * @end:	The final page index (inclusive).
2180  * @fbatch:	Where the resulting entries are placed.
2181  * @indices:	The cache indices of the entries in @fbatch.
2182  *
2183  * find_lock_entries() will return a batch of entries from @mapping.
2184  * Swap, shadow and DAX entries are included.  Folios are returned
2185  * locked and with an incremented refcount.  Folios which are locked
2186  * by somebody else or under writeback are skipped.  Folios which are
2187  * partially outside the range are not returned.
2188  *
2189  * The entries have ascending indexes.  The indices may not be consecutive
2190  * due to not-present entries, large folios, folios which could not be
2191  * locked or folios under writeback.
2192  *
2193  * Return: The number of entries which were found.
2194  */
find_lock_entries(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch,pgoff_t * indices)2195 unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,
2196 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2197 {
2198 	XA_STATE(xas, &mapping->i_pages, *start);
2199 	struct folio *folio;
2200 
2201 	rcu_read_lock();
2202 	while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2203 		unsigned long base;
2204 		unsigned long nr;
2205 
2206 		if (!xa_is_value(folio)) {
2207 			nr = folio_nr_pages(folio);
2208 			base = folio->index;
2209 			/* Omit large folio which begins before the start */
2210 			if (base < *start)
2211 				goto put;
2212 			/* Omit large folio which extends beyond the end */
2213 			if (base + nr - 1 > end)
2214 				goto put;
2215 			if (!folio_trylock(folio))
2216 				goto put;
2217 			if (folio->mapping != mapping ||
2218 			    folio_test_writeback(folio))
2219 				goto unlock;
2220 			VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2221 					folio);
2222 		} else {
2223 			nr = 1 << xas_get_order(&xas);
2224 			base = xas.xa_index & ~(nr - 1);
2225 			/* Omit order>0 value which begins before the start */
2226 			if (base < *start)
2227 				continue;
2228 			/* Omit order>0 value which extends beyond the end */
2229 			if (base + nr - 1 > end)
2230 				break;
2231 		}
2232 
2233 		/* Update start now so that last update is correct on return */
2234 		*start = base + nr;
2235 		indices[fbatch->nr] = xas.xa_index;
2236 		if (!folio_batch_add(fbatch, folio))
2237 			break;
2238 		continue;
2239 unlock:
2240 		folio_unlock(folio);
2241 put:
2242 		folio_put(folio);
2243 	}
2244 	rcu_read_unlock();
2245 
2246 	return folio_batch_count(fbatch);
2247 }
2248 
2249 /**
2250  * filemap_get_folios - Get a batch of folios
2251  * @mapping:	The address_space to search
2252  * @start:	The starting page index
2253  * @end:	The final page index (inclusive)
2254  * @fbatch:	The batch to fill.
2255  *
2256  * Search for and return a batch of folios in the mapping starting at
2257  * index @start and up to index @end (inclusive).  The folios are returned
2258  * in @fbatch with an elevated reference count.
2259  *
2260  * Return: The number of folios which were found.
2261  * We also update @start to index the next folio for the traversal.
2262  */
filemap_get_folios(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch)2263 unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start,
2264 		pgoff_t end, struct folio_batch *fbatch)
2265 {
2266 	return filemap_get_folios_tag(mapping, start, end, XA_PRESENT, fbatch);
2267 }
2268 EXPORT_SYMBOL(filemap_get_folios);
2269 
2270 /**
2271  * filemap_get_folios_contig - Get a batch of contiguous folios
2272  * @mapping:	The address_space to search
2273  * @start:	The starting page index
2274  * @end:	The final page index (inclusive)
2275  * @fbatch:	The batch to fill
2276  *
2277  * filemap_get_folios_contig() works exactly like filemap_get_folios(),
2278  * except the returned folios are guaranteed to be contiguous. This may
2279  * not return all contiguous folios if the batch gets filled up.
2280  *
2281  * Return: The number of folios found.
2282  * Also update @start to be positioned for traversal of the next folio.
2283  */
2284 
filemap_get_folios_contig(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch)2285 unsigned filemap_get_folios_contig(struct address_space *mapping,
2286 		pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
2287 {
2288 	XA_STATE(xas, &mapping->i_pages, *start);
2289 	unsigned long nr;
2290 	struct folio *folio;
2291 
2292 	rcu_read_lock();
2293 
2294 	for (folio = xas_load(&xas); folio && xas.xa_index <= end;
2295 			folio = xas_next(&xas)) {
2296 		if (xas_retry(&xas, folio))
2297 			continue;
2298 		/*
2299 		 * If the entry has been swapped out, we can stop looking.
2300 		 * No current caller is looking for DAX entries.
2301 		 */
2302 		if (xa_is_value(folio))
2303 			goto update_start;
2304 
2305 		/* If we landed in the middle of a THP, continue at its end. */
2306 		if (xa_is_sibling(folio))
2307 			goto update_start;
2308 
2309 		if (!folio_try_get(folio))
2310 			goto retry;
2311 
2312 		if (unlikely(folio != xas_reload(&xas)))
2313 			goto put_folio;
2314 
2315 		if (!folio_batch_add(fbatch, folio)) {
2316 			nr = folio_nr_pages(folio);
2317 			*start = folio->index + nr;
2318 			goto out;
2319 		}
2320 		xas_advance(&xas, folio_next_index(folio) - 1);
2321 		continue;
2322 put_folio:
2323 		folio_put(folio);
2324 
2325 retry:
2326 		xas_reset(&xas);
2327 	}
2328 
2329 update_start:
2330 	nr = folio_batch_count(fbatch);
2331 
2332 	if (nr) {
2333 		folio = fbatch->folios[nr - 1];
2334 		*start = folio_next_index(folio);
2335 	}
2336 out:
2337 	rcu_read_unlock();
2338 	return folio_batch_count(fbatch);
2339 }
2340 EXPORT_SYMBOL(filemap_get_folios_contig);
2341 
2342 /**
2343  * filemap_get_folios_tag - Get a batch of folios matching @tag
2344  * @mapping:    The address_space to search
2345  * @start:      The starting page index
2346  * @end:        The final page index (inclusive)
2347  * @tag:        The tag index
2348  * @fbatch:     The batch to fill
2349  *
2350  * The first folio may start before @start; if it does, it will contain
2351  * @start.  The final folio may extend beyond @end; if it does, it will
2352  * contain @end.  The folios have ascending indices.  There may be gaps
2353  * between the folios if there are indices which have no folio in the
2354  * page cache.  If folios are added to or removed from the page cache
2355  * while this is running, they may or may not be found by this call.
2356  * Only returns folios that are tagged with @tag.
2357  *
2358  * Return: The number of folios found.
2359  * Also update @start to index the next folio for traversal.
2360  */
filemap_get_folios_tag(struct address_space * mapping,pgoff_t * start,pgoff_t end,xa_mark_t tag,struct folio_batch * fbatch)2361 unsigned filemap_get_folios_tag(struct address_space *mapping, pgoff_t *start,
2362 			pgoff_t end, xa_mark_t tag, struct folio_batch *fbatch)
2363 {
2364 	XA_STATE(xas, &mapping->i_pages, *start);
2365 	struct folio *folio;
2366 
2367 	rcu_read_lock();
2368 	while ((folio = find_get_entry(&xas, end, tag)) != NULL) {
2369 		/*
2370 		 * Shadow entries should never be tagged, but this iteration
2371 		 * is lockless so there is a window for page reclaim to evict
2372 		 * a page we saw tagged. Skip over it.
2373 		 */
2374 		if (xa_is_value(folio))
2375 			continue;
2376 		if (!folio_batch_add(fbatch, folio)) {
2377 			unsigned long nr = folio_nr_pages(folio);
2378 			*start = folio->index + nr;
2379 			goto out;
2380 		}
2381 	}
2382 	/*
2383 	 * We come here when there is no page beyond @end. We take care to not
2384 	 * overflow the index @start as it confuses some of the callers. This
2385 	 * breaks the iteration when there is a page at index -1 but that is
2386 	 * already broke anyway.
2387 	 */
2388 	if (end == (pgoff_t)-1)
2389 		*start = (pgoff_t)-1;
2390 	else
2391 		*start = end + 1;
2392 out:
2393 	rcu_read_unlock();
2394 
2395 	return folio_batch_count(fbatch);
2396 }
2397 EXPORT_SYMBOL(filemap_get_folios_tag);
2398 
2399 /*
2400  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2401  * a _large_ part of the i/o request. Imagine the worst scenario:
2402  *
2403  *      ---R__________________________________________B__________
2404  *         ^ reading here                             ^ bad block(assume 4k)
2405  *
2406  * read(R) => miss => readahead(R...B) => media error => frustrating retries
2407  * => failing the whole request => read(R) => read(R+1) =>
2408  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2409  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2410  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2411  *
2412  * It is going insane. Fix it by quickly scaling down the readahead size.
2413  */
shrink_readahead_size_eio(struct file_ra_state * ra)2414 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2415 {
2416 	ra->ra_pages /= 4;
2417 }
2418 
2419 /*
2420  * filemap_get_read_batch - Get a batch of folios for read
2421  *
2422  * Get a batch of folios which represent a contiguous range of bytes in
2423  * the file.  No exceptional entries will be returned.  If @index is in
2424  * the middle of a folio, the entire folio will be returned.  The last
2425  * folio in the batch may have the readahead flag set or the uptodate flag
2426  * clear so that the caller can take the appropriate action.
2427  */
filemap_get_read_batch(struct address_space * mapping,pgoff_t index,pgoff_t max,struct folio_batch * fbatch)2428 static void filemap_get_read_batch(struct address_space *mapping,
2429 		pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2430 {
2431 	XA_STATE(xas, &mapping->i_pages, index);
2432 	struct folio *folio;
2433 
2434 	rcu_read_lock();
2435 	for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2436 		if (xas_retry(&xas, folio))
2437 			continue;
2438 		if (xas.xa_index > max || xa_is_value(folio))
2439 			break;
2440 		if (xa_is_sibling(folio))
2441 			break;
2442 		if (!folio_try_get(folio))
2443 			goto retry;
2444 
2445 		if (unlikely(folio != xas_reload(&xas)))
2446 			goto put_folio;
2447 
2448 		if (!folio_batch_add(fbatch, folio))
2449 			break;
2450 		if (!folio_test_uptodate(folio))
2451 			break;
2452 		if (folio_test_readahead(folio))
2453 			break;
2454 		xas_advance(&xas, folio_next_index(folio) - 1);
2455 		continue;
2456 put_folio:
2457 		folio_put(folio);
2458 retry:
2459 		xas_reset(&xas);
2460 	}
2461 	rcu_read_unlock();
2462 }
2463 
filemap_read_folio(struct file * file,filler_t filler,struct folio * folio)2464 static int filemap_read_folio(struct file *file, filler_t filler,
2465 		struct folio *folio)
2466 {
2467 	bool workingset = folio_test_workingset(folio);
2468 	unsigned long pflags;
2469 	int error;
2470 
2471 	/* Start the actual read. The read will unlock the page. */
2472 	if (unlikely(workingset))
2473 		psi_memstall_enter(&pflags);
2474 	error = filler(file, folio);
2475 	if (unlikely(workingset))
2476 		psi_memstall_leave(&pflags);
2477 	if (error)
2478 		return error;
2479 
2480 	error = folio_wait_locked_killable(folio);
2481 	if (error)
2482 		return error;
2483 	if (folio_test_uptodate(folio))
2484 		return 0;
2485 	if (file)
2486 		shrink_readahead_size_eio(&file->f_ra);
2487 	return -EIO;
2488 }
2489 
filemap_range_uptodate(struct address_space * mapping,loff_t pos,size_t count,struct folio * folio,bool need_uptodate)2490 static bool filemap_range_uptodate(struct address_space *mapping,
2491 		loff_t pos, size_t count, struct folio *folio,
2492 		bool need_uptodate)
2493 {
2494 	if (folio_test_uptodate(folio))
2495 		return true;
2496 	/* pipes can't handle partially uptodate pages */
2497 	if (need_uptodate)
2498 		return false;
2499 	if (!mapping->a_ops->is_partially_uptodate)
2500 		return false;
2501 	if (mapping->host->i_blkbits >= folio_shift(folio))
2502 		return false;
2503 
2504 	if (folio_pos(folio) > pos) {
2505 		count -= folio_pos(folio) - pos;
2506 		pos = 0;
2507 	} else {
2508 		pos -= folio_pos(folio);
2509 	}
2510 
2511 	return mapping->a_ops->is_partially_uptodate(folio, pos, count);
2512 }
2513 
filemap_update_page(struct kiocb * iocb,struct address_space * mapping,size_t count,struct folio * folio,bool need_uptodate)2514 static int filemap_update_page(struct kiocb *iocb,
2515 		struct address_space *mapping, size_t count,
2516 		struct folio *folio, bool need_uptodate)
2517 {
2518 	int error;
2519 
2520 	trace_android_vh_filemap_update_page(mapping, folio, iocb->ki_filp);
2521 
2522 	if (iocb->ki_flags & IOCB_NOWAIT) {
2523 		if (!filemap_invalidate_trylock_shared(mapping))
2524 			return -EAGAIN;
2525 	} else {
2526 		filemap_invalidate_lock_shared(mapping);
2527 	}
2528 
2529 	if (!folio_trylock(folio)) {
2530 		error = -EAGAIN;
2531 		if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2532 			goto unlock_mapping;
2533 		if (!(iocb->ki_flags & IOCB_WAITQ)) {
2534 			filemap_invalidate_unlock_shared(mapping);
2535 			/*
2536 			 * This is where we usually end up waiting for a
2537 			 * previously submitted readahead to finish.
2538 			 */
2539 			folio_put_wait_locked(folio, TASK_KILLABLE);
2540 			return AOP_TRUNCATED_PAGE;
2541 		}
2542 		error = __folio_lock_async(folio, iocb->ki_waitq);
2543 		if (error)
2544 			goto unlock_mapping;
2545 	}
2546 
2547 	error = AOP_TRUNCATED_PAGE;
2548 	if (!folio->mapping)
2549 		goto unlock;
2550 
2551 	error = 0;
2552 	if (filemap_range_uptodate(mapping, iocb->ki_pos, count, folio,
2553 				   need_uptodate))
2554 		goto unlock;
2555 
2556 	error = -EAGAIN;
2557 	if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2558 		goto unlock;
2559 
2560 	error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio,
2561 			folio);
2562 	goto unlock_mapping;
2563 unlock:
2564 	folio_unlock(folio);
2565 unlock_mapping:
2566 	filemap_invalidate_unlock_shared(mapping);
2567 	if (error == AOP_TRUNCATED_PAGE)
2568 		folio_put(folio);
2569 	return error;
2570 }
2571 
filemap_create_folio(struct kiocb * iocb,struct folio_batch * fbatch)2572 static int filemap_create_folio(struct kiocb *iocb, struct folio_batch *fbatch)
2573 {
2574 	struct address_space *mapping = iocb->ki_filp->f_mapping;
2575 	struct folio *folio;
2576 	int error;
2577 	unsigned int min_order = mapping_min_folio_order(mapping);
2578 	pgoff_t index;
2579 
2580 	if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2581 		return -EAGAIN;
2582 
2583 	folio = filemap_alloc_folio(mapping_gfp_mask(mapping), min_order);
2584 	if (!folio)
2585 		return -ENOMEM;
2586 	if (iocb->ki_flags & IOCB_DONTCACHE)
2587 		__folio_set_dropbehind(folio);
2588 
2589 	/*
2590 	 * Protect against truncate / hole punch. Grabbing invalidate_lock
2591 	 * here assures we cannot instantiate and bring uptodate new
2592 	 * pagecache folios after evicting page cache during truncate
2593 	 * and before actually freeing blocks.	Note that we could
2594 	 * release invalidate_lock after inserting the folio into
2595 	 * the page cache as the locked folio would then be enough to
2596 	 * synchronize with hole punching. But there are code paths
2597 	 * such as filemap_update_page() filling in partially uptodate
2598 	 * pages or ->readahead() that need to hold invalidate_lock
2599 	 * while mapping blocks for IO so let's hold the lock here as
2600 	 * well to keep locking rules simple.
2601 	 */
2602 	filemap_invalidate_lock_shared(mapping);
2603 	index = (iocb->ki_pos >> (PAGE_SHIFT + min_order)) << min_order;
2604 	error = filemap_add_folio(mapping, folio, index,
2605 			mapping_gfp_constraint(mapping, GFP_KERNEL));
2606 	if (error == -EEXIST)
2607 		error = AOP_TRUNCATED_PAGE;
2608 	if (error)
2609 		goto error;
2610 
2611 	error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio,
2612 					folio);
2613 	if (error)
2614 		goto error;
2615 
2616 	filemap_invalidate_unlock_shared(mapping);
2617 	folio_batch_add(fbatch, folio);
2618 	return 0;
2619 error:
2620 	filemap_invalidate_unlock_shared(mapping);
2621 	folio_put(folio);
2622 	return error;
2623 }
2624 
filemap_readahead(struct kiocb * iocb,struct file * file,struct address_space * mapping,struct folio * folio,pgoff_t last_index)2625 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2626 		struct address_space *mapping, struct folio *folio,
2627 		pgoff_t last_index)
2628 {
2629 	DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
2630 
2631 	if (iocb->ki_flags & IOCB_NOIO)
2632 		return -EAGAIN;
2633 	if (iocb->ki_flags & IOCB_DONTCACHE)
2634 		ractl.dropbehind = 1;
2635 	page_cache_async_ra(&ractl, folio, last_index - folio->index);
2636 	return 0;
2637 }
2638 
filemap_get_pages(struct kiocb * iocb,size_t count,struct folio_batch * fbatch,bool need_uptodate)2639 static int filemap_get_pages(struct kiocb *iocb, size_t count,
2640 		struct folio_batch *fbatch, bool need_uptodate)
2641 {
2642 	struct file *filp = iocb->ki_filp;
2643 	struct address_space *mapping = filp->f_mapping;
2644 	pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2645 	pgoff_t last_index;
2646 	struct folio *folio;
2647 	unsigned int flags;
2648 	int err = 0;
2649 
2650 	/* "last_index" is the index of the page beyond the end of the read */
2651 	last_index = DIV_ROUND_UP(iocb->ki_pos + count, PAGE_SIZE);
2652 retry:
2653 	if (fatal_signal_pending(current))
2654 		return -EINTR;
2655 
2656 	filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
2657 	if (!folio_batch_count(fbatch)) {
2658 		DEFINE_READAHEAD(ractl, filp, &filp->f_ra, mapping, index);
2659 
2660 		if (iocb->ki_flags & IOCB_NOIO)
2661 			return -EAGAIN;
2662 		if (iocb->ki_flags & IOCB_NOWAIT)
2663 			flags = memalloc_noio_save();
2664 		if (iocb->ki_flags & IOCB_DONTCACHE)
2665 			ractl.dropbehind = 1;
2666 		page_cache_sync_ra(&ractl, last_index - index);
2667 		if (iocb->ki_flags & IOCB_NOWAIT)
2668 			memalloc_noio_restore(flags);
2669 		filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
2670 	}
2671 	if (!folio_batch_count(fbatch)) {
2672 		err = filemap_create_folio(iocb, fbatch);
2673 		if (err == AOP_TRUNCATED_PAGE)
2674 			goto retry;
2675 		return err;
2676 	}
2677 
2678 	folio = fbatch->folios[folio_batch_count(fbatch) - 1];
2679 	if (folio_test_readahead(folio)) {
2680 		err = filemap_readahead(iocb, filp, mapping, folio, last_index);
2681 		if (err)
2682 			goto err;
2683 	}
2684 	if (!folio_test_uptodate(folio)) {
2685 		if ((iocb->ki_flags & IOCB_WAITQ) &&
2686 		    folio_batch_count(fbatch) > 1)
2687 			iocb->ki_flags |= IOCB_NOWAIT;
2688 		err = filemap_update_page(iocb, mapping, count, folio,
2689 					  need_uptodate);
2690 		if (err)
2691 			goto err;
2692 	}
2693 
2694 	trace_mm_filemap_get_pages(mapping, index, last_index - 1);
2695 	return 0;
2696 err:
2697 	if (err < 0)
2698 		folio_put(folio);
2699 	if (likely(--fbatch->nr))
2700 		return 0;
2701 	if (err == AOP_TRUNCATED_PAGE)
2702 		goto retry;
2703 	return err;
2704 }
2705 
pos_same_folio(loff_t pos1,loff_t pos2,struct folio * folio)2706 static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)
2707 {
2708 	unsigned int shift = folio_shift(folio);
2709 
2710 	return (pos1 >> shift == pos2 >> shift);
2711 }
2712 
filemap_end_dropbehind_read(struct folio * folio)2713 static void filemap_end_dropbehind_read(struct folio *folio)
2714 {
2715 	if (!folio_test_dropbehind(folio))
2716 		return;
2717 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
2718 		return;
2719 	if (folio_trylock(folio)) {
2720 		filemap_end_dropbehind(folio);
2721 		folio_unlock(folio);
2722 	}
2723 }
2724 
2725 /**
2726  * filemap_read - Read data from the page cache.
2727  * @iocb: The iocb to read.
2728  * @iter: Destination for the data.
2729  * @already_read: Number of bytes already read by the caller.
2730  *
2731  * Copies data from the page cache.  If the data is not currently present,
2732  * uses the readahead and read_folio address_space operations to fetch it.
2733  *
2734  * Return: Total number of bytes copied, including those already read by
2735  * the caller.  If an error happens before any bytes are copied, returns
2736  * a negative error number.
2737  */
filemap_read(struct kiocb * iocb,struct iov_iter * iter,ssize_t already_read)2738 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2739 		ssize_t already_read)
2740 {
2741 	struct file *filp = iocb->ki_filp;
2742 	struct file_ra_state *ra = &filp->f_ra;
2743 	struct address_space *mapping = filp->f_mapping;
2744 	struct inode *inode = mapping->host;
2745 	struct folio_batch fbatch;
2746 	int i, error = 0;
2747 	bool writably_mapped;
2748 	loff_t isize, end_offset;
2749 	loff_t last_pos = ra->prev_pos;
2750 
2751 	if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2752 		return 0;
2753 	if (unlikely(!iov_iter_count(iter)))
2754 		return 0;
2755 
2756 	iov_iter_truncate(iter, inode->i_sb->s_maxbytes - iocb->ki_pos);
2757 	folio_batch_init(&fbatch);
2758 	trace_android_vh_filemap_read(filp, iocb->ki_pos, iov_iter_count(iter));
2759 
2760 	do {
2761 		cond_resched();
2762 
2763 		/*
2764 		 * If we've already successfully copied some data, then we
2765 		 * can no longer safely return -EIOCBQUEUED. Hence mark
2766 		 * an async read NOWAIT at that point.
2767 		 */
2768 		if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2769 			iocb->ki_flags |= IOCB_NOWAIT;
2770 
2771 		if (unlikely(iocb->ki_pos >= i_size_read(inode)))
2772 			break;
2773 
2774 		error = filemap_get_pages(iocb, iter->count, &fbatch, false);
2775 		if (error < 0)
2776 			break;
2777 
2778 		/*
2779 		 * i_size must be checked after we know the pages are Uptodate.
2780 		 *
2781 		 * Checking i_size after the check allows us to calculate
2782 		 * the correct value for "nr", which means the zero-filled
2783 		 * part of the page is not copied back to userspace (unless
2784 		 * another truncate extends the file - this is desired though).
2785 		 */
2786 		isize = i_size_read(inode);
2787 		if (unlikely(iocb->ki_pos >= isize))
2788 			goto put_folios;
2789 		end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2790 
2791 		/*
2792 		 * Once we start copying data, we don't want to be touching any
2793 		 * cachelines that might be contended:
2794 		 */
2795 		writably_mapped = mapping_writably_mapped(mapping);
2796 
2797 		/*
2798 		 * When a read accesses the same folio several times, only
2799 		 * mark it as accessed the first time.
2800 		 */
2801 		if (!pos_same_folio(iocb->ki_pos, last_pos - 1,
2802 				    fbatch.folios[0]))
2803 			folio_mark_accessed(fbatch.folios[0]);
2804 
2805 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
2806 			struct folio *folio = fbatch.folios[i];
2807 			size_t fsize = folio_size(folio);
2808 			size_t offset = iocb->ki_pos & (fsize - 1);
2809 			size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2810 					     fsize - offset);
2811 			size_t copied;
2812 
2813 			if (end_offset < folio_pos(folio))
2814 				break;
2815 			if (i > 0)
2816 				folio_mark_accessed(folio);
2817 			/*
2818 			 * If users can be writing to this folio using arbitrary
2819 			 * virtual addresses, take care of potential aliasing
2820 			 * before reading the folio on the kernel side.
2821 			 */
2822 			if (writably_mapped)
2823 				flush_dcache_folio(folio);
2824 
2825 			copied = copy_folio_to_iter(folio, offset, bytes, iter);
2826 
2827 			already_read += copied;
2828 			iocb->ki_pos += copied;
2829 			last_pos = iocb->ki_pos;
2830 
2831 			if (copied < bytes) {
2832 				error = -EFAULT;
2833 				break;
2834 			}
2835 		}
2836 put_folios:
2837 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
2838 			struct folio *folio = fbatch.folios[i];
2839 
2840 			filemap_end_dropbehind_read(folio);
2841 			folio_put(folio);
2842 		}
2843 		folio_batch_init(&fbatch);
2844 	} while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2845 
2846 	file_accessed(filp);
2847 	ra->prev_pos = last_pos;
2848 	return already_read ? already_read : error;
2849 }
2850 EXPORT_SYMBOL_GPL(filemap_read);
2851 
kiocb_write_and_wait(struct kiocb * iocb,size_t count)2852 int kiocb_write_and_wait(struct kiocb *iocb, size_t count)
2853 {
2854 	struct address_space *mapping = iocb->ki_filp->f_mapping;
2855 	loff_t pos = iocb->ki_pos;
2856 	loff_t end = pos + count - 1;
2857 
2858 	if (iocb->ki_flags & IOCB_NOWAIT) {
2859 		if (filemap_range_needs_writeback(mapping, pos, end))
2860 			return -EAGAIN;
2861 		return 0;
2862 	}
2863 
2864 	return filemap_write_and_wait_range(mapping, pos, end);
2865 }
2866 EXPORT_SYMBOL_GPL(kiocb_write_and_wait);
2867 
filemap_invalidate_pages(struct address_space * mapping,loff_t pos,loff_t end,bool nowait)2868 int filemap_invalidate_pages(struct address_space *mapping,
2869 			     loff_t pos, loff_t end, bool nowait)
2870 {
2871 	int ret;
2872 
2873 	if (nowait) {
2874 		/* we could block if there are any pages in the range */
2875 		if (filemap_range_has_page(mapping, pos, end))
2876 			return -EAGAIN;
2877 	} else {
2878 		ret = filemap_write_and_wait_range(mapping, pos, end);
2879 		if (ret)
2880 			return ret;
2881 	}
2882 
2883 	/*
2884 	 * After a write we want buffered reads to be sure to go to disk to get
2885 	 * the new data.  We invalidate clean cached page from the region we're
2886 	 * about to write.  We do this *before* the write so that we can return
2887 	 * without clobbering -EIOCBQUEUED from ->direct_IO().
2888 	 */
2889 	return invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT,
2890 					     end >> PAGE_SHIFT);
2891 }
2892 
kiocb_invalidate_pages(struct kiocb * iocb,size_t count)2893 int kiocb_invalidate_pages(struct kiocb *iocb, size_t count)
2894 {
2895 	struct address_space *mapping = iocb->ki_filp->f_mapping;
2896 
2897 	return filemap_invalidate_pages(mapping, iocb->ki_pos,
2898 					iocb->ki_pos + count - 1,
2899 					iocb->ki_flags & IOCB_NOWAIT);
2900 }
2901 EXPORT_SYMBOL_GPL(kiocb_invalidate_pages);
2902 
2903 /**
2904  * generic_file_read_iter - generic filesystem read routine
2905  * @iocb:	kernel I/O control block
2906  * @iter:	destination for the data read
2907  *
2908  * This is the "read_iter()" routine for all filesystems
2909  * that can use the page cache directly.
2910  *
2911  * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2912  * be returned when no data can be read without waiting for I/O requests
2913  * to complete; it doesn't prevent readahead.
2914  *
2915  * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2916  * requests shall be made for the read or for readahead.  When no data
2917  * can be read, -EAGAIN shall be returned.  When readahead would be
2918  * triggered, a partial, possibly empty read shall be returned.
2919  *
2920  * Return:
2921  * * number of bytes copied, even for partial reads
2922  * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2923  */
2924 ssize_t
generic_file_read_iter(struct kiocb * iocb,struct iov_iter * iter)2925 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2926 {
2927 	size_t count = iov_iter_count(iter);
2928 	ssize_t retval = 0;
2929 
2930 	if (!count)
2931 		return 0; /* skip atime */
2932 
2933 	if (iocb->ki_flags & IOCB_DIRECT) {
2934 		struct file *file = iocb->ki_filp;
2935 		struct address_space *mapping = file->f_mapping;
2936 		struct inode *inode = mapping->host;
2937 
2938 		retval = kiocb_write_and_wait(iocb, count);
2939 		if (retval < 0)
2940 			return retval;
2941 		file_accessed(file);
2942 
2943 		retval = mapping->a_ops->direct_IO(iocb, iter);
2944 		if (retval >= 0) {
2945 			iocb->ki_pos += retval;
2946 			count -= retval;
2947 		}
2948 		if (retval != -EIOCBQUEUED)
2949 			iov_iter_revert(iter, count - iov_iter_count(iter));
2950 
2951 		/*
2952 		 * Btrfs can have a short DIO read if we encounter
2953 		 * compressed extents, so if there was an error, or if
2954 		 * we've already read everything we wanted to, or if
2955 		 * there was a short read because we hit EOF, go ahead
2956 		 * and return.  Otherwise fallthrough to buffered io for
2957 		 * the rest of the read.  Buffered reads will not work for
2958 		 * DAX files, so don't bother trying.
2959 		 */
2960 		if (retval < 0 || !count || IS_DAX(inode))
2961 			return retval;
2962 		if (iocb->ki_pos >= i_size_read(inode))
2963 			return retval;
2964 	}
2965 
2966 	return filemap_read(iocb, iter, retval);
2967 }
2968 EXPORT_SYMBOL(generic_file_read_iter);
2969 
2970 /*
2971  * Splice subpages from a folio into a pipe.
2972  */
splice_folio_into_pipe(struct pipe_inode_info * pipe,struct folio * folio,loff_t fpos,size_t size)2973 size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
2974 			      struct folio *folio, loff_t fpos, size_t size)
2975 {
2976 	struct page *page;
2977 	size_t spliced = 0, offset = offset_in_folio(folio, fpos);
2978 
2979 	page = folio_page(folio, offset / PAGE_SIZE);
2980 	size = min(size, folio_size(folio) - offset);
2981 	offset %= PAGE_SIZE;
2982 
2983 	while (spliced < size &&
2984 	       !pipe_full(pipe->head, pipe->tail, pipe->max_usage)) {
2985 		struct pipe_buffer *buf = pipe_head_buf(pipe);
2986 		size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced);
2987 
2988 		*buf = (struct pipe_buffer) {
2989 			.ops	= &page_cache_pipe_buf_ops,
2990 			.page	= page,
2991 			.offset	= offset,
2992 			.len	= part,
2993 		};
2994 		folio_get(folio);
2995 		pipe->head++;
2996 		page++;
2997 		spliced += part;
2998 		offset = 0;
2999 	}
3000 
3001 	return spliced;
3002 }
3003 
3004 /**
3005  * filemap_splice_read -  Splice data from a file's pagecache into a pipe
3006  * @in: The file to read from
3007  * @ppos: Pointer to the file position to read from
3008  * @pipe: The pipe to splice into
3009  * @len: The amount to splice
3010  * @flags: The SPLICE_F_* flags
3011  *
3012  * This function gets folios from a file's pagecache and splices them into the
3013  * pipe.  Readahead will be called as necessary to fill more folios.  This may
3014  * be used for blockdevs also.
3015  *
3016  * Return: On success, the number of bytes read will be returned and *@ppos
3017  * will be updated if appropriate; 0 will be returned if there is no more data
3018  * to be read; -EAGAIN will be returned if the pipe had no space, and some
3019  * other negative error code will be returned on error.  A short read may occur
3020  * if the pipe has insufficient space, we reach the end of the data or we hit a
3021  * hole.
3022  */
filemap_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)3023 ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
3024 			    struct pipe_inode_info *pipe,
3025 			    size_t len, unsigned int flags)
3026 {
3027 	struct folio_batch fbatch;
3028 	struct kiocb iocb;
3029 	size_t total_spliced = 0, used, npages;
3030 	loff_t isize, end_offset;
3031 	bool writably_mapped;
3032 	int i, error = 0;
3033 
3034 	if (unlikely(*ppos >= in->f_mapping->host->i_sb->s_maxbytes))
3035 		return 0;
3036 
3037 	init_sync_kiocb(&iocb, in);
3038 	iocb.ki_pos = *ppos;
3039 
3040 	/* Work out how much data we can actually add into the pipe */
3041 	used = pipe_occupancy(pipe->head, pipe->tail);
3042 	npages = max_t(ssize_t, pipe->max_usage - used, 0);
3043 	len = min_t(size_t, len, npages * PAGE_SIZE);
3044 
3045 	folio_batch_init(&fbatch);
3046 
3047 	do {
3048 		cond_resched();
3049 
3050 		if (*ppos >= i_size_read(in->f_mapping->host))
3051 			break;
3052 
3053 		iocb.ki_pos = *ppos;
3054 		error = filemap_get_pages(&iocb, len, &fbatch, true);
3055 		if (error < 0)
3056 			break;
3057 
3058 		/*
3059 		 * i_size must be checked after we know the pages are Uptodate.
3060 		 *
3061 		 * Checking i_size after the check allows us to calculate
3062 		 * the correct value for "nr", which means the zero-filled
3063 		 * part of the page is not copied back to userspace (unless
3064 		 * another truncate extends the file - this is desired though).
3065 		 */
3066 		isize = i_size_read(in->f_mapping->host);
3067 		if (unlikely(*ppos >= isize))
3068 			break;
3069 		end_offset = min_t(loff_t, isize, *ppos + len);
3070 
3071 		/*
3072 		 * Once we start copying data, we don't want to be touching any
3073 		 * cachelines that might be contended:
3074 		 */
3075 		writably_mapped = mapping_writably_mapped(in->f_mapping);
3076 
3077 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
3078 			struct folio *folio = fbatch.folios[i];
3079 			size_t n;
3080 
3081 			if (folio_pos(folio) >= end_offset)
3082 				goto out;
3083 			folio_mark_accessed(folio);
3084 
3085 			/*
3086 			 * If users can be writing to this folio using arbitrary
3087 			 * virtual addresses, take care of potential aliasing
3088 			 * before reading the folio on the kernel side.
3089 			 */
3090 			if (writably_mapped)
3091 				flush_dcache_folio(folio);
3092 
3093 			n = min_t(loff_t, len, isize - *ppos);
3094 			n = splice_folio_into_pipe(pipe, folio, *ppos, n);
3095 			if (!n)
3096 				goto out;
3097 			len -= n;
3098 			total_spliced += n;
3099 			*ppos += n;
3100 			in->f_ra.prev_pos = *ppos;
3101 			if (pipe_full(pipe->head, pipe->tail, pipe->max_usage))
3102 				goto out;
3103 		}
3104 
3105 		folio_batch_release(&fbatch);
3106 	} while (len);
3107 
3108 out:
3109 	folio_batch_release(&fbatch);
3110 	file_accessed(in);
3111 
3112 	return total_spliced ? total_spliced : error;
3113 }
3114 EXPORT_SYMBOL(filemap_splice_read);
3115 
folio_seek_hole_data(struct xa_state * xas,struct address_space * mapping,struct folio * folio,loff_t start,loff_t end,bool seek_data)3116 static inline loff_t folio_seek_hole_data(struct xa_state *xas,
3117 		struct address_space *mapping, struct folio *folio,
3118 		loff_t start, loff_t end, bool seek_data)
3119 {
3120 	const struct address_space_operations *ops = mapping->a_ops;
3121 	size_t offset, bsz = i_blocksize(mapping->host);
3122 
3123 	if (xa_is_value(folio) || folio_test_uptodate(folio))
3124 		return seek_data ? start : end;
3125 	if (!ops->is_partially_uptodate)
3126 		return seek_data ? end : start;
3127 
3128 	xas_pause(xas);
3129 	rcu_read_unlock();
3130 	folio_lock(folio);
3131 	if (unlikely(folio->mapping != mapping))
3132 		goto unlock;
3133 
3134 	offset = offset_in_folio(folio, start) & ~(bsz - 1);
3135 
3136 	do {
3137 		if (ops->is_partially_uptodate(folio, offset, bsz) ==
3138 							seek_data)
3139 			break;
3140 		start = (start + bsz) & ~((u64)bsz - 1);
3141 		offset += bsz;
3142 	} while (offset < folio_size(folio));
3143 unlock:
3144 	folio_unlock(folio);
3145 	rcu_read_lock();
3146 	return start;
3147 }
3148 
seek_folio_size(struct xa_state * xas,struct folio * folio)3149 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
3150 {
3151 	if (xa_is_value(folio))
3152 		return PAGE_SIZE << xas_get_order(xas);
3153 	return folio_size(folio);
3154 }
3155 
3156 /**
3157  * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
3158  * @mapping: Address space to search.
3159  * @start: First byte to consider.
3160  * @end: Limit of search (exclusive).
3161  * @whence: Either SEEK_HOLE or SEEK_DATA.
3162  *
3163  * If the page cache knows which blocks contain holes and which blocks
3164  * contain data, your filesystem can use this function to implement
3165  * SEEK_HOLE and SEEK_DATA.  This is useful for filesystems which are
3166  * entirely memory-based such as tmpfs, and filesystems which support
3167  * unwritten extents.
3168  *
3169  * Return: The requested offset on success, or -ENXIO if @whence specifies
3170  * SEEK_DATA and there is no data after @start.  There is an implicit hole
3171  * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
3172  * and @end contain data.
3173  */
mapping_seek_hole_data(struct address_space * mapping,loff_t start,loff_t end,int whence)3174 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
3175 		loff_t end, int whence)
3176 {
3177 	XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
3178 	pgoff_t max = (end - 1) >> PAGE_SHIFT;
3179 	bool seek_data = (whence == SEEK_DATA);
3180 	struct folio *folio;
3181 
3182 	if (end <= start)
3183 		return -ENXIO;
3184 
3185 	rcu_read_lock();
3186 	while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
3187 		loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
3188 		size_t seek_size;
3189 
3190 		if (start < pos) {
3191 			if (!seek_data)
3192 				goto unlock;
3193 			start = pos;
3194 		}
3195 
3196 		seek_size = seek_folio_size(&xas, folio);
3197 		pos = round_up((u64)pos + 1, seek_size);
3198 		start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
3199 				seek_data);
3200 		if (start < pos)
3201 			goto unlock;
3202 		if (start >= end)
3203 			break;
3204 		if (seek_size > PAGE_SIZE)
3205 			xas_set(&xas, pos >> PAGE_SHIFT);
3206 		if (!xa_is_value(folio))
3207 			folio_put(folio);
3208 	}
3209 	if (seek_data)
3210 		start = -ENXIO;
3211 unlock:
3212 	rcu_read_unlock();
3213 	if (folio && !xa_is_value(folio))
3214 		folio_put(folio);
3215 	if (start > end)
3216 		return end;
3217 	return start;
3218 }
3219 
3220 #ifdef CONFIG_MMU
3221 #define MMAP_LOTSAMISS  (100)
3222 /*
3223  * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
3224  * @vmf - the vm_fault for this fault.
3225  * @folio - the folio to lock.
3226  * @fpin - the pointer to the file we may pin (or is already pinned).
3227  *
3228  * This works similar to lock_folio_or_retry in that it can drop the
3229  * mmap_lock.  It differs in that it actually returns the folio locked
3230  * if it returns 1 and 0 if it couldn't lock the folio.  If we did have
3231  * to drop the mmap_lock then fpin will point to the pinned file and
3232  * needs to be fput()'ed at a later point.
3233  */
lock_folio_maybe_drop_mmap(struct vm_fault * vmf,struct folio * folio,struct file ** fpin)3234 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
3235 				     struct file **fpin)
3236 {
3237 	struct task_struct *tsk = NULL;
3238 
3239 	if (folio_trylock(folio))
3240 		return 1;
3241 
3242 	/*
3243 	 * NOTE! This will make us return with VM_FAULT_RETRY, but with
3244 	 * the fault lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
3245 	 * is supposed to work. We have way too many special cases..
3246 	 */
3247 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
3248 		return 0;
3249 
3250 	*fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
3251 	trace_android_vh_lock_folio_drop_mmap_start(&tsk, vmf, folio, *fpin);
3252 	if (vmf->flags & FAULT_FLAG_KILLABLE) {
3253 		if (__folio_lock_killable(folio)) {
3254 			/*
3255 			 * We didn't have the right flags to drop the
3256 			 * fault lock, but all fault_handlers only check
3257 			 * for fatal signals if we return VM_FAULT_RETRY,
3258 			 * so we need to drop the fault lock here and
3259 			 * return 0 if we don't have a fpin.
3260 			 */
3261 			if (*fpin == NULL)
3262 				release_fault_lock(vmf);
3263 			trace_android_vh_lock_folio_drop_mmap_end(false, &tsk, vmf, folio, *fpin);
3264 			return 0;
3265 		}
3266 	} else
3267 		__folio_lock(folio);
3268 
3269 	trace_android_vh_lock_folio_drop_mmap_end(true, &tsk, vmf, folio, *fpin);
3270 	return 1;
3271 }
3272 
3273 /*
3274  * Synchronous readahead happens when we don't even find a page in the page
3275  * cache at all.  We don't want to perform IO under the mmap sem, so if we have
3276  * to drop the mmap sem we return the file that was pinned in order for us to do
3277  * that.  If we didn't pin a file then we return NULL.  The file that is
3278  * returned needs to be fput()'ed when we're done with it.
3279  */
do_sync_mmap_readahead(struct vm_fault * vmf)3280 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
3281 {
3282 	struct file *file = vmf->vma->vm_file;
3283 	struct file_ra_state *ra = &file->f_ra;
3284 	struct address_space *mapping = file->f_mapping;
3285 	DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
3286 	struct file *fpin = NULL;
3287 	unsigned long vm_flags = vmf->vma->vm_flags;
3288 	unsigned int mmap_miss;
3289 
3290 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3291 	/* Use the readahead code, even if readahead is disabled */
3292 	if ((vm_flags & VM_HUGEPAGE) && HPAGE_PMD_ORDER <= MAX_PAGECACHE_ORDER) {
3293 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3294 		ractl._index &= ~((unsigned long)HPAGE_PMD_NR - 1);
3295 		ra->size = HPAGE_PMD_NR;
3296 		/*
3297 		 * Fetch two PMD folios, so we get the chance to actually
3298 		 * readahead, unless we've been told not to.
3299 		 */
3300 		if (!(vm_flags & VM_RAND_READ))
3301 			ra->size *= 2;
3302 		ra->async_size = HPAGE_PMD_NR;
3303 		page_cache_ra_order(&ractl, ra, HPAGE_PMD_ORDER);
3304 		return fpin;
3305 	}
3306 #endif
3307 
3308 	/* If we don't want any read-ahead, don't bother */
3309 	if (vm_flags & VM_RAND_READ)
3310 		return fpin;
3311 	if (!ra->ra_pages)
3312 		return fpin;
3313 
3314 	if (vm_flags & VM_SEQ_READ) {
3315 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3316 		trace_android_vh_page_cache_readahead_start(file, vmf->pgoff,
3317 				ra->ra_pages, true);
3318 		page_cache_sync_ra(&ractl, ra->ra_pages);
3319 		trace_android_vh_page_cache_readahead_end(file, vmf->pgoff);
3320 		return fpin;
3321 	}
3322 
3323 	/* Avoid banging the cache line if not needed */
3324 	mmap_miss = READ_ONCE(ra->mmap_miss);
3325 	if (mmap_miss < MMAP_LOTSAMISS * 10)
3326 		WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
3327 
3328 	/*
3329 	 * Do we miss much more than hit in this file? If so,
3330 	 * stop bothering with read-ahead. It will only hurt.
3331 	 */
3332 	if (mmap_miss > MMAP_LOTSAMISS)
3333 		return fpin;
3334 
3335 	/*
3336 	 * mmap read-around
3337 	 */
3338 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3339 	ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
3340 	ra->size = ra->ra_pages;
3341 	ra->async_size = ra->ra_pages / 4;
3342 	trace_android_vh_tune_mmap_readaround(ra->ra_pages, vmf->pgoff,
3343 			&ra->start, &ra->size, &ra->async_size);
3344 	ractl._index = ra->start;
3345 	trace_android_vh_page_cache_readahead_start(file, vmf->pgoff,
3346 			ra->size, true);
3347 	page_cache_ra_order(&ractl, ra, 0);
3348 	trace_android_vh_page_cache_readahead_end(file, vmf->pgoff);
3349 	return fpin;
3350 }
3351 
3352 /*
3353  * Asynchronous readahead happens when we find the page and PG_readahead,
3354  * so we want to possibly extend the readahead further.  We return the file that
3355  * was pinned if we have to drop the mmap_lock in order to do IO.
3356  */
do_async_mmap_readahead(struct vm_fault * vmf,struct folio * folio)3357 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
3358 					    struct folio *folio)
3359 {
3360 	struct file *file = vmf->vma->vm_file;
3361 	struct file_ra_state *ra = &file->f_ra;
3362 	DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
3363 	struct file *fpin = NULL;
3364 	unsigned int mmap_miss;
3365 	bool skip = false;
3366 
3367 	trace_android_vh_do_async_mmap_readahead(vmf, folio, &skip);
3368 	if (skip)
3369 		return fpin;
3370 
3371 	/* If we don't want any read-ahead, don't bother */
3372 	if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
3373 		return fpin;
3374 
3375 	mmap_miss = READ_ONCE(ra->mmap_miss);
3376 	if (mmap_miss)
3377 		WRITE_ONCE(ra->mmap_miss, --mmap_miss);
3378 
3379 	if (folio_test_readahead(folio)) {
3380 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3381 		trace_android_vh_page_cache_readahead_start(file, vmf->pgoff,
3382 				ra->ra_pages, false);
3383 		page_cache_async_ra(&ractl, folio, ra->ra_pages);
3384 		trace_android_vh_page_cache_readahead_end(file, vmf->pgoff);
3385 	}
3386 	return fpin;
3387 }
3388 
filemap_fault_recheck_pte_none(struct vm_fault * vmf)3389 static vm_fault_t filemap_fault_recheck_pte_none(struct vm_fault *vmf)
3390 {
3391 	struct vm_area_struct *vma = vmf->vma;
3392 	vm_fault_t ret = 0;
3393 	pte_t *ptep;
3394 
3395 	/*
3396 	 * We might have COW'ed a pagecache folio and might now have an mlocked
3397 	 * anon folio mapped. The original pagecache folio is not mlocked and
3398 	 * might have been evicted. During a read+clear/modify/write update of
3399 	 * the PTE, such as done in do_numa_page()/change_pte_range(), we
3400 	 * temporarily clear the PTE under PT lock and might detect it here as
3401 	 * "none" when not holding the PT lock.
3402 	 *
3403 	 * Not rechecking the PTE under PT lock could result in an unexpected
3404 	 * major fault in an mlock'ed region. Recheck only for this special
3405 	 * scenario while holding the PT lock, to not degrade non-mlocked
3406 	 * scenarios. Recheck the PTE without PT lock firstly, thereby reducing
3407 	 * the number of times we hold PT lock.
3408 	 */
3409 	if (!(vma->vm_flags & VM_LOCKED))
3410 		return 0;
3411 
3412 	if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID))
3413 		return 0;
3414 
3415 	ptep = pte_offset_map_ro_nolock(vma->vm_mm, vmf->pmd, vmf->address,
3416 					&vmf->ptl);
3417 	if (unlikely(!ptep))
3418 		return VM_FAULT_NOPAGE;
3419 
3420 	if (unlikely(!pte_none(ptep_get_lockless(ptep)))) {
3421 		ret = VM_FAULT_NOPAGE;
3422 	} else {
3423 		spin_lock(vmf->ptl);
3424 		if (unlikely(!pte_none(ptep_get(ptep))))
3425 			ret = VM_FAULT_NOPAGE;
3426 		spin_unlock(vmf->ptl);
3427 	}
3428 	pte_unmap(ptep);
3429 	return ret;
3430 }
3431 
3432 /**
3433  * filemap_fault - read in file data for page fault handling
3434  * @vmf:	struct vm_fault containing details of the fault
3435  *
3436  * filemap_fault() is invoked via the vma operations vector for a
3437  * mapped memory region to read in file data during a page fault.
3438  *
3439  * The goto's are kind of ugly, but this streamlines the normal case of having
3440  * it in the page cache, and handles the special cases reasonably without
3441  * having a lot of duplicated code.
3442  *
3443  * vma->vm_mm->mmap_lock must be held on entry.
3444  *
3445  * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
3446  * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
3447  *
3448  * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
3449  * has not been released.
3450  *
3451  * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3452  *
3453  * Return: bitwise-OR of %VM_FAULT_ codes.
3454  */
filemap_fault(struct vm_fault * vmf)3455 vm_fault_t filemap_fault(struct vm_fault *vmf)
3456 {
3457 	int error;
3458 	struct file *file = vmf->vma->vm_file;
3459 	struct file *fpin = NULL;
3460 	struct address_space *mapping = file->f_mapping;
3461 	struct inode *inode = mapping->host;
3462 	pgoff_t max_idx, index = vmf->pgoff;
3463 	struct folio *folio;
3464 	vm_fault_t ret = 0;
3465 	bool mapping_locked = false;
3466 
3467 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3468 	if (unlikely(index >= max_idx))
3469 		return VM_FAULT_SIGBUS;
3470 
3471 	trace_mm_filemap_fault(mapping, index);
3472 
3473 	/*
3474 	 * Do we have something in the page cache already?
3475 	 */
3476 	folio = filemap_get_folio(mapping, index);
3477 	if (likely(!IS_ERR(folio))) {
3478 		/*
3479 		 * We found the page, so try async readahead before waiting for
3480 		 * the lock.
3481 		 */
3482 		if (!(vmf->flags & FAULT_FLAG_TRIED))
3483 			fpin = do_async_mmap_readahead(vmf, folio);
3484 		if (unlikely(!folio_test_uptodate(folio))) {
3485 			filemap_invalidate_lock_shared(mapping);
3486 			mapping_locked = true;
3487 		}
3488 	} else {
3489 		ret = filemap_fault_recheck_pte_none(vmf);
3490 		if (unlikely(ret))
3491 			return ret;
3492 
3493 		/* No page in the page cache at all */
3494 		count_vm_event(PGMAJFAULT);
3495 		count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3496 		ret = VM_FAULT_MAJOR;
3497 		fpin = do_sync_mmap_readahead(vmf);
3498 retry_find:
3499 		/*
3500 		 * See comment in filemap_create_folio() why we need
3501 		 * invalidate_lock
3502 		 */
3503 		if (!mapping_locked) {
3504 			filemap_invalidate_lock_shared(mapping);
3505 			mapping_locked = true;
3506 		}
3507 		folio = __filemap_get_folio(mapping, index,
3508 					  FGP_CREAT|FGP_FOR_MMAP,
3509 					  vmf->gfp_mask);
3510 		if (IS_ERR(folio)) {
3511 			if (fpin)
3512 				goto out_retry;
3513 			filemap_invalidate_unlock_shared(mapping);
3514 			return VM_FAULT_OOM;
3515 		}
3516 	}
3517 
3518 	if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
3519 		goto out_retry;
3520 
3521 	/* Did it get truncated? */
3522 	if (unlikely(folio->mapping != mapping)) {
3523 		folio_unlock(folio);
3524 		folio_put(folio);
3525 		goto retry_find;
3526 	}
3527 	VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
3528 
3529 	/*
3530 	 * We have a locked folio in the page cache, now we need to check
3531 	 * that it's up-to-date. If not, it is going to be due to an error,
3532 	 * or because readahead was otherwise unable to retrieve it.
3533 	 */
3534 	if (unlikely(!folio_test_uptodate(folio))) {
3535 		/*
3536 		 * If the invalidate lock is not held, the folio was in cache
3537 		 * and uptodate and now it is not. Strange but possible since we
3538 		 * didn't hold the page lock all the time. Let's drop
3539 		 * everything, get the invalidate lock and try again.
3540 		 */
3541 		if (!mapping_locked) {
3542 			folio_unlock(folio);
3543 			folio_put(folio);
3544 			goto retry_find;
3545 		}
3546 
3547 		/*
3548 		 * OK, the folio is really not uptodate. This can be because the
3549 		 * VMA has the VM_RAND_READ flag set, or because an error
3550 		 * arose. Let's read it in directly.
3551 		 */
3552 		goto page_not_uptodate;
3553 	}
3554 
3555 	/*
3556 	 * We've made it this far and we had to drop our mmap_lock, now is the
3557 	 * time to return to the upper layer and have it re-find the vma and
3558 	 * redo the fault.
3559 	 */
3560 	if (fpin) {
3561 		folio_unlock(folio);
3562 		goto out_retry;
3563 	}
3564 	if (mapping_locked)
3565 		filemap_invalidate_unlock_shared(mapping);
3566 
3567 	/*
3568 	 * Found the page and have a reference on it.
3569 	 * We must recheck i_size under page lock.
3570 	 */
3571 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3572 	if (unlikely(index >= max_idx)) {
3573 		folio_unlock(folio);
3574 		folio_put(folio);
3575 		return VM_FAULT_SIGBUS;
3576 	}
3577 
3578 	vmf->page = folio_file_page(folio, index);
3579 	return ret | VM_FAULT_LOCKED;
3580 
3581 page_not_uptodate:
3582 	/*
3583 	 * Umm, take care of errors if the page isn't up-to-date.
3584 	 * Try to re-read it _once_. We do this synchronously,
3585 	 * because there really aren't any performance issues here
3586 	 * and we need to check for errors.
3587 	 */
3588 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3589 	trace_android_vh_filemap_fault_start(file, vmf->pgoff);
3590 	error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
3591 	trace_android_vh_filemap_fault_end(file, vmf->pgoff);
3592 	if (fpin)
3593 		goto out_retry;
3594 	folio_put(folio);
3595 
3596 	if (!error || error == AOP_TRUNCATED_PAGE)
3597 		goto retry_find;
3598 	filemap_invalidate_unlock_shared(mapping);
3599 
3600 	return VM_FAULT_SIGBUS;
3601 
3602 out_retry:
3603 	/*
3604 	 * We dropped the mmap_lock, we need to return to the fault handler to
3605 	 * re-find the vma and come back and find our hopefully still populated
3606 	 * page.
3607 	 */
3608 	if (!IS_ERR(folio))
3609 		folio_put(folio);
3610 	if (mapping_locked)
3611 		filemap_invalidate_unlock_shared(mapping);
3612 	if (fpin)
3613 		fput(fpin);
3614 	return ret | VM_FAULT_RETRY;
3615 }
3616 EXPORT_SYMBOL(filemap_fault);
3617 
filemap_map_pmd(struct vm_fault * vmf,struct folio * folio,pgoff_t start)3618 static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio,
3619 		pgoff_t start)
3620 {
3621 	struct mm_struct *mm = vmf->vma->vm_mm;
3622 
3623 	/* Huge page is mapped? No need to proceed. */
3624 	if (pmd_trans_huge(*vmf->pmd)) {
3625 		folio_unlock(folio);
3626 		folio_put(folio);
3627 		return true;
3628 	}
3629 
3630 	if (pmd_none(*vmf->pmd) && folio_test_pmd_mappable(folio)) {
3631 		struct page *page = folio_file_page(folio, start);
3632 		vm_fault_t ret = do_set_pmd(vmf, page);
3633 		if (!ret) {
3634 			/* The page is mapped successfully, reference consumed. */
3635 			folio_unlock(folio);
3636 			return true;
3637 		}
3638 	}
3639 
3640 	if (pmd_none(*vmf->pmd) && vmf->prealloc_pte)
3641 		pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3642 
3643 	return false;
3644 }
3645 
next_uptodate_folio(struct xa_state * xas,struct address_space * mapping,pgoff_t end_pgoff)3646 static struct folio *next_uptodate_folio(struct xa_state *xas,
3647 		struct address_space *mapping, pgoff_t end_pgoff)
3648 {
3649 	struct folio *folio = xas_next_entry(xas, end_pgoff);
3650 	unsigned long max_idx;
3651 
3652 	do {
3653 		if (!folio)
3654 			return NULL;
3655 		if (xas_retry(xas, folio))
3656 			continue;
3657 		if (xa_is_value(folio))
3658 			continue;
3659 		if (folio_test_locked(folio))
3660 			continue;
3661 		if (!folio_try_get(folio))
3662 			continue;
3663 		/* Has the page moved or been split? */
3664 		if (unlikely(folio != xas_reload(xas)))
3665 			goto skip;
3666 		if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3667 			goto skip;
3668 		if (!folio_trylock(folio))
3669 			goto skip;
3670 		if (folio->mapping != mapping)
3671 			goto unlock;
3672 		if (!folio_test_uptodate(folio))
3673 			goto unlock;
3674 		max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3675 		if (xas->xa_index >= max_idx)
3676 			goto unlock;
3677 		return folio;
3678 unlock:
3679 		folio_unlock(folio);
3680 skip:
3681 		folio_put(folio);
3682 	} while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3683 
3684 	return NULL;
3685 }
3686 
3687 /*
3688  * Map page range [start_page, start_page + nr_pages) of folio.
3689  * start_page is gotten from start by folio_page(folio, start)
3690  */
filemap_map_folio_range(struct vm_fault * vmf,struct folio * folio,unsigned long start,unsigned long addr,unsigned int nr_pages,unsigned long * rss,unsigned int * mmap_miss)3691 static vm_fault_t filemap_map_folio_range(struct vm_fault *vmf,
3692 			struct folio *folio, unsigned long start,
3693 			unsigned long addr, unsigned int nr_pages,
3694 			unsigned long *rss, unsigned int *mmap_miss)
3695 {
3696 	vm_fault_t ret = 0;
3697 	struct page *page = folio_page(folio, start);
3698 	unsigned int count = 0;
3699 	pte_t *old_ptep = vmf->pte;
3700 
3701 	do {
3702 		if (PageHWPoison(page + count))
3703 			goto skip;
3704 
3705 		/*
3706 		 * If there are too many folios that are recently evicted
3707 		 * in a file, they will probably continue to be evicted.
3708 		 * In such situation, read-ahead is only a waste of IO.
3709 		 * Don't decrease mmap_miss in this scenario to make sure
3710 		 * we can stop read-ahead.
3711 		 */
3712 		if (!folio_test_workingset(folio))
3713 			(*mmap_miss)++;
3714 
3715 		/*
3716 		 * NOTE: If there're PTE markers, we'll leave them to be
3717 		 * handled in the specific fault path, and it'll prohibit the
3718 		 * fault-around logic.
3719 		 */
3720 		if (!pte_none(ptep_get(&vmf->pte[count])))
3721 			goto skip;
3722 
3723 		count++;
3724 		continue;
3725 skip:
3726 		if (count) {
3727 			set_pte_range(vmf, folio, page, count, addr);
3728 			*rss += count;
3729 			folio_ref_add(folio, count);
3730 			if (in_range(vmf->address, addr, count * PAGE_SIZE))
3731 				ret = VM_FAULT_NOPAGE;
3732 		}
3733 
3734 		count++;
3735 		page += count;
3736 		vmf->pte += count;
3737 		addr += count * PAGE_SIZE;
3738 		count = 0;
3739 	} while (--nr_pages > 0);
3740 
3741 	if (count) {
3742 		set_pte_range(vmf, folio, page, count, addr);
3743 		*rss += count;
3744 		folio_ref_add(folio, count);
3745 		if (in_range(vmf->address, addr, count * PAGE_SIZE))
3746 			ret = VM_FAULT_NOPAGE;
3747 	}
3748 
3749 	vmf->pte = old_ptep;
3750 
3751 	return ret;
3752 }
3753 
filemap_map_order0_folio(struct vm_fault * vmf,struct folio * folio,unsigned long addr,unsigned long * rss,unsigned int * mmap_miss)3754 static vm_fault_t filemap_map_order0_folio(struct vm_fault *vmf,
3755 		struct folio *folio, unsigned long addr,
3756 		unsigned long *rss, unsigned int *mmap_miss)
3757 {
3758 	vm_fault_t ret = 0;
3759 	struct page *page = &folio->page;
3760 
3761 	if (PageHWPoison(page))
3762 		return ret;
3763 
3764 	/* See comment of filemap_map_folio_range() */
3765 	if (!folio_test_workingset(folio))
3766 		(*mmap_miss)++;
3767 
3768 	/*
3769 	 * NOTE: If there're PTE markers, we'll leave them to be
3770 	 * handled in the specific fault path, and it'll prohibit
3771 	 * the fault-around logic.
3772 	 */
3773 	if (!pte_none(ptep_get(vmf->pte)))
3774 		return ret;
3775 
3776 	if (vmf->address == addr)
3777 		ret = VM_FAULT_NOPAGE;
3778 
3779 	set_pte_range(vmf, folio, page, 1, addr);
3780 	(*rss)++;
3781 	folio_ref_inc(folio);
3782 
3783 	return ret;
3784 }
3785 
filemap_map_pages(struct vm_fault * vmf,pgoff_t start_pgoff,pgoff_t end_pgoff)3786 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3787 			     pgoff_t start_pgoff, pgoff_t end_pgoff)
3788 {
3789 	struct vm_area_struct *vma = vmf->vma;
3790 	struct file *file = vma->vm_file;
3791 	struct address_space *mapping = file->f_mapping;
3792 	pgoff_t file_end, last_pgoff = start_pgoff;
3793 	unsigned long addr;
3794 	XA_STATE(xas, &mapping->i_pages, start_pgoff);
3795 	struct folio *folio;
3796 	vm_fault_t ret = 0;
3797 	unsigned long rss = 0;
3798 	unsigned int nr_pages = 0, mmap_miss = 0, mmap_miss_saved, folio_type;
3799 	pgoff_t first_pgoff = 0;
3800 	pgoff_t orig_start_pgoff = start_pgoff;
3801 
3802 	rcu_read_lock();
3803 	folio = next_uptodate_folio(&xas, mapping, end_pgoff);
3804 	if (!folio)
3805 		goto out;
3806 	first_pgoff = xas.xa_index;
3807 	orig_start_pgoff = xas.xa_index;
3808 
3809 	if (filemap_map_pmd(vmf, folio, start_pgoff)) {
3810 		ret = VM_FAULT_NOPAGE;
3811 		goto out;
3812 	}
3813 
3814 	addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3815 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
3816 	if (!vmf->pte) {
3817 		folio_unlock(folio);
3818 		folio_put(folio);
3819 		goto out;
3820 	}
3821 
3822 	file_end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE) - 1;
3823 	if (end_pgoff > file_end)
3824 		end_pgoff = file_end;
3825 
3826 	folio_type = mm_counter_file(folio);
3827 	do {
3828 		unsigned long end;
3829 
3830 		addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3831 		vmf->pte += xas.xa_index - last_pgoff;
3832 		last_pgoff = xas.xa_index;
3833 		end = folio_next_index(folio) - 1;
3834 		nr_pages = min(end, end_pgoff) - xas.xa_index + 1;
3835 
3836 		if (!folio_test_large(folio))
3837 			ret |= filemap_map_order0_folio(vmf,
3838 					folio, addr, &rss, &mmap_miss);
3839 		else
3840 			ret |= filemap_map_folio_range(vmf, folio,
3841 					xas.xa_index - folio->index, addr,
3842 					nr_pages, &rss, &mmap_miss);
3843 
3844 		folio_unlock(folio);
3845 		folio_put(folio);
3846 	} while ((folio = next_uptodate_folio(&xas, mapping, end_pgoff)) != NULL);
3847 	add_mm_counter(vma->vm_mm, folio_type, rss);
3848 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3849 	trace_mm_filemap_map_pages(mapping, start_pgoff, end_pgoff);
3850 out:
3851 	rcu_read_unlock();
3852 
3853 	mmap_miss_saved = READ_ONCE(file->f_ra.mmap_miss);
3854 	if (mmap_miss >= mmap_miss_saved)
3855 		WRITE_ONCE(file->f_ra.mmap_miss, 0);
3856 	else
3857 		WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss_saved - mmap_miss);
3858 	trace_android_vh_filemap_map_pages(file, orig_start_pgoff,
3859 					first_pgoff, last_pgoff, ret);
3860 
3861 	return ret;
3862 }
3863 EXPORT_SYMBOL(filemap_map_pages);
3864 
filemap_page_mkwrite(struct vm_fault * vmf)3865 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3866 {
3867 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3868 	struct folio *folio = page_folio(vmf->page);
3869 	vm_fault_t ret = VM_FAULT_LOCKED;
3870 
3871 	sb_start_pagefault(mapping->host->i_sb);
3872 	file_update_time(vmf->vma->vm_file);
3873 	folio_lock(folio);
3874 	if (folio->mapping != mapping) {
3875 		folio_unlock(folio);
3876 		ret = VM_FAULT_NOPAGE;
3877 		goto out;
3878 	}
3879 	/*
3880 	 * We mark the folio dirty already here so that when freeze is in
3881 	 * progress, we are guaranteed that writeback during freezing will
3882 	 * see the dirty folio and writeprotect it again.
3883 	 */
3884 	folio_mark_dirty(folio);
3885 	folio_wait_stable(folio);
3886 out:
3887 	sb_end_pagefault(mapping->host->i_sb);
3888 	return ret;
3889 }
3890 
3891 const struct vm_operations_struct generic_file_vm_ops = {
3892 	.fault		= filemap_fault,
3893 	.map_pages	= filemap_map_pages,
3894 	.page_mkwrite	= filemap_page_mkwrite,
3895 };
3896 
3897 /* This is used for a general mmap of a disk file */
3898 
generic_file_mmap(struct file * file,struct vm_area_struct * vma)3899 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3900 {
3901 	struct address_space *mapping = file->f_mapping;
3902 
3903 	if (!mapping->a_ops->read_folio)
3904 		return -ENOEXEC;
3905 	file_accessed(file);
3906 	vma->vm_ops = &generic_file_vm_ops;
3907 	return 0;
3908 }
3909 
3910 /*
3911  * This is for filesystems which do not implement ->writepage.
3912  */
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)3913 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3914 {
3915 	if (vma_is_shared_maywrite(vma))
3916 		return -EINVAL;
3917 	return generic_file_mmap(file, vma);
3918 }
3919 #else
filemap_page_mkwrite(struct vm_fault * vmf)3920 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3921 {
3922 	return VM_FAULT_SIGBUS;
3923 }
generic_file_mmap(struct file * file,struct vm_area_struct * vma)3924 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3925 {
3926 	return -ENOSYS;
3927 }
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)3928 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3929 {
3930 	return -ENOSYS;
3931 }
3932 #endif /* CONFIG_MMU */
3933 
3934 EXPORT_SYMBOL(filemap_page_mkwrite);
3935 EXPORT_SYMBOL(generic_file_mmap);
3936 EXPORT_SYMBOL(generic_file_readonly_mmap);
3937 
do_read_cache_folio(struct address_space * mapping,pgoff_t index,filler_t filler,struct file * file,gfp_t gfp)3938 static struct folio *do_read_cache_folio(struct address_space *mapping,
3939 		pgoff_t index, filler_t filler, struct file *file, gfp_t gfp)
3940 {
3941 	struct folio *folio;
3942 	int err;
3943 
3944 	if (!filler)
3945 		filler = mapping->a_ops->read_folio;
3946 repeat:
3947 	folio = filemap_get_folio(mapping, index);
3948 	if (IS_ERR(folio)) {
3949 		folio = filemap_alloc_folio(gfp,
3950 					    mapping_min_folio_order(mapping));
3951 		if (!folio)
3952 			return ERR_PTR(-ENOMEM);
3953 		index = mapping_align_index(mapping, index);
3954 		err = filemap_add_folio(mapping, folio, index, gfp);
3955 		if (unlikely(err)) {
3956 			folio_put(folio);
3957 			if (err == -EEXIST)
3958 				goto repeat;
3959 			/* Presumably ENOMEM for xarray node */
3960 			return ERR_PTR(err);
3961 		}
3962 
3963 		goto filler;
3964 	}
3965 	if (folio_test_uptodate(folio))
3966 		goto out;
3967 
3968 	if (!folio_trylock(folio)) {
3969 		folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
3970 		goto repeat;
3971 	}
3972 
3973 	/* Folio was truncated from mapping */
3974 	if (!folio->mapping) {
3975 		folio_unlock(folio);
3976 		folio_put(folio);
3977 		goto repeat;
3978 	}
3979 
3980 	/* Someone else locked and filled the page in a very small window */
3981 	if (folio_test_uptodate(folio)) {
3982 		folio_unlock(folio);
3983 		goto out;
3984 	}
3985 
3986 filler:
3987 	err = filemap_read_folio(file, filler, folio);
3988 	if (err) {
3989 		folio_put(folio);
3990 		if (err == AOP_TRUNCATED_PAGE)
3991 			goto repeat;
3992 		return ERR_PTR(err);
3993 	}
3994 
3995 out:
3996 	folio_mark_accessed(folio);
3997 	return folio;
3998 }
3999 
4000 /**
4001  * read_cache_folio - Read into page cache, fill it if needed.
4002  * @mapping: The address_space to read from.
4003  * @index: The index to read.
4004  * @filler: Function to perform the read, or NULL to use aops->read_folio().
4005  * @file: Passed to filler function, may be NULL if not required.
4006  *
4007  * Read one page into the page cache.  If it succeeds, the folio returned
4008  * will contain @index, but it may not be the first page of the folio.
4009  *
4010  * If the filler function returns an error, it will be returned to the
4011  * caller.
4012  *
4013  * Context: May sleep.  Expects mapping->invalidate_lock to be held.
4014  * Return: An uptodate folio on success, ERR_PTR() on failure.
4015  */
read_cache_folio(struct address_space * mapping,pgoff_t index,filler_t filler,struct file * file)4016 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
4017 		filler_t filler, struct file *file)
4018 {
4019 	return do_read_cache_folio(mapping, index, filler, file,
4020 			mapping_gfp_mask(mapping));
4021 }
4022 EXPORT_SYMBOL(read_cache_folio);
4023 
4024 /**
4025  * mapping_read_folio_gfp - Read into page cache, using specified allocation flags.
4026  * @mapping:	The address_space for the folio.
4027  * @index:	The index that the allocated folio will contain.
4028  * @gfp:	The page allocator flags to use if allocating.
4029  *
4030  * This is the same as "read_cache_folio(mapping, index, NULL, NULL)", but with
4031  * any new memory allocations done using the specified allocation flags.
4032  *
4033  * The most likely error from this function is EIO, but ENOMEM is
4034  * possible and so is EINTR.  If ->read_folio returns another error,
4035  * that will be returned to the caller.
4036  *
4037  * The function expects mapping->invalidate_lock to be already held.
4038  *
4039  * Return: Uptodate folio on success, ERR_PTR() on failure.
4040  */
mapping_read_folio_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)4041 struct folio *mapping_read_folio_gfp(struct address_space *mapping,
4042 		pgoff_t index, gfp_t gfp)
4043 {
4044 	return do_read_cache_folio(mapping, index, NULL, NULL, gfp);
4045 }
4046 EXPORT_SYMBOL(mapping_read_folio_gfp);
4047 
do_read_cache_page(struct address_space * mapping,pgoff_t index,filler_t * filler,struct file * file,gfp_t gfp)4048 static struct page *do_read_cache_page(struct address_space *mapping,
4049 		pgoff_t index, filler_t *filler, struct file *file, gfp_t gfp)
4050 {
4051 	struct folio *folio;
4052 
4053 	folio = do_read_cache_folio(mapping, index, filler, file, gfp);
4054 	if (IS_ERR(folio))
4055 		return &folio->page;
4056 	return folio_file_page(folio, index);
4057 }
4058 
read_cache_page(struct address_space * mapping,pgoff_t index,filler_t * filler,struct file * file)4059 struct page *read_cache_page(struct address_space *mapping,
4060 			pgoff_t index, filler_t *filler, struct file *file)
4061 {
4062 	return do_read_cache_page(mapping, index, filler, file,
4063 			mapping_gfp_mask(mapping));
4064 }
4065 EXPORT_SYMBOL(read_cache_page);
4066 
4067 /**
4068  * read_cache_page_gfp - read into page cache, using specified page allocation flags.
4069  * @mapping:	the page's address_space
4070  * @index:	the page index
4071  * @gfp:	the page allocator flags to use if allocating
4072  *
4073  * This is the same as "read_mapping_page(mapping, index, NULL)", but with
4074  * any new page allocations done using the specified allocation flags.
4075  *
4076  * If the page does not get brought uptodate, return -EIO.
4077  *
4078  * The function expects mapping->invalidate_lock to be already held.
4079  *
4080  * Return: up to date page on success, ERR_PTR() on failure.
4081  */
read_cache_page_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)4082 struct page *read_cache_page_gfp(struct address_space *mapping,
4083 				pgoff_t index,
4084 				gfp_t gfp)
4085 {
4086 	return do_read_cache_page(mapping, index, NULL, NULL, gfp);
4087 }
4088 EXPORT_SYMBOL(read_cache_page_gfp);
4089 
4090 /*
4091  * Warn about a page cache invalidation failure during a direct I/O write.
4092  */
dio_warn_stale_pagecache(struct file * filp)4093 static void dio_warn_stale_pagecache(struct file *filp)
4094 {
4095 	static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
4096 	char pathname[128];
4097 	char *path;
4098 
4099 	errseq_set(&filp->f_mapping->wb_err, -EIO);
4100 	if (__ratelimit(&_rs)) {
4101 		path = file_path(filp, pathname, sizeof(pathname));
4102 		if (IS_ERR(path))
4103 			path = "(unknown)";
4104 		pr_crit("Page cache invalidation failure on direct I/O.  Possible data corruption due to collision with buffered I/O!\n");
4105 		pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
4106 			current->comm);
4107 	}
4108 }
4109 
kiocb_invalidate_post_direct_write(struct kiocb * iocb,size_t count)4110 void kiocb_invalidate_post_direct_write(struct kiocb *iocb, size_t count)
4111 {
4112 	struct address_space *mapping = iocb->ki_filp->f_mapping;
4113 
4114 	if (mapping->nrpages &&
4115 	    invalidate_inode_pages2_range(mapping,
4116 			iocb->ki_pos >> PAGE_SHIFT,
4117 			(iocb->ki_pos + count - 1) >> PAGE_SHIFT))
4118 		dio_warn_stale_pagecache(iocb->ki_filp);
4119 }
4120 
4121 ssize_t
generic_file_direct_write(struct kiocb * iocb,struct iov_iter * from)4122 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
4123 {
4124 	struct address_space *mapping = iocb->ki_filp->f_mapping;
4125 	size_t write_len = iov_iter_count(from);
4126 	ssize_t written;
4127 
4128 	/*
4129 	 * If a page can not be invalidated, return 0 to fall back
4130 	 * to buffered write.
4131 	 */
4132 	written = kiocb_invalidate_pages(iocb, write_len);
4133 	if (written) {
4134 		if (written == -EBUSY)
4135 			return 0;
4136 		return written;
4137 	}
4138 
4139 	written = mapping->a_ops->direct_IO(iocb, from);
4140 
4141 	/*
4142 	 * Finally, try again to invalidate clean pages which might have been
4143 	 * cached by non-direct readahead, or faulted in by get_user_pages()
4144 	 * if the source of the write was an mmap'ed region of the file
4145 	 * we're writing.  Either one is a pretty crazy thing to do,
4146 	 * so we don't support it 100%.  If this invalidation
4147 	 * fails, tough, the write still worked...
4148 	 *
4149 	 * Most of the time we do not need this since dio_complete() will do
4150 	 * the invalidation for us. However there are some file systems that
4151 	 * do not end up with dio_complete() being called, so let's not break
4152 	 * them by removing it completely.
4153 	 *
4154 	 * Noticeable example is a blkdev_direct_IO().
4155 	 *
4156 	 * Skip invalidation for async writes or if mapping has no pages.
4157 	 */
4158 	if (written > 0) {
4159 		struct inode *inode = mapping->host;
4160 		loff_t pos = iocb->ki_pos;
4161 
4162 		kiocb_invalidate_post_direct_write(iocb, written);
4163 		pos += written;
4164 		write_len -= written;
4165 		if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
4166 			i_size_write(inode, pos);
4167 			mark_inode_dirty(inode);
4168 		}
4169 		iocb->ki_pos = pos;
4170 	}
4171 	if (written != -EIOCBQUEUED)
4172 		iov_iter_revert(from, write_len - iov_iter_count(from));
4173 	return written;
4174 }
4175 EXPORT_SYMBOL(generic_file_direct_write);
4176 
generic_perform_write(struct kiocb * iocb,struct iov_iter * i)4177 ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i)
4178 {
4179 	struct file *file = iocb->ki_filp;
4180 	loff_t pos = iocb->ki_pos;
4181 	struct address_space *mapping = file->f_mapping;
4182 	const struct address_space_operations *a_ops = mapping->a_ops;
4183 	size_t chunk = mapping_max_folio_size(mapping);
4184 	long status = 0;
4185 	ssize_t written = 0;
4186 
4187 	do {
4188 		struct folio *folio;
4189 		size_t offset;		/* Offset into folio */
4190 		size_t bytes;		/* Bytes to write to folio */
4191 		size_t copied;		/* Bytes copied from user */
4192 		void *fsdata = NULL;
4193 
4194 		bytes = iov_iter_count(i);
4195 retry:
4196 		offset = pos & (chunk - 1);
4197 		bytes = min(chunk - offset, bytes);
4198 		balance_dirty_pages_ratelimited(mapping);
4199 
4200 		/*
4201 		 * Bring in the user page that we will copy from _first_.
4202 		 * Otherwise there's a nasty deadlock on copying from the
4203 		 * same page as we're writing to, without it being marked
4204 		 * up-to-date.
4205 		 */
4206 		if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
4207 			status = -EFAULT;
4208 			break;
4209 		}
4210 
4211 		if (fatal_signal_pending(current)) {
4212 			status = -EINTR;
4213 			break;
4214 		}
4215 
4216 		status = a_ops->write_begin(file, mapping, pos, bytes,
4217 						&folio, &fsdata);
4218 		if (unlikely(status < 0))
4219 			break;
4220 
4221 		offset = offset_in_folio(folio, pos);
4222 		if (bytes > folio_size(folio) - offset)
4223 			bytes = folio_size(folio) - offset;
4224 
4225 		if (mapping_writably_mapped(mapping))
4226 			flush_dcache_folio(folio);
4227 
4228 		copied = copy_folio_from_iter_atomic(folio, offset, bytes, i);
4229 		flush_dcache_folio(folio);
4230 
4231 		status = a_ops->write_end(file, mapping, pos, bytes, copied,
4232 						folio, fsdata);
4233 		if (unlikely(status != copied)) {
4234 			iov_iter_revert(i, copied - max(status, 0L));
4235 			if (unlikely(status < 0))
4236 				break;
4237 		}
4238 		trace_android_vh_io_statistics(mapping, folio->index, 1, false, false);
4239 		cond_resched();
4240 
4241 		if (unlikely(status == 0)) {
4242 			/*
4243 			 * A short copy made ->write_end() reject the
4244 			 * thing entirely.  Might be memory poisoning
4245 			 * halfway through, might be a race with munmap,
4246 			 * might be severe memory pressure.
4247 			 */
4248 			if (chunk > PAGE_SIZE)
4249 				chunk /= 2;
4250 			if (copied) {
4251 				bytes = copied;
4252 				goto retry;
4253 			}
4254 		} else {
4255 			pos += status;
4256 			written += status;
4257 		}
4258 	} while (iov_iter_count(i));
4259 
4260 	if (!written)
4261 		return status;
4262 	iocb->ki_pos += written;
4263 	return written;
4264 }
4265 EXPORT_SYMBOL(generic_perform_write);
4266 
4267 /**
4268  * __generic_file_write_iter - write data to a file
4269  * @iocb:	IO state structure (file, offset, etc.)
4270  * @from:	iov_iter with data to write
4271  *
4272  * This function does all the work needed for actually writing data to a
4273  * file. It does all basic checks, removes SUID from the file, updates
4274  * modification times and calls proper subroutines depending on whether we
4275  * do direct IO or a standard buffered write.
4276  *
4277  * It expects i_rwsem to be grabbed unless we work on a block device or similar
4278  * object which does not need locking at all.
4279  *
4280  * This function does *not* take care of syncing data in case of O_SYNC write.
4281  * A caller has to handle it. This is mainly due to the fact that we want to
4282  * avoid syncing under i_rwsem.
4283  *
4284  * Return:
4285  * * number of bytes written, even for truncated writes
4286  * * negative error code if no data has been written at all
4287  */
__generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)4288 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
4289 {
4290 	struct file *file = iocb->ki_filp;
4291 	struct address_space *mapping = file->f_mapping;
4292 	struct inode *inode = mapping->host;
4293 	ssize_t ret;
4294 
4295 	ret = file_remove_privs(file);
4296 	if (ret)
4297 		return ret;
4298 
4299 	ret = file_update_time(file);
4300 	if (ret)
4301 		return ret;
4302 
4303 	if (iocb->ki_flags & IOCB_DIRECT) {
4304 		ret = generic_file_direct_write(iocb, from);
4305 		/*
4306 		 * If the write stopped short of completing, fall back to
4307 		 * buffered writes.  Some filesystems do this for writes to
4308 		 * holes, for example.  For DAX files, a buffered write will
4309 		 * not succeed (even if it did, DAX does not handle dirty
4310 		 * page-cache pages correctly).
4311 		 */
4312 		if (ret < 0 || !iov_iter_count(from) || IS_DAX(inode))
4313 			return ret;
4314 		return direct_write_fallback(iocb, from, ret,
4315 				generic_perform_write(iocb, from));
4316 	}
4317 
4318 	return generic_perform_write(iocb, from);
4319 }
4320 EXPORT_SYMBOL(__generic_file_write_iter);
4321 
4322 /**
4323  * generic_file_write_iter - write data to a file
4324  * @iocb:	IO state structure
4325  * @from:	iov_iter with data to write
4326  *
4327  * This is a wrapper around __generic_file_write_iter() to be used by most
4328  * filesystems. It takes care of syncing the file in case of O_SYNC file
4329  * and acquires i_rwsem as needed.
4330  * Return:
4331  * * negative error code if no data has been written at all of
4332  *   vfs_fsync_range() failed for a synchronous write
4333  * * number of bytes written, even for truncated writes
4334  */
generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)4335 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
4336 {
4337 	struct file *file = iocb->ki_filp;
4338 	struct inode *inode = file->f_mapping->host;
4339 	ssize_t ret;
4340 
4341 	inode_lock(inode);
4342 	ret = generic_write_checks(iocb, from);
4343 	if (ret > 0)
4344 		ret = __generic_file_write_iter(iocb, from);
4345 	inode_unlock(inode);
4346 
4347 	if (ret > 0)
4348 		ret = generic_write_sync(iocb, ret);
4349 	return ret;
4350 }
4351 EXPORT_SYMBOL(generic_file_write_iter);
4352 
4353 /**
4354  * filemap_release_folio() - Release fs-specific metadata on a folio.
4355  * @folio: The folio which the kernel is trying to free.
4356  * @gfp: Memory allocation flags (and I/O mode).
4357  *
4358  * The address_space is trying to release any data attached to a folio
4359  * (presumably at folio->private).
4360  *
4361  * This will also be called if the private_2 flag is set on a page,
4362  * indicating that the folio has other metadata associated with it.
4363  *
4364  * The @gfp argument specifies whether I/O may be performed to release
4365  * this page (__GFP_IO), and whether the call may block
4366  * (__GFP_RECLAIM & __GFP_FS).
4367  *
4368  * Return: %true if the release was successful, otherwise %false.
4369  */
filemap_release_folio(struct folio * folio,gfp_t gfp)4370 bool filemap_release_folio(struct folio *folio, gfp_t gfp)
4371 {
4372 	struct address_space * const mapping = folio->mapping;
4373 
4374 	BUG_ON(!folio_test_locked(folio));
4375 	if (!folio_needs_release(folio))
4376 		return true;
4377 	if (folio_test_writeback(folio))
4378 		return false;
4379 
4380 	if (mapping && mapping->a_ops->release_folio)
4381 		return mapping->a_ops->release_folio(folio, gfp);
4382 	return try_to_free_buffers(folio);
4383 }
4384 EXPORT_SYMBOL(filemap_release_folio);
4385 
4386 /**
4387  * filemap_invalidate_inode - Invalidate/forcibly write back a range of an inode's pagecache
4388  * @inode: The inode to flush
4389  * @flush: Set to write back rather than simply invalidate.
4390  * @start: First byte to in range.
4391  * @end: Last byte in range (inclusive), or LLONG_MAX for everything from start
4392  *       onwards.
4393  *
4394  * Invalidate all the folios on an inode that contribute to the specified
4395  * range, possibly writing them back first.  Whilst the operation is
4396  * undertaken, the invalidate lock is held to prevent new folios from being
4397  * installed.
4398  */
filemap_invalidate_inode(struct inode * inode,bool flush,loff_t start,loff_t end)4399 int filemap_invalidate_inode(struct inode *inode, bool flush,
4400 			     loff_t start, loff_t end)
4401 {
4402 	struct address_space *mapping = inode->i_mapping;
4403 	pgoff_t first = start >> PAGE_SHIFT;
4404 	pgoff_t last = end >> PAGE_SHIFT;
4405 	pgoff_t nr = end == LLONG_MAX ? ULONG_MAX : last - first + 1;
4406 
4407 	if (!mapping || !mapping->nrpages || end < start)
4408 		goto out;
4409 
4410 	/* Prevent new folios from being added to the inode. */
4411 	filemap_invalidate_lock(mapping);
4412 
4413 	if (!mapping->nrpages)
4414 		goto unlock;
4415 
4416 	unmap_mapping_pages(mapping, first, nr, false);
4417 
4418 	/* Write back the data if we're asked to. */
4419 	if (flush) {
4420 		struct writeback_control wbc = {
4421 			.sync_mode	= WB_SYNC_ALL,
4422 			.nr_to_write	= LONG_MAX,
4423 			.range_start	= start,
4424 			.range_end	= end,
4425 		};
4426 
4427 		filemap_fdatawrite_wbc(mapping, &wbc);
4428 	}
4429 
4430 	/* Wait for writeback to complete on all folios and discard. */
4431 	invalidate_inode_pages2_range(mapping, start / PAGE_SIZE, end / PAGE_SIZE);
4432 
4433 unlock:
4434 	filemap_invalidate_unlock(mapping);
4435 out:
4436 	return filemap_check_errors(mapping);
4437 }
4438 EXPORT_SYMBOL_GPL(filemap_invalidate_inode);
4439 
4440 #ifdef CONFIG_CACHESTAT_SYSCALL
4441 /**
4442  * filemap_cachestat() - compute the page cache statistics of a mapping
4443  * @mapping:	The mapping to compute the statistics for.
4444  * @first_index:	The starting page cache index.
4445  * @last_index:	The final page index (inclusive).
4446  * @cs:	the cachestat struct to write the result to.
4447  *
4448  * This will query the page cache statistics of a mapping in the
4449  * page range of [first_index, last_index] (inclusive). The statistics
4450  * queried include: number of dirty pages, number of pages marked for
4451  * writeback, and the number of (recently) evicted pages.
4452  */
filemap_cachestat(struct address_space * mapping,pgoff_t first_index,pgoff_t last_index,struct cachestat * cs)4453 static void filemap_cachestat(struct address_space *mapping,
4454 		pgoff_t first_index, pgoff_t last_index, struct cachestat *cs)
4455 {
4456 	XA_STATE(xas, &mapping->i_pages, first_index);
4457 	struct folio *folio;
4458 
4459 	/* Flush stats (and potentially sleep) outside the RCU read section. */
4460 	mem_cgroup_flush_stats_ratelimited(NULL);
4461 
4462 	rcu_read_lock();
4463 	xas_for_each(&xas, folio, last_index) {
4464 		int order;
4465 		unsigned long nr_pages;
4466 		pgoff_t folio_first_index, folio_last_index;
4467 
4468 		/*
4469 		 * Don't deref the folio. It is not pinned, and might
4470 		 * get freed (and reused) underneath us.
4471 		 *
4472 		 * We *could* pin it, but that would be expensive for
4473 		 * what should be a fast and lightweight syscall.
4474 		 *
4475 		 * Instead, derive all information of interest from
4476 		 * the rcu-protected xarray.
4477 		 */
4478 
4479 		if (xas_retry(&xas, folio))
4480 			continue;
4481 
4482 		order = xas_get_order(&xas);
4483 		nr_pages = 1 << order;
4484 		folio_first_index = round_down(xas.xa_index, 1 << order);
4485 		folio_last_index = folio_first_index + nr_pages - 1;
4486 
4487 		/* Folios might straddle the range boundaries, only count covered pages */
4488 		if (folio_first_index < first_index)
4489 			nr_pages -= first_index - folio_first_index;
4490 
4491 		if (folio_last_index > last_index)
4492 			nr_pages -= folio_last_index - last_index;
4493 
4494 		if (xa_is_value(folio)) {
4495 			/* page is evicted */
4496 			void *shadow = (void *)folio;
4497 			bool workingset; /* not used */
4498 
4499 			cs->nr_evicted += nr_pages;
4500 
4501 #ifdef CONFIG_SWAP /* implies CONFIG_MMU */
4502 			if (shmem_mapping(mapping)) {
4503 				/* shmem file - in swap cache */
4504 				swp_entry_t swp = radix_to_swp_entry(folio);
4505 
4506 				/* swapin error results in poisoned entry */
4507 				if (non_swap_entry(swp))
4508 					goto resched;
4509 
4510 				/*
4511 				 * Getting a swap entry from the shmem
4512 				 * inode means we beat
4513 				 * shmem_unuse(). rcu_read_lock()
4514 				 * ensures swapoff waits for us before
4515 				 * freeing the swapper space. However,
4516 				 * we can race with swapping and
4517 				 * invalidation, so there might not be
4518 				 * a shadow in the swapcache (yet).
4519 				 */
4520 				shadow = get_shadow_from_swap_cache(swp);
4521 				if (!shadow)
4522 					goto resched;
4523 			}
4524 #endif
4525 			if (workingset_test_recent(shadow, true, &workingset, false))
4526 				cs->nr_recently_evicted += nr_pages;
4527 
4528 			goto resched;
4529 		}
4530 
4531 		/* page is in cache */
4532 		cs->nr_cache += nr_pages;
4533 
4534 		if (xas_get_mark(&xas, PAGECACHE_TAG_DIRTY))
4535 			cs->nr_dirty += nr_pages;
4536 
4537 		if (xas_get_mark(&xas, PAGECACHE_TAG_WRITEBACK))
4538 			cs->nr_writeback += nr_pages;
4539 
4540 resched:
4541 		if (need_resched()) {
4542 			xas_pause(&xas);
4543 			cond_resched_rcu();
4544 		}
4545 	}
4546 	rcu_read_unlock();
4547 
4548 	__adjust_cachestat_counters(cs);
4549 }
4550 
4551 /*
4552  * See mincore: reveal pagecache information only for files
4553  * that the calling process has write access to, or could (if
4554  * tried) open for writing.
4555  */
can_do_cachestat(struct file * f)4556 static inline bool can_do_cachestat(struct file *f)
4557 {
4558 	if (f->f_mode & FMODE_WRITE)
4559 		return true;
4560 	if (inode_owner_or_capable(file_mnt_idmap(f), file_inode(f)))
4561 		return true;
4562 	return file_permission(f, MAY_WRITE) == 0;
4563 }
4564 
4565 /*
4566  * The cachestat(2) system call.
4567  *
4568  * cachestat() returns the page cache statistics of a file in the
4569  * bytes range specified by `off` and `len`: number of cached pages,
4570  * number of dirty pages, number of pages marked for writeback,
4571  * number of evicted pages, and number of recently evicted pages.
4572  *
4573  * An evicted page is a page that is previously in the page cache
4574  * but has been evicted since. A page is recently evicted if its last
4575  * eviction was recent enough that its reentry to the cache would
4576  * indicate that it is actively being used by the system, and that
4577  * there is memory pressure on the system.
4578  *
4579  * `off` and `len` must be non-negative integers. If `len` > 0,
4580  * the queried range is [`off`, `off` + `len`]. If `len` == 0,
4581  * we will query in the range from `off` to the end of the file.
4582  *
4583  * The `flags` argument is unused for now, but is included for future
4584  * extensibility. User should pass 0 (i.e no flag specified).
4585  *
4586  * Currently, hugetlbfs is not supported.
4587  *
4588  * Because the status of a page can change after cachestat() checks it
4589  * but before it returns to the application, the returned values may
4590  * contain stale information.
4591  *
4592  * return values:
4593  *  zero        - success
4594  *  -EFAULT     - cstat or cstat_range points to an illegal address
4595  *  -EINVAL     - invalid flags
4596  *  -EBADF      - invalid file descriptor
4597  *  -EOPNOTSUPP - file descriptor is of a hugetlbfs file
4598  */
SYSCALL_DEFINE4(cachestat,unsigned int,fd,struct cachestat_range __user *,cstat_range,struct cachestat __user *,cstat,unsigned int,flags)4599 SYSCALL_DEFINE4(cachestat, unsigned int, fd,
4600 		struct cachestat_range __user *, cstat_range,
4601 		struct cachestat __user *, cstat, unsigned int, flags)
4602 {
4603 	struct fd f = fdget(fd);
4604 	struct address_space *mapping;
4605 	struct cachestat_range csr;
4606 	struct cachestat cs;
4607 	pgoff_t first_index, last_index;
4608 
4609 	if (!fd_file(f))
4610 		return -EBADF;
4611 
4612 	if (copy_from_user(&csr, cstat_range,
4613 			sizeof(struct cachestat_range))) {
4614 		fdput(f);
4615 		return -EFAULT;
4616 	}
4617 
4618 	/* hugetlbfs is not supported */
4619 	if (is_file_hugepages(fd_file(f))) {
4620 		fdput(f);
4621 		return -EOPNOTSUPP;
4622 	}
4623 
4624 	if (!can_do_cachestat(fd_file(f))) {
4625 		fdput(f);
4626 		return -EPERM;
4627 	}
4628 
4629 	if (flags != 0) {
4630 		fdput(f);
4631 		return -EINVAL;
4632 	}
4633 
4634 	first_index = csr.off >> PAGE_SHIFT;
4635 	last_index =
4636 		csr.len == 0 ? ULONG_MAX : (csr.off + csr.len - 1) >> PAGE_SHIFT;
4637 	memset(&cs, 0, sizeof(struct cachestat));
4638 	mapping = fd_file(f)->f_mapping;
4639 	filemap_cachestat(mapping, first_index, last_index, &cs);
4640 	fdput(f);
4641 
4642 	if (copy_to_user(cstat, &cs, sizeof(struct cachestat)))
4643 		return -EFAULT;
4644 
4645 	return 0;
4646 }
4647 #endif /* CONFIG_CACHESTAT_SYSCALL */
4648