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