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