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