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