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