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