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