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