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