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