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