xref: /linux/mm/filemap.c (revision f347c9d2697fcbbb64e077f7113a3887a181b8c0)
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/mman.h>
26 #include <linux/pagemap.h>
27 #include <linux/file.h>
28 #include <linux/uio.h>
29 #include <linux/error-injection.h>
30 #include <linux/hash.h>
31 #include <linux/writeback.h>
32 #include <linux/backing-dev.h>
33 #include <linux/pagevec.h>
34 #include <linux/security.h>
35 #include <linux/cpuset.h>
36 #include <linux/hugetlb.h>
37 #include <linux/memcontrol.h>
38 #include <linux/shmem_fs.h>
39 #include <linux/rmap.h>
40 #include <linux/delayacct.h>
41 #include <linux/psi.h>
42 #include <linux/ramfs.h>
43 #include <linux/page_idle.h>
44 #include <linux/migrate.h>
45 #include <asm/pgalloc.h>
46 #include <asm/tlbflush.h>
47 #include "internal.h"
48 
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/filemap.h>
51 
52 /*
53  * FIXME: remove all knowledge of the buffer layer from the core VM
54  */
55 #include <linux/buffer_head.h> /* for try_to_free_buffers */
56 
57 #include <asm/mman.h>
58 
59 /*
60  * Shared mappings implemented 30.11.1994. It's not fully working yet,
61  * though.
62  *
63  * Shared mappings now work. 15.8.1995  Bruno.
64  *
65  * finished 'unifying' the page and buffer cache and SMP-threaded the
66  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
67  *
68  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
69  */
70 
71 /*
72  * Lock ordering:
73  *
74  *  ->i_mmap_rwsem		(truncate_pagecache)
75  *    ->private_lock		(__free_pte->block_dirty_folio)
76  *      ->swap_lock		(exclusive_swap_page, others)
77  *        ->i_pages lock
78  *
79  *  ->i_rwsem
80  *    ->invalidate_lock		(acquired by fs in truncate path)
81  *      ->i_mmap_rwsem		(truncate->unmap_mapping_range)
82  *
83  *  ->mmap_lock
84  *    ->i_mmap_rwsem
85  *      ->page_table_lock or pte_lock	(various, mainly in memory.c)
86  *        ->i_pages lock	(arch-dependent flush_dcache_mmap_lock)
87  *
88  *  ->mmap_lock
89  *    ->invalidate_lock		(filemap_fault)
90  *      ->lock_page		(filemap_fault, access_process_vm)
91  *
92  *  ->i_rwsem			(generic_perform_write)
93  *    ->mmap_lock		(fault_in_readable->do_page_fault)
94  *
95  *  bdi->wb.list_lock
96  *    sb_lock			(fs/fs-writeback.c)
97  *    ->i_pages lock		(__sync_single_inode)
98  *
99  *  ->i_mmap_rwsem
100  *    ->anon_vma.lock		(vma_adjust)
101  *
102  *  ->anon_vma.lock
103  *    ->page_table_lock or pte_lock	(anon_vma_prepare and various)
104  *
105  *  ->page_table_lock or pte_lock
106  *    ->swap_lock		(try_to_unmap_one)
107  *    ->private_lock		(try_to_unmap_one)
108  *    ->i_pages lock		(try_to_unmap_one)
109  *    ->lruvec->lru_lock	(follow_page->mark_page_accessed)
110  *    ->lruvec->lru_lock	(check_pte_range->isolate_lru_page)
111  *    ->private_lock		(page_remove_rmap->set_page_dirty)
112  *    ->i_pages lock		(page_remove_rmap->set_page_dirty)
113  *    bdi.wb->list_lock		(page_remove_rmap->set_page_dirty)
114  *    ->inode->i_lock		(page_remove_rmap->set_page_dirty)
115  *    ->memcg->move_lock	(page_remove_rmap->lock_page_memcg)
116  *    bdi.wb->list_lock		(zap_pte_range->set_page_dirty)
117  *    ->inode->i_lock		(zap_pte_range->set_page_dirty)
118  *    ->private_lock		(zap_pte_range->block_dirty_folio)
119  *
120  * ->i_mmap_rwsem
121  *   ->tasklist_lock            (memory_failure, collect_procs_ao)
122  */
123 
124 static void page_cache_delete(struct address_space *mapping,
125 				   struct folio *folio, void *shadow)
126 {
127 	XA_STATE(xas, &mapping->i_pages, folio->index);
128 	long nr = 1;
129 
130 	mapping_set_update(&xas, mapping);
131 
132 	/* hugetlb pages are represented by a single entry in the xarray */
133 	if (!folio_test_hugetlb(folio)) {
134 		xas_set_order(&xas, folio->index, folio_order(folio));
135 		nr = folio_nr_pages(folio);
136 	}
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 
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 = page_mapcount(&folio->page);
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 				page_mapcount_reset(&folio->page);
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  */
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 
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) && !folio_test_hugetlb(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  */
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  */
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 
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 
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 
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  */
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  */
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 
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 
430 int filemap_fdatawrite(struct address_space *mapping)
431 {
432 	return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
433 }
434 EXPORT_SYMBOL(filemap_fdatawrite);
435 
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_flush - mostly a non-blocking flush
445  * @mapping:	target address_space
446  *
447  * This is a mostly non-blocking flush.  Not suitable for data-integrity
448  * purposes - I/O may not be started against all dirty pages.
449  *
450  * Return: %0 on success, negative error code otherwise.
451  */
452 int filemap_flush(struct address_space *mapping)
453 {
454 	return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
455 }
456 EXPORT_SYMBOL(filemap_flush);
457 
458 /**
459  * filemap_range_has_page - check if a page exists in range.
460  * @mapping:           address space within which to check
461  * @start_byte:        offset in bytes where the range starts
462  * @end_byte:          offset in bytes where the range ends (inclusive)
463  *
464  * Find at least one page in the range supplied, usually used to check if
465  * direct writing in this range will trigger a writeback.
466  *
467  * Return: %true if at least one page exists in the specified range,
468  * %false otherwise.
469  */
470 bool filemap_range_has_page(struct address_space *mapping,
471 			   loff_t start_byte, loff_t end_byte)
472 {
473 	struct page *page;
474 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
475 	pgoff_t max = end_byte >> PAGE_SHIFT;
476 
477 	if (end_byte < start_byte)
478 		return false;
479 
480 	rcu_read_lock();
481 	for (;;) {
482 		page = xas_find(&xas, max);
483 		if (xas_retry(&xas, page))
484 			continue;
485 		/* Shadow entries don't count */
486 		if (xa_is_value(page))
487 			continue;
488 		/*
489 		 * We don't need to try to pin this page; we're about to
490 		 * release the RCU lock anyway.  It is enough to know that
491 		 * there was a page here recently.
492 		 */
493 		break;
494 	}
495 	rcu_read_unlock();
496 
497 	return page != NULL;
498 }
499 EXPORT_SYMBOL(filemap_range_has_page);
500 
501 static void __filemap_fdatawait_range(struct address_space *mapping,
502 				     loff_t start_byte, loff_t end_byte)
503 {
504 	pgoff_t index = start_byte >> PAGE_SHIFT;
505 	pgoff_t end = end_byte >> PAGE_SHIFT;
506 	struct pagevec pvec;
507 	int nr_pages;
508 
509 	if (end_byte < start_byte)
510 		return;
511 
512 	pagevec_init(&pvec);
513 	while (index <= end) {
514 		unsigned i;
515 
516 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
517 				end, PAGECACHE_TAG_WRITEBACK);
518 		if (!nr_pages)
519 			break;
520 
521 		for (i = 0; i < nr_pages; i++) {
522 			struct page *page = pvec.pages[i];
523 
524 			wait_on_page_writeback(page);
525 			ClearPageError(page);
526 		}
527 		pagevec_release(&pvec);
528 		cond_resched();
529 	}
530 }
531 
532 /**
533  * filemap_fdatawait_range - wait for writeback to complete
534  * @mapping:		address space structure to wait for
535  * @start_byte:		offset in bytes where the range starts
536  * @end_byte:		offset in bytes where the range ends (inclusive)
537  *
538  * Walk the list of under-writeback pages of the given address space
539  * in the given range and wait for all of them.  Check error status of
540  * the address space and return it.
541  *
542  * Since the error status of the address space is cleared by this function,
543  * callers are responsible for checking the return value and handling and/or
544  * reporting the error.
545  *
546  * Return: error status of the address space.
547  */
548 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
549 			    loff_t end_byte)
550 {
551 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
552 	return filemap_check_errors(mapping);
553 }
554 EXPORT_SYMBOL(filemap_fdatawait_range);
555 
556 /**
557  * filemap_fdatawait_range_keep_errors - wait for writeback to complete
558  * @mapping:		address space structure to wait for
559  * @start_byte:		offset in bytes where the range starts
560  * @end_byte:		offset in bytes where the range ends (inclusive)
561  *
562  * Walk the list of under-writeback pages of the given address space in the
563  * given range and wait for all of them.  Unlike filemap_fdatawait_range(),
564  * this function does not clear error status of the address space.
565  *
566  * Use this function if callers don't handle errors themselves.  Expected
567  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
568  * fsfreeze(8)
569  */
570 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
571 		loff_t start_byte, loff_t end_byte)
572 {
573 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
574 	return filemap_check_and_keep_errors(mapping);
575 }
576 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
577 
578 /**
579  * file_fdatawait_range - wait for writeback to complete
580  * @file:		file pointing to address space structure to wait for
581  * @start_byte:		offset in bytes where the range starts
582  * @end_byte:		offset in bytes where the range ends (inclusive)
583  *
584  * Walk the list of under-writeback pages of the address space that file
585  * refers to, in the given range and wait for all of them.  Check error
586  * status of the address space vs. the file->f_wb_err cursor and return it.
587  *
588  * Since the error status of the file is advanced by this function,
589  * callers are responsible for checking the return value and handling and/or
590  * reporting the error.
591  *
592  * Return: error status of the address space vs. the file->f_wb_err cursor.
593  */
594 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
595 {
596 	struct address_space *mapping = file->f_mapping;
597 
598 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
599 	return file_check_and_advance_wb_err(file);
600 }
601 EXPORT_SYMBOL(file_fdatawait_range);
602 
603 /**
604  * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
605  * @mapping: address space structure to wait for
606  *
607  * Walk the list of under-writeback pages of the given address space
608  * and wait for all of them.  Unlike filemap_fdatawait(), this function
609  * does not clear error status of the address space.
610  *
611  * Use this function if callers don't handle errors themselves.  Expected
612  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
613  * fsfreeze(8)
614  *
615  * Return: error status of the address space.
616  */
617 int filemap_fdatawait_keep_errors(struct address_space *mapping)
618 {
619 	__filemap_fdatawait_range(mapping, 0, LLONG_MAX);
620 	return filemap_check_and_keep_errors(mapping);
621 }
622 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
623 
624 /* Returns true if writeback might be needed or already in progress. */
625 static bool mapping_needs_writeback(struct address_space *mapping)
626 {
627 	return mapping->nrpages;
628 }
629 
630 bool filemap_range_has_writeback(struct address_space *mapping,
631 				 loff_t start_byte, loff_t end_byte)
632 {
633 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
634 	pgoff_t max = end_byte >> PAGE_SHIFT;
635 	struct page *page;
636 
637 	if (end_byte < start_byte)
638 		return false;
639 
640 	rcu_read_lock();
641 	xas_for_each(&xas, page, max) {
642 		if (xas_retry(&xas, page))
643 			continue;
644 		if (xa_is_value(page))
645 			continue;
646 		if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
647 			break;
648 	}
649 	rcu_read_unlock();
650 	return page != NULL;
651 }
652 EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
653 
654 /**
655  * filemap_write_and_wait_range - write out & wait on a file range
656  * @mapping:	the address_space for the pages
657  * @lstart:	offset in bytes where the range starts
658  * @lend:	offset in bytes where the range ends (inclusive)
659  *
660  * Write out and wait upon file offsets lstart->lend, inclusive.
661  *
662  * Note that @lend is inclusive (describes the last byte to be written) so
663  * that this function can be used to write to the very end-of-file (end = -1).
664  *
665  * Return: error status of the address space.
666  */
667 int filemap_write_and_wait_range(struct address_space *mapping,
668 				 loff_t lstart, loff_t lend)
669 {
670 	int err = 0, err2;
671 
672 	if (mapping_needs_writeback(mapping)) {
673 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
674 						 WB_SYNC_ALL);
675 		/*
676 		 * Even if the above returned error, the pages may be
677 		 * written partially (e.g. -ENOSPC), so we wait for it.
678 		 * But the -EIO is special case, it may indicate the worst
679 		 * thing (e.g. bug) happened, so we avoid waiting for it.
680 		 */
681 		if (err != -EIO)
682 			__filemap_fdatawait_range(mapping, lstart, lend);
683 	}
684 	err2 = filemap_check_errors(mapping);
685 	if (!err)
686 		err = err2;
687 	return err;
688 }
689 EXPORT_SYMBOL(filemap_write_and_wait_range);
690 
691 void __filemap_set_wb_err(struct address_space *mapping, int err)
692 {
693 	errseq_t eseq = errseq_set(&mapping->wb_err, err);
694 
695 	trace_filemap_set_wb_err(mapping, eseq);
696 }
697 EXPORT_SYMBOL(__filemap_set_wb_err);
698 
699 /**
700  * file_check_and_advance_wb_err - report wb error (if any) that was previously
701  * 				   and advance wb_err to current one
702  * @file: struct file on which the error is being reported
703  *
704  * When userland calls fsync (or something like nfsd does the equivalent), we
705  * want to report any writeback errors that occurred since the last fsync (or
706  * since the file was opened if there haven't been any).
707  *
708  * Grab the wb_err from the mapping. If it matches what we have in the file,
709  * then just quickly return 0. The file is all caught up.
710  *
711  * If it doesn't match, then take the mapping value, set the "seen" flag in
712  * it and try to swap it into place. If it works, or another task beat us
713  * to it with the new value, then update the f_wb_err and return the error
714  * portion. The error at this point must be reported via proper channels
715  * (a'la fsync, or NFS COMMIT operation, etc.).
716  *
717  * While we handle mapping->wb_err with atomic operations, the f_wb_err
718  * value is protected by the f_lock since we must ensure that it reflects
719  * the latest value swapped in for this file descriptor.
720  *
721  * Return: %0 on success, negative error code otherwise.
722  */
723 int file_check_and_advance_wb_err(struct file *file)
724 {
725 	int err = 0;
726 	errseq_t old = READ_ONCE(file->f_wb_err);
727 	struct address_space *mapping = file->f_mapping;
728 
729 	/* Locklessly handle the common case where nothing has changed */
730 	if (errseq_check(&mapping->wb_err, old)) {
731 		/* Something changed, must use slow path */
732 		spin_lock(&file->f_lock);
733 		old = file->f_wb_err;
734 		err = errseq_check_and_advance(&mapping->wb_err,
735 						&file->f_wb_err);
736 		trace_file_check_and_advance_wb_err(file, old);
737 		spin_unlock(&file->f_lock);
738 	}
739 
740 	/*
741 	 * We're mostly using this function as a drop in replacement for
742 	 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
743 	 * that the legacy code would have had on these flags.
744 	 */
745 	clear_bit(AS_EIO, &mapping->flags);
746 	clear_bit(AS_ENOSPC, &mapping->flags);
747 	return err;
748 }
749 EXPORT_SYMBOL(file_check_and_advance_wb_err);
750 
751 /**
752  * file_write_and_wait_range - write out & wait on a file range
753  * @file:	file pointing to address_space with pages
754  * @lstart:	offset in bytes where the range starts
755  * @lend:	offset in bytes where the range ends (inclusive)
756  *
757  * Write out and wait upon file offsets lstart->lend, inclusive.
758  *
759  * Note that @lend is inclusive (describes the last byte to be written) so
760  * that this function can be used to write to the very end-of-file (end = -1).
761  *
762  * After writing out and waiting on the data, we check and advance the
763  * f_wb_err cursor to the latest value, and return any errors detected there.
764  *
765  * Return: %0 on success, negative error code otherwise.
766  */
767 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
768 {
769 	int err = 0, err2;
770 	struct address_space *mapping = file->f_mapping;
771 
772 	if (mapping_needs_writeback(mapping)) {
773 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
774 						 WB_SYNC_ALL);
775 		/* See comment of filemap_write_and_wait() */
776 		if (err != -EIO)
777 			__filemap_fdatawait_range(mapping, lstart, lend);
778 	}
779 	err2 = file_check_and_advance_wb_err(file);
780 	if (!err)
781 		err = err2;
782 	return err;
783 }
784 EXPORT_SYMBOL(file_write_and_wait_range);
785 
786 /**
787  * replace_page_cache_page - replace a pagecache page with a new one
788  * @old:	page to be replaced
789  * @new:	page to replace with
790  *
791  * This function replaces a page in the pagecache with a new one.  On
792  * success it acquires the pagecache reference for the new page and
793  * drops it for the old page.  Both the old and new pages must be
794  * locked.  This function does not add the new page to the LRU, the
795  * caller must do that.
796  *
797  * The remove + add is atomic.  This function cannot fail.
798  */
799 void replace_page_cache_page(struct page *old, struct page *new)
800 {
801 	struct folio *fold = page_folio(old);
802 	struct folio *fnew = page_folio(new);
803 	struct address_space *mapping = old->mapping;
804 	void (*free_folio)(struct folio *) = mapping->a_ops->free_folio;
805 	pgoff_t offset = old->index;
806 	XA_STATE(xas, &mapping->i_pages, offset);
807 
808 	VM_BUG_ON_PAGE(!PageLocked(old), old);
809 	VM_BUG_ON_PAGE(!PageLocked(new), new);
810 	VM_BUG_ON_PAGE(new->mapping, new);
811 
812 	get_page(new);
813 	new->mapping = mapping;
814 	new->index = offset;
815 
816 	mem_cgroup_migrate(fold, fnew);
817 
818 	xas_lock_irq(&xas);
819 	xas_store(&xas, new);
820 
821 	old->mapping = NULL;
822 	/* hugetlb pages do not participate in page cache accounting. */
823 	if (!PageHuge(old))
824 		__dec_lruvec_page_state(old, NR_FILE_PAGES);
825 	if (!PageHuge(new))
826 		__inc_lruvec_page_state(new, NR_FILE_PAGES);
827 	if (PageSwapBacked(old))
828 		__dec_lruvec_page_state(old, NR_SHMEM);
829 	if (PageSwapBacked(new))
830 		__inc_lruvec_page_state(new, NR_SHMEM);
831 	xas_unlock_irq(&xas);
832 	if (free_folio)
833 		free_folio(fold);
834 	folio_put(fold);
835 }
836 EXPORT_SYMBOL_GPL(replace_page_cache_page);
837 
838 noinline int __filemap_add_folio(struct address_space *mapping,
839 		struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
840 {
841 	XA_STATE(xas, &mapping->i_pages, index);
842 	int huge = folio_test_hugetlb(folio);
843 	bool charged = false;
844 	long nr = 1;
845 
846 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
847 	VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
848 	mapping_set_update(&xas, mapping);
849 
850 	if (!huge) {
851 		int error = mem_cgroup_charge(folio, NULL, gfp);
852 		VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
853 		if (error)
854 			return error;
855 		charged = true;
856 		xas_set_order(&xas, index, folio_order(folio));
857 		nr = folio_nr_pages(folio);
858 	}
859 
860 	gfp &= GFP_RECLAIM_MASK;
861 	folio_ref_add(folio, nr);
862 	folio->mapping = mapping;
863 	folio->index = xas.xa_index;
864 
865 	do {
866 		unsigned int order = xa_get_order(xas.xa, xas.xa_index);
867 		void *entry, *old = NULL;
868 
869 		if (order > folio_order(folio))
870 			xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
871 					order, gfp);
872 		xas_lock_irq(&xas);
873 		xas_for_each_conflict(&xas, entry) {
874 			old = entry;
875 			if (!xa_is_value(entry)) {
876 				xas_set_err(&xas, -EEXIST);
877 				goto unlock;
878 			}
879 		}
880 
881 		if (old) {
882 			if (shadowp)
883 				*shadowp = old;
884 			/* entry may have been split before we acquired lock */
885 			order = xa_get_order(xas.xa, xas.xa_index);
886 			if (order > folio_order(folio)) {
887 				/* How to handle large swap entries? */
888 				BUG_ON(shmem_mapping(mapping));
889 				xas_split(&xas, old, order);
890 				xas_reset(&xas);
891 			}
892 		}
893 
894 		xas_store(&xas, folio);
895 		if (xas_error(&xas))
896 			goto unlock;
897 
898 		mapping->nrpages += nr;
899 
900 		/* hugetlb pages do not participate in page cache accounting */
901 		if (!huge) {
902 			__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
903 			if (folio_test_pmd_mappable(folio))
904 				__lruvec_stat_mod_folio(folio,
905 						NR_FILE_THPS, nr);
906 		}
907 unlock:
908 		xas_unlock_irq(&xas);
909 	} while (xas_nomem(&xas, gfp));
910 
911 	if (xas_error(&xas))
912 		goto error;
913 
914 	trace_mm_filemap_add_to_page_cache(folio);
915 	return 0;
916 error:
917 	if (charged)
918 		mem_cgroup_uncharge(folio);
919 	folio->mapping = NULL;
920 	/* Leave page->index set: truncation relies upon it */
921 	folio_put_refs(folio, nr);
922 	return xas_error(&xas);
923 }
924 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
925 
926 int filemap_add_folio(struct address_space *mapping, struct folio *folio,
927 				pgoff_t index, gfp_t gfp)
928 {
929 	void *shadow = NULL;
930 	int ret;
931 
932 	__folio_set_locked(folio);
933 	ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
934 	if (unlikely(ret))
935 		__folio_clear_locked(folio);
936 	else {
937 		/*
938 		 * The folio might have been evicted from cache only
939 		 * recently, in which case it should be activated like
940 		 * any other repeatedly accessed folio.
941 		 * The exception is folios getting rewritten; evicting other
942 		 * data from the working set, only to cache data that will
943 		 * get overwritten with something else, is a waste of memory.
944 		 */
945 		WARN_ON_ONCE(folio_test_active(folio));
946 		if (!(gfp & __GFP_WRITE) && shadow)
947 			workingset_refault(folio, shadow);
948 		folio_add_lru(folio);
949 	}
950 	return ret;
951 }
952 EXPORT_SYMBOL_GPL(filemap_add_folio);
953 
954 #ifdef CONFIG_NUMA
955 struct folio *filemap_alloc_folio(gfp_t gfp, unsigned int order)
956 {
957 	int n;
958 	struct folio *folio;
959 
960 	if (cpuset_do_page_mem_spread()) {
961 		unsigned int cpuset_mems_cookie;
962 		do {
963 			cpuset_mems_cookie = read_mems_allowed_begin();
964 			n = cpuset_mem_spread_node();
965 			folio = __folio_alloc_node(gfp, order, n);
966 		} while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
967 
968 		return folio;
969 	}
970 	return folio_alloc(gfp, order);
971 }
972 EXPORT_SYMBOL(filemap_alloc_folio);
973 #endif
974 
975 /*
976  * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
977  *
978  * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
979  *
980  * @mapping1: the first mapping to lock
981  * @mapping2: the second mapping to lock
982  */
983 void filemap_invalidate_lock_two(struct address_space *mapping1,
984 				 struct address_space *mapping2)
985 {
986 	if (mapping1 > mapping2)
987 		swap(mapping1, mapping2);
988 	if (mapping1)
989 		down_write(&mapping1->invalidate_lock);
990 	if (mapping2 && mapping1 != mapping2)
991 		down_write_nested(&mapping2->invalidate_lock, 1);
992 }
993 EXPORT_SYMBOL(filemap_invalidate_lock_two);
994 
995 /*
996  * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
997  *
998  * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
999  *
1000  * @mapping1: the first mapping to unlock
1001  * @mapping2: the second mapping to unlock
1002  */
1003 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1004 				   struct address_space *mapping2)
1005 {
1006 	if (mapping1)
1007 		up_write(&mapping1->invalidate_lock);
1008 	if (mapping2 && mapping1 != mapping2)
1009 		up_write(&mapping2->invalidate_lock);
1010 }
1011 EXPORT_SYMBOL(filemap_invalidate_unlock_two);
1012 
1013 /*
1014  * In order to wait for pages to become available there must be
1015  * waitqueues associated with pages. By using a hash table of
1016  * waitqueues where the bucket discipline is to maintain all
1017  * waiters on the same queue and wake all when any of the pages
1018  * become available, and for the woken contexts to check to be
1019  * sure the appropriate page became available, this saves space
1020  * at a cost of "thundering herd" phenomena during rare hash
1021  * collisions.
1022  */
1023 #define PAGE_WAIT_TABLE_BITS 8
1024 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1025 static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1026 
1027 static wait_queue_head_t *folio_waitqueue(struct folio *folio)
1028 {
1029 	return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
1030 }
1031 
1032 void __init pagecache_init(void)
1033 {
1034 	int i;
1035 
1036 	for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1037 		init_waitqueue_head(&folio_wait_table[i]);
1038 
1039 	page_writeback_init();
1040 }
1041 
1042 /*
1043  * The page wait code treats the "wait->flags" somewhat unusually, because
1044  * we have multiple different kinds of waits, not just the usual "exclusive"
1045  * one.
1046  *
1047  * We have:
1048  *
1049  *  (a) no special bits set:
1050  *
1051  *	We're just waiting for the bit to be released, and when a waker
1052  *	calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1053  *	and remove it from the wait queue.
1054  *
1055  *	Simple and straightforward.
1056  *
1057  *  (b) WQ_FLAG_EXCLUSIVE:
1058  *
1059  *	The waiter is waiting to get the lock, and only one waiter should
1060  *	be woken up to avoid any thundering herd behavior. We'll set the
1061  *	WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1062  *
1063  *	This is the traditional exclusive wait.
1064  *
1065  *  (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
1066  *
1067  *	The waiter is waiting to get the bit, and additionally wants the
1068  *	lock to be transferred to it for fair lock behavior. If the lock
1069  *	cannot be taken, we stop walking the wait queue without waking
1070  *	the waiter.
1071  *
1072  *	This is the "fair lock handoff" case, and in addition to setting
1073  *	WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1074  *	that it now has the lock.
1075  */
1076 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
1077 {
1078 	unsigned int flags;
1079 	struct wait_page_key *key = arg;
1080 	struct wait_page_queue *wait_page
1081 		= container_of(wait, struct wait_page_queue, wait);
1082 
1083 	if (!wake_page_match(wait_page, key))
1084 		return 0;
1085 
1086 	/*
1087 	 * If it's a lock handoff wait, we get the bit for it, and
1088 	 * stop walking (and do not wake it up) if we can't.
1089 	 */
1090 	flags = wait->flags;
1091 	if (flags & WQ_FLAG_EXCLUSIVE) {
1092 		if (test_bit(key->bit_nr, &key->folio->flags))
1093 			return -1;
1094 		if (flags & WQ_FLAG_CUSTOM) {
1095 			if (test_and_set_bit(key->bit_nr, &key->folio->flags))
1096 				return -1;
1097 			flags |= WQ_FLAG_DONE;
1098 		}
1099 	}
1100 
1101 	/*
1102 	 * We are holding the wait-queue lock, but the waiter that
1103 	 * is waiting for this will be checking the flags without
1104 	 * any locking.
1105 	 *
1106 	 * So update the flags atomically, and wake up the waiter
1107 	 * afterwards to avoid any races. This store-release pairs
1108 	 * with the load-acquire in folio_wait_bit_common().
1109 	 */
1110 	smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
1111 	wake_up_state(wait->private, mode);
1112 
1113 	/*
1114 	 * Ok, we have successfully done what we're waiting for,
1115 	 * and we can unconditionally remove the wait entry.
1116 	 *
1117 	 * Note that this pairs with the "finish_wait()" in the
1118 	 * waiter, and has to be the absolute last thing we do.
1119 	 * After this list_del_init(&wait->entry) the wait entry
1120 	 * might be de-allocated and the process might even have
1121 	 * exited.
1122 	 */
1123 	list_del_init_careful(&wait->entry);
1124 	return (flags & WQ_FLAG_EXCLUSIVE) != 0;
1125 }
1126 
1127 static void folio_wake_bit(struct folio *folio, int bit_nr)
1128 {
1129 	wait_queue_head_t *q = folio_waitqueue(folio);
1130 	struct wait_page_key key;
1131 	unsigned long flags;
1132 	wait_queue_entry_t bookmark;
1133 
1134 	key.folio = folio;
1135 	key.bit_nr = bit_nr;
1136 	key.page_match = 0;
1137 
1138 	bookmark.flags = 0;
1139 	bookmark.private = NULL;
1140 	bookmark.func = NULL;
1141 	INIT_LIST_HEAD(&bookmark.entry);
1142 
1143 	spin_lock_irqsave(&q->lock, flags);
1144 	__wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1145 
1146 	while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1147 		/*
1148 		 * Take a breather from holding the lock,
1149 		 * allow pages that finish wake up asynchronously
1150 		 * to acquire the lock and remove themselves
1151 		 * from wait queue
1152 		 */
1153 		spin_unlock_irqrestore(&q->lock, flags);
1154 		cpu_relax();
1155 		spin_lock_irqsave(&q->lock, flags);
1156 		__wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1157 	}
1158 
1159 	/*
1160 	 * It's possible to miss clearing waiters here, when we woke our page
1161 	 * waiters, but the hashed waitqueue has waiters for other pages on it.
1162 	 * That's okay, it's a rare case. The next waker will clear it.
1163 	 *
1164 	 * Note that, depending on the page pool (buddy, hugetlb, ZONE_DEVICE,
1165 	 * other), the flag may be cleared in the course of freeing the page;
1166 	 * but that is not required for correctness.
1167 	 */
1168 	if (!waitqueue_active(q) || !key.page_match)
1169 		folio_clear_waiters(folio);
1170 
1171 	spin_unlock_irqrestore(&q->lock, flags);
1172 }
1173 
1174 static void folio_wake(struct folio *folio, int bit)
1175 {
1176 	if (!folio_test_waiters(folio))
1177 		return;
1178 	folio_wake_bit(folio, bit);
1179 }
1180 
1181 /*
1182  * A choice of three behaviors for folio_wait_bit_common():
1183  */
1184 enum behavior {
1185 	EXCLUSIVE,	/* Hold ref to page and take the bit when woken, like
1186 			 * __folio_lock() waiting on then setting PG_locked.
1187 			 */
1188 	SHARED,		/* Hold ref to page and check the bit when woken, like
1189 			 * folio_wait_writeback() waiting on PG_writeback.
1190 			 */
1191 	DROP,		/* Drop ref to page before wait, no check when woken,
1192 			 * like folio_put_wait_locked() on PG_locked.
1193 			 */
1194 };
1195 
1196 /*
1197  * Attempt to check (or get) the folio flag, and mark us done
1198  * if successful.
1199  */
1200 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
1201 					struct wait_queue_entry *wait)
1202 {
1203 	if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1204 		if (test_and_set_bit(bit_nr, &folio->flags))
1205 			return false;
1206 	} else if (test_bit(bit_nr, &folio->flags))
1207 		return false;
1208 
1209 	wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
1210 	return true;
1211 }
1212 
1213 /* How many times do we accept lock stealing from under a waiter? */
1214 int sysctl_page_lock_unfairness = 5;
1215 
1216 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1217 		int state, enum behavior behavior)
1218 {
1219 	wait_queue_head_t *q = folio_waitqueue(folio);
1220 	int unfairness = sysctl_page_lock_unfairness;
1221 	struct wait_page_queue wait_page;
1222 	wait_queue_entry_t *wait = &wait_page.wait;
1223 	bool thrashing = false;
1224 	unsigned long pflags;
1225 
1226 	if (bit_nr == PG_locked &&
1227 	    !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1228 		delayacct_thrashing_start();
1229 		psi_memstall_enter(&pflags);
1230 		thrashing = true;
1231 	}
1232 
1233 	init_wait(wait);
1234 	wait->func = wake_page_function;
1235 	wait_page.folio = folio;
1236 	wait_page.bit_nr = bit_nr;
1237 
1238 repeat:
1239 	wait->flags = 0;
1240 	if (behavior == EXCLUSIVE) {
1241 		wait->flags = WQ_FLAG_EXCLUSIVE;
1242 		if (--unfairness < 0)
1243 			wait->flags |= WQ_FLAG_CUSTOM;
1244 	}
1245 
1246 	/*
1247 	 * Do one last check whether we can get the
1248 	 * page bit synchronously.
1249 	 *
1250 	 * Do the folio_set_waiters() marking before that
1251 	 * to let any waker we _just_ missed know they
1252 	 * need to wake us up (otherwise they'll never
1253 	 * even go to the slow case that looks at the
1254 	 * page queue), and add ourselves to the wait
1255 	 * queue if we need to sleep.
1256 	 *
1257 	 * This part needs to be done under the queue
1258 	 * lock to avoid races.
1259 	 */
1260 	spin_lock_irq(&q->lock);
1261 	folio_set_waiters(folio);
1262 	if (!folio_trylock_flag(folio, bit_nr, wait))
1263 		__add_wait_queue_entry_tail(q, wait);
1264 	spin_unlock_irq(&q->lock);
1265 
1266 	/*
1267 	 * From now on, all the logic will be based on
1268 	 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1269 	 * see whether the page bit testing has already
1270 	 * been done by the wake function.
1271 	 *
1272 	 * We can drop our reference to the folio.
1273 	 */
1274 	if (behavior == DROP)
1275 		folio_put(folio);
1276 
1277 	/*
1278 	 * Note that until the "finish_wait()", or until
1279 	 * we see the WQ_FLAG_WOKEN flag, we need to
1280 	 * be very careful with the 'wait->flags', because
1281 	 * we may race with a waker that sets them.
1282 	 */
1283 	for (;;) {
1284 		unsigned int flags;
1285 
1286 		set_current_state(state);
1287 
1288 		/* Loop until we've been woken or interrupted */
1289 		flags = smp_load_acquire(&wait->flags);
1290 		if (!(flags & WQ_FLAG_WOKEN)) {
1291 			if (signal_pending_state(state, current))
1292 				break;
1293 
1294 			io_schedule();
1295 			continue;
1296 		}
1297 
1298 		/* If we were non-exclusive, we're done */
1299 		if (behavior != EXCLUSIVE)
1300 			break;
1301 
1302 		/* If the waker got the lock for us, we're done */
1303 		if (flags & WQ_FLAG_DONE)
1304 			break;
1305 
1306 		/*
1307 		 * Otherwise, if we're getting the lock, we need to
1308 		 * try to get it ourselves.
1309 		 *
1310 		 * And if that fails, we'll have to retry this all.
1311 		 */
1312 		if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
1313 			goto repeat;
1314 
1315 		wait->flags |= WQ_FLAG_DONE;
1316 		break;
1317 	}
1318 
1319 	/*
1320 	 * If a signal happened, this 'finish_wait()' may remove the last
1321 	 * waiter from the wait-queues, but the folio waiters bit will remain
1322 	 * set. That's ok. The next wakeup will take care of it, and trying
1323 	 * to do it here would be difficult and prone to races.
1324 	 */
1325 	finish_wait(q, wait);
1326 
1327 	if (thrashing) {
1328 		delayacct_thrashing_end();
1329 		psi_memstall_leave(&pflags);
1330 	}
1331 
1332 	/*
1333 	 * NOTE! The wait->flags weren't stable until we've done the
1334 	 * 'finish_wait()', and we could have exited the loop above due
1335 	 * to a signal, and had a wakeup event happen after the signal
1336 	 * test but before the 'finish_wait()'.
1337 	 *
1338 	 * So only after the finish_wait() can we reliably determine
1339 	 * if we got woken up or not, so we can now figure out the final
1340 	 * return value based on that state without races.
1341 	 *
1342 	 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1343 	 * waiter, but an exclusive one requires WQ_FLAG_DONE.
1344 	 */
1345 	if (behavior == EXCLUSIVE)
1346 		return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
1347 
1348 	return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
1349 }
1350 
1351 #ifdef CONFIG_MIGRATION
1352 /**
1353  * migration_entry_wait_on_locked - Wait for a migration entry to be removed
1354  * @entry: migration swap entry.
1355  * @ptep: mapped pte pointer. Will return with the ptep unmapped. Only required
1356  *        for pte entries, pass NULL for pmd entries.
1357  * @ptl: already locked ptl. This function will drop the lock.
1358  *
1359  * Wait for a migration entry referencing the given page to be removed. This is
1360  * equivalent to put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE) except
1361  * this can be called without taking a reference on the page. Instead this
1362  * should be called while holding the ptl for the migration entry referencing
1363  * the page.
1364  *
1365  * Returns after unmapping and unlocking the pte/ptl with pte_unmap_unlock().
1366  *
1367  * This follows the same logic as folio_wait_bit_common() so see the comments
1368  * there.
1369  */
1370 void migration_entry_wait_on_locked(swp_entry_t entry, pte_t *ptep,
1371 				spinlock_t *ptl)
1372 {
1373 	struct wait_page_queue wait_page;
1374 	wait_queue_entry_t *wait = &wait_page.wait;
1375 	bool thrashing = false;
1376 	unsigned long pflags;
1377 	wait_queue_head_t *q;
1378 	struct folio *folio = page_folio(pfn_swap_entry_to_page(entry));
1379 
1380 	q = folio_waitqueue(folio);
1381 	if (!folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1382 		delayacct_thrashing_start();
1383 		psi_memstall_enter(&pflags);
1384 		thrashing = true;
1385 	}
1386 
1387 	init_wait(wait);
1388 	wait->func = wake_page_function;
1389 	wait_page.folio = folio;
1390 	wait_page.bit_nr = PG_locked;
1391 	wait->flags = 0;
1392 
1393 	spin_lock_irq(&q->lock);
1394 	folio_set_waiters(folio);
1395 	if (!folio_trylock_flag(folio, PG_locked, wait))
1396 		__add_wait_queue_entry_tail(q, wait);
1397 	spin_unlock_irq(&q->lock);
1398 
1399 	/*
1400 	 * If a migration entry exists for the page the migration path must hold
1401 	 * a valid reference to the page, and it must take the ptl to remove the
1402 	 * migration entry. So the page is valid until the ptl is dropped.
1403 	 */
1404 	if (ptep)
1405 		pte_unmap_unlock(ptep, ptl);
1406 	else
1407 		spin_unlock(ptl);
1408 
1409 	for (;;) {
1410 		unsigned int flags;
1411 
1412 		set_current_state(TASK_UNINTERRUPTIBLE);
1413 
1414 		/* Loop until we've been woken or interrupted */
1415 		flags = smp_load_acquire(&wait->flags);
1416 		if (!(flags & WQ_FLAG_WOKEN)) {
1417 			if (signal_pending_state(TASK_UNINTERRUPTIBLE, current))
1418 				break;
1419 
1420 			io_schedule();
1421 			continue;
1422 		}
1423 		break;
1424 	}
1425 
1426 	finish_wait(q, wait);
1427 
1428 	if (thrashing) {
1429 		delayacct_thrashing_end();
1430 		psi_memstall_leave(&pflags);
1431 	}
1432 }
1433 #endif
1434 
1435 void folio_wait_bit(struct folio *folio, int bit_nr)
1436 {
1437 	folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
1438 }
1439 EXPORT_SYMBOL(folio_wait_bit);
1440 
1441 int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1442 {
1443 	return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1444 }
1445 EXPORT_SYMBOL(folio_wait_bit_killable);
1446 
1447 /**
1448  * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
1449  * @folio: The folio to wait for.
1450  * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
1451  *
1452  * The caller should hold a reference on @folio.  They expect the page to
1453  * become unlocked relatively soon, but do not wish to hold up migration
1454  * (for example) by holding the reference while waiting for the folio to
1455  * come unlocked.  After this function returns, the caller should not
1456  * dereference @folio.
1457  *
1458  * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
1459  */
1460 int folio_put_wait_locked(struct folio *folio, int state)
1461 {
1462 	return folio_wait_bit_common(folio, PG_locked, state, DROP);
1463 }
1464 
1465 /**
1466  * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
1467  * @folio: Folio defining the wait queue of interest
1468  * @waiter: Waiter to add to the queue
1469  *
1470  * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1471  */
1472 void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1473 {
1474 	wait_queue_head_t *q = folio_waitqueue(folio);
1475 	unsigned long flags;
1476 
1477 	spin_lock_irqsave(&q->lock, flags);
1478 	__add_wait_queue_entry_tail(q, waiter);
1479 	folio_set_waiters(folio);
1480 	spin_unlock_irqrestore(&q->lock, flags);
1481 }
1482 EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1483 
1484 #ifndef clear_bit_unlock_is_negative_byte
1485 
1486 /*
1487  * PG_waiters is the high bit in the same byte as PG_lock.
1488  *
1489  * On x86 (and on many other architectures), we can clear PG_lock and
1490  * test the sign bit at the same time. But if the architecture does
1491  * not support that special operation, we just do this all by hand
1492  * instead.
1493  *
1494  * The read of PG_waiters has to be after (or concurrently with) PG_locked
1495  * being cleared, but a memory barrier should be unnecessary since it is
1496  * in the same byte as PG_locked.
1497  */
1498 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1499 {
1500 	clear_bit_unlock(nr, mem);
1501 	/* smp_mb__after_atomic(); */
1502 	return test_bit(PG_waiters, mem);
1503 }
1504 
1505 #endif
1506 
1507 /**
1508  * folio_unlock - Unlock a locked folio.
1509  * @folio: The folio.
1510  *
1511  * Unlocks the folio and wakes up any thread sleeping on the page lock.
1512  *
1513  * Context: May be called from interrupt or process context.  May not be
1514  * called from NMI context.
1515  */
1516 void folio_unlock(struct folio *folio)
1517 {
1518 	/* Bit 7 allows x86 to check the byte's sign bit */
1519 	BUILD_BUG_ON(PG_waiters != 7);
1520 	BUILD_BUG_ON(PG_locked > 7);
1521 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1522 	if (clear_bit_unlock_is_negative_byte(PG_locked, folio_flags(folio, 0)))
1523 		folio_wake_bit(folio, PG_locked);
1524 }
1525 EXPORT_SYMBOL(folio_unlock);
1526 
1527 /**
1528  * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1529  * @folio: The folio.
1530  *
1531  * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
1532  * it.  The folio reference held for PG_private_2 being set is released.
1533  *
1534  * This is, for example, used when a netfs folio is being written to a local
1535  * disk cache, thereby allowing writes to the cache for the same folio to be
1536  * serialised.
1537  */
1538 void folio_end_private_2(struct folio *folio)
1539 {
1540 	VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
1541 	clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
1542 	folio_wake_bit(folio, PG_private_2);
1543 	folio_put(folio);
1544 }
1545 EXPORT_SYMBOL(folio_end_private_2);
1546 
1547 /**
1548  * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1549  * @folio: The folio to wait on.
1550  *
1551  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio.
1552  */
1553 void folio_wait_private_2(struct folio *folio)
1554 {
1555 	while (folio_test_private_2(folio))
1556 		folio_wait_bit(folio, PG_private_2);
1557 }
1558 EXPORT_SYMBOL(folio_wait_private_2);
1559 
1560 /**
1561  * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1562  * @folio: The folio to wait on.
1563  *
1564  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio or until a
1565  * fatal signal is received by the calling task.
1566  *
1567  * Return:
1568  * - 0 if successful.
1569  * - -EINTR if a fatal signal was encountered.
1570  */
1571 int folio_wait_private_2_killable(struct folio *folio)
1572 {
1573 	int ret = 0;
1574 
1575 	while (folio_test_private_2(folio)) {
1576 		ret = folio_wait_bit_killable(folio, PG_private_2);
1577 		if (ret < 0)
1578 			break;
1579 	}
1580 
1581 	return ret;
1582 }
1583 EXPORT_SYMBOL(folio_wait_private_2_killable);
1584 
1585 /**
1586  * folio_end_writeback - End writeback against a folio.
1587  * @folio: The folio.
1588  */
1589 void folio_end_writeback(struct folio *folio)
1590 {
1591 	/*
1592 	 * folio_test_clear_reclaim() could be used here but it is an
1593 	 * atomic operation and overkill in this particular case. Failing
1594 	 * to shuffle a folio marked for immediate reclaim is too mild
1595 	 * a gain to justify taking an atomic operation penalty at the
1596 	 * end of every folio writeback.
1597 	 */
1598 	if (folio_test_reclaim(folio)) {
1599 		folio_clear_reclaim(folio);
1600 		folio_rotate_reclaimable(folio);
1601 	}
1602 
1603 	/*
1604 	 * Writeback does not hold a folio reference of its own, relying
1605 	 * on truncation to wait for the clearing of PG_writeback.
1606 	 * But here we must make sure that the folio is not freed and
1607 	 * reused before the folio_wake().
1608 	 */
1609 	folio_get(folio);
1610 	if (!__folio_end_writeback(folio))
1611 		BUG();
1612 
1613 	smp_mb__after_atomic();
1614 	folio_wake(folio, PG_writeback);
1615 	acct_reclaim_writeback(folio);
1616 	folio_put(folio);
1617 }
1618 EXPORT_SYMBOL(folio_end_writeback);
1619 
1620 /*
1621  * After completing I/O on a page, call this routine to update the page
1622  * flags appropriately
1623  */
1624 void page_endio(struct page *page, bool is_write, int err)
1625 {
1626 	struct folio *folio = page_folio(page);
1627 
1628 	if (!is_write) {
1629 		if (!err) {
1630 			folio_mark_uptodate(folio);
1631 		} else {
1632 			folio_clear_uptodate(folio);
1633 			folio_set_error(folio);
1634 		}
1635 		folio_unlock(folio);
1636 	} else {
1637 		if (err) {
1638 			struct address_space *mapping;
1639 
1640 			folio_set_error(folio);
1641 			mapping = folio_mapping(folio);
1642 			if (mapping)
1643 				mapping_set_error(mapping, err);
1644 		}
1645 		folio_end_writeback(folio);
1646 	}
1647 }
1648 EXPORT_SYMBOL_GPL(page_endio);
1649 
1650 /**
1651  * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
1652  * @folio: The folio to lock
1653  */
1654 void __folio_lock(struct folio *folio)
1655 {
1656 	folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
1657 				EXCLUSIVE);
1658 }
1659 EXPORT_SYMBOL(__folio_lock);
1660 
1661 int __folio_lock_killable(struct folio *folio)
1662 {
1663 	return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
1664 					EXCLUSIVE);
1665 }
1666 EXPORT_SYMBOL_GPL(__folio_lock_killable);
1667 
1668 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1669 {
1670 	struct wait_queue_head *q = folio_waitqueue(folio);
1671 	int ret = 0;
1672 
1673 	wait->folio = folio;
1674 	wait->bit_nr = PG_locked;
1675 
1676 	spin_lock_irq(&q->lock);
1677 	__add_wait_queue_entry_tail(q, &wait->wait);
1678 	folio_set_waiters(folio);
1679 	ret = !folio_trylock(folio);
1680 	/*
1681 	 * If we were successful now, we know we're still on the
1682 	 * waitqueue as we're still under the lock. This means it's
1683 	 * safe to remove and return success, we know the callback
1684 	 * isn't going to trigger.
1685 	 */
1686 	if (!ret)
1687 		__remove_wait_queue(q, &wait->wait);
1688 	else
1689 		ret = -EIOCBQUEUED;
1690 	spin_unlock_irq(&q->lock);
1691 	return ret;
1692 }
1693 
1694 /*
1695  * Return values:
1696  * true - folio is locked; mmap_lock is still held.
1697  * false - folio is not locked.
1698  *     mmap_lock has been released (mmap_read_unlock(), unless flags had both
1699  *     FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1700  *     which case mmap_lock is still held.
1701  *
1702  * If neither ALLOW_RETRY nor KILLABLE are set, will always return true
1703  * with the folio locked and the mmap_lock unperturbed.
1704  */
1705 bool __folio_lock_or_retry(struct folio *folio, struct mm_struct *mm,
1706 			 unsigned int flags)
1707 {
1708 	if (fault_flag_allow_retry_first(flags)) {
1709 		/*
1710 		 * CAUTION! In this case, mmap_lock is not released
1711 		 * even though return 0.
1712 		 */
1713 		if (flags & FAULT_FLAG_RETRY_NOWAIT)
1714 			return false;
1715 
1716 		mmap_read_unlock(mm);
1717 		if (flags & FAULT_FLAG_KILLABLE)
1718 			folio_wait_locked_killable(folio);
1719 		else
1720 			folio_wait_locked(folio);
1721 		return false;
1722 	}
1723 	if (flags & FAULT_FLAG_KILLABLE) {
1724 		bool ret;
1725 
1726 		ret = __folio_lock_killable(folio);
1727 		if (ret) {
1728 			mmap_read_unlock(mm);
1729 			return false;
1730 		}
1731 	} else {
1732 		__folio_lock(folio);
1733 	}
1734 
1735 	return true;
1736 }
1737 
1738 /**
1739  * page_cache_next_miss() - Find the next gap in the page cache.
1740  * @mapping: Mapping.
1741  * @index: Index.
1742  * @max_scan: Maximum range to search.
1743  *
1744  * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1745  * gap with the lowest index.
1746  *
1747  * This function may be called under the rcu_read_lock.  However, this will
1748  * not atomically search a snapshot of the cache at a single point in time.
1749  * For example, if a gap is created at index 5, then subsequently a gap is
1750  * created at index 10, page_cache_next_miss covering both indices may
1751  * return 10 if called under the rcu_read_lock.
1752  *
1753  * Return: The index of the gap if found, otherwise an index outside the
1754  * range specified (in which case 'return - index >= max_scan' will be true).
1755  * In the rare case of index wrap-around, 0 will be returned.
1756  */
1757 pgoff_t page_cache_next_miss(struct address_space *mapping,
1758 			     pgoff_t index, unsigned long max_scan)
1759 {
1760 	XA_STATE(xas, &mapping->i_pages, index);
1761 
1762 	while (max_scan--) {
1763 		void *entry = xas_next(&xas);
1764 		if (!entry || xa_is_value(entry))
1765 			break;
1766 		if (xas.xa_index == 0)
1767 			break;
1768 	}
1769 
1770 	return xas.xa_index;
1771 }
1772 EXPORT_SYMBOL(page_cache_next_miss);
1773 
1774 /**
1775  * page_cache_prev_miss() - Find the previous gap in the page cache.
1776  * @mapping: Mapping.
1777  * @index: Index.
1778  * @max_scan: Maximum range to search.
1779  *
1780  * Search the range [max(index - max_scan + 1, 0), index] for the
1781  * gap with the highest index.
1782  *
1783  * This function may be called under the rcu_read_lock.  However, this will
1784  * not atomically search a snapshot of the cache at a single point in time.
1785  * For example, if a gap is created at index 10, then subsequently a gap is
1786  * created at index 5, page_cache_prev_miss() covering both indices may
1787  * return 5 if called under the rcu_read_lock.
1788  *
1789  * Return: The index of the gap if found, otherwise an index outside the
1790  * range specified (in which case 'index - return >= max_scan' will be true).
1791  * In the rare case of wrap-around, ULONG_MAX will be returned.
1792  */
1793 pgoff_t page_cache_prev_miss(struct address_space *mapping,
1794 			     pgoff_t index, unsigned long max_scan)
1795 {
1796 	XA_STATE(xas, &mapping->i_pages, index);
1797 
1798 	while (max_scan--) {
1799 		void *entry = xas_prev(&xas);
1800 		if (!entry || xa_is_value(entry))
1801 			break;
1802 		if (xas.xa_index == ULONG_MAX)
1803 			break;
1804 	}
1805 
1806 	return xas.xa_index;
1807 }
1808 EXPORT_SYMBOL(page_cache_prev_miss);
1809 
1810 /*
1811  * Lockless page cache protocol:
1812  * On the lookup side:
1813  * 1. Load the folio from i_pages
1814  * 2. Increment the refcount if it's not zero
1815  * 3. If the folio is not found by xas_reload(), put the refcount and retry
1816  *
1817  * On the removal side:
1818  * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
1819  * B. Remove the page from i_pages
1820  * C. Return the page to the page allocator
1821  *
1822  * This means that any page may have its reference count temporarily
1823  * increased by a speculative page cache (or fast GUP) lookup as it can
1824  * be allocated by another user before the RCU grace period expires.
1825  * Because the refcount temporarily acquired here may end up being the
1826  * last refcount on the page, any page allocation must be freeable by
1827  * folio_put().
1828  */
1829 
1830 /*
1831  * mapping_get_entry - Get a page cache entry.
1832  * @mapping: the address_space to search
1833  * @index: The page cache index.
1834  *
1835  * Looks up the page cache entry at @mapping & @index.  If it is a folio,
1836  * it is returned with an increased refcount.  If it is a shadow entry
1837  * of a previously evicted folio, or a swap entry from shmem/tmpfs,
1838  * it is returned without further action.
1839  *
1840  * Return: The folio, swap or shadow entry, %NULL if nothing is found.
1841  */
1842 static void *mapping_get_entry(struct address_space *mapping, pgoff_t index)
1843 {
1844 	XA_STATE(xas, &mapping->i_pages, index);
1845 	struct folio *folio;
1846 
1847 	rcu_read_lock();
1848 repeat:
1849 	xas_reset(&xas);
1850 	folio = xas_load(&xas);
1851 	if (xas_retry(&xas, folio))
1852 		goto repeat;
1853 	/*
1854 	 * A shadow entry of a recently evicted page, or a swap entry from
1855 	 * shmem/tmpfs.  Return it without attempting to raise page count.
1856 	 */
1857 	if (!folio || xa_is_value(folio))
1858 		goto out;
1859 
1860 	if (!folio_try_get_rcu(folio))
1861 		goto repeat;
1862 
1863 	if (unlikely(folio != xas_reload(&xas))) {
1864 		folio_put(folio);
1865 		goto repeat;
1866 	}
1867 out:
1868 	rcu_read_unlock();
1869 
1870 	return folio;
1871 }
1872 
1873 /**
1874  * __filemap_get_folio - Find and get a reference to a folio.
1875  * @mapping: The address_space to search.
1876  * @index: The page index.
1877  * @fgp_flags: %FGP flags modify how the folio is returned.
1878  * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
1879  *
1880  * Looks up the page cache entry at @mapping & @index.
1881  *
1882  * @fgp_flags can be zero or more of these flags:
1883  *
1884  * * %FGP_ACCESSED - The folio will be marked accessed.
1885  * * %FGP_LOCK - The folio is returned locked.
1886  * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1887  *   instead of allocating a new folio to replace it.
1888  * * %FGP_CREAT - If no page is present then a new page is allocated using
1889  *   @gfp and added to the page cache and the VM's LRU list.
1890  *   The page is returned locked and with an increased refcount.
1891  * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1892  *   page is already in cache.  If the page was allocated, unlock it before
1893  *   returning so the caller can do the same dance.
1894  * * %FGP_WRITE - The page will be written to by the caller.
1895  * * %FGP_NOFS - __GFP_FS will get cleared in gfp.
1896  * * %FGP_NOWAIT - Don't get blocked by page lock.
1897  * * %FGP_STABLE - Wait for the folio to be stable (finished writeback)
1898  *
1899  * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1900  * if the %GFP flags specified for %FGP_CREAT are atomic.
1901  *
1902  * If there is a page cache page, it is returned with an increased refcount.
1903  *
1904  * Return: The found folio or %NULL otherwise.
1905  */
1906 struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1907 		int fgp_flags, gfp_t gfp)
1908 {
1909 	struct folio *folio;
1910 
1911 repeat:
1912 	folio = mapping_get_entry(mapping, index);
1913 	if (xa_is_value(folio)) {
1914 		if (fgp_flags & FGP_ENTRY)
1915 			return folio;
1916 		folio = NULL;
1917 	}
1918 	if (!folio)
1919 		goto no_page;
1920 
1921 	if (fgp_flags & FGP_LOCK) {
1922 		if (fgp_flags & FGP_NOWAIT) {
1923 			if (!folio_trylock(folio)) {
1924 				folio_put(folio);
1925 				return NULL;
1926 			}
1927 		} else {
1928 			folio_lock(folio);
1929 		}
1930 
1931 		/* Has the page been truncated? */
1932 		if (unlikely(folio->mapping != mapping)) {
1933 			folio_unlock(folio);
1934 			folio_put(folio);
1935 			goto repeat;
1936 		}
1937 		VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
1938 	}
1939 
1940 	if (fgp_flags & FGP_ACCESSED)
1941 		folio_mark_accessed(folio);
1942 	else if (fgp_flags & FGP_WRITE) {
1943 		/* Clear idle flag for buffer write */
1944 		if (folio_test_idle(folio))
1945 			folio_clear_idle(folio);
1946 	}
1947 
1948 	if (fgp_flags & FGP_STABLE)
1949 		folio_wait_stable(folio);
1950 no_page:
1951 	if (!folio && (fgp_flags & FGP_CREAT)) {
1952 		int err;
1953 		if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
1954 			gfp |= __GFP_WRITE;
1955 		if (fgp_flags & FGP_NOFS)
1956 			gfp &= ~__GFP_FS;
1957 		if (fgp_flags & FGP_NOWAIT) {
1958 			gfp &= ~GFP_KERNEL;
1959 			gfp |= GFP_NOWAIT | __GFP_NOWARN;
1960 		}
1961 
1962 		folio = filemap_alloc_folio(gfp, 0);
1963 		if (!folio)
1964 			return NULL;
1965 
1966 		if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
1967 			fgp_flags |= FGP_LOCK;
1968 
1969 		/* Init accessed so avoid atomic mark_page_accessed later */
1970 		if (fgp_flags & FGP_ACCESSED)
1971 			__folio_set_referenced(folio);
1972 
1973 		err = filemap_add_folio(mapping, folio, index, gfp);
1974 		if (unlikely(err)) {
1975 			folio_put(folio);
1976 			folio = NULL;
1977 			if (err == -EEXIST)
1978 				goto repeat;
1979 		}
1980 
1981 		/*
1982 		 * filemap_add_folio locks the page, and for mmap
1983 		 * we expect an unlocked page.
1984 		 */
1985 		if (folio && (fgp_flags & FGP_FOR_MMAP))
1986 			folio_unlock(folio);
1987 	}
1988 
1989 	return folio;
1990 }
1991 EXPORT_SYMBOL(__filemap_get_folio);
1992 
1993 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
1994 		xa_mark_t mark)
1995 {
1996 	struct folio *folio;
1997 
1998 retry:
1999 	if (mark == XA_PRESENT)
2000 		folio = xas_find(xas, max);
2001 	else
2002 		folio = xas_find_marked(xas, max, mark);
2003 
2004 	if (xas_retry(xas, folio))
2005 		goto retry;
2006 	/*
2007 	 * A shadow entry of a recently evicted page, a swap
2008 	 * entry from shmem/tmpfs or a DAX entry.  Return it
2009 	 * without attempting to raise page count.
2010 	 */
2011 	if (!folio || xa_is_value(folio))
2012 		return folio;
2013 
2014 	if (!folio_try_get_rcu(folio))
2015 		goto reset;
2016 
2017 	if (unlikely(folio != xas_reload(xas))) {
2018 		folio_put(folio);
2019 		goto reset;
2020 	}
2021 
2022 	return folio;
2023 reset:
2024 	xas_reset(xas);
2025 	goto retry;
2026 }
2027 
2028 /**
2029  * find_get_entries - gang pagecache lookup
2030  * @mapping:	The address_space to search
2031  * @start:	The starting page cache index
2032  * @end:	The final page index (inclusive).
2033  * @fbatch:	Where the resulting entries are placed.
2034  * @indices:	The cache indices corresponding to the entries in @entries
2035  *
2036  * find_get_entries() will search for and return a batch of entries in
2037  * the mapping.  The entries are placed in @fbatch.  find_get_entries()
2038  * takes a reference on any actual folios it returns.
2039  *
2040  * The entries have ascending indexes.  The indices may not be consecutive
2041  * due to not-present entries or large folios.
2042  *
2043  * Any shadow entries of evicted folios, or swap entries from
2044  * shmem/tmpfs, are included in the returned array.
2045  *
2046  * Return: The number of entries which were found.
2047  */
2048 unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
2049 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2050 {
2051 	XA_STATE(xas, &mapping->i_pages, start);
2052 	struct folio *folio;
2053 
2054 	rcu_read_lock();
2055 	while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2056 		indices[fbatch->nr] = xas.xa_index;
2057 		if (!folio_batch_add(fbatch, folio))
2058 			break;
2059 	}
2060 	rcu_read_unlock();
2061 
2062 	return folio_batch_count(fbatch);
2063 }
2064 
2065 /**
2066  * find_lock_entries - Find a batch of pagecache entries.
2067  * @mapping:	The address_space to search.
2068  * @start:	The starting page cache index.
2069  * @end:	The final page index (inclusive).
2070  * @fbatch:	Where the resulting entries are placed.
2071  * @indices:	The cache indices of the entries in @fbatch.
2072  *
2073  * find_lock_entries() will return a batch of entries from @mapping.
2074  * Swap, shadow and DAX entries are included.  Folios are returned
2075  * locked and with an incremented refcount.  Folios which are locked
2076  * by somebody else or under writeback are skipped.  Folios which are
2077  * partially outside the range are not returned.
2078  *
2079  * The entries have ascending indexes.  The indices may not be consecutive
2080  * due to not-present entries, large folios, folios which could not be
2081  * locked or folios under writeback.
2082  *
2083  * Return: The number of entries which were found.
2084  */
2085 unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2086 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
2087 {
2088 	XA_STATE(xas, &mapping->i_pages, start);
2089 	struct folio *folio;
2090 
2091 	rcu_read_lock();
2092 	while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2093 		if (!xa_is_value(folio)) {
2094 			if (folio->index < start)
2095 				goto put;
2096 			if (folio->index + folio_nr_pages(folio) - 1 > end)
2097 				goto put;
2098 			if (!folio_trylock(folio))
2099 				goto put;
2100 			if (folio->mapping != mapping ||
2101 			    folio_test_writeback(folio))
2102 				goto unlock;
2103 			VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2104 					folio);
2105 		}
2106 		indices[fbatch->nr] = xas.xa_index;
2107 		if (!folio_batch_add(fbatch, folio))
2108 			break;
2109 		continue;
2110 unlock:
2111 		folio_unlock(folio);
2112 put:
2113 		folio_put(folio);
2114 	}
2115 	rcu_read_unlock();
2116 
2117 	return folio_batch_count(fbatch);
2118 }
2119 
2120 /**
2121  * filemap_get_folios - Get a batch of folios
2122  * @mapping:	The address_space to search
2123  * @start:	The starting page index
2124  * @end:	The final page index (inclusive)
2125  * @fbatch:	The batch to fill.
2126  *
2127  * Search for and return a batch of folios in the mapping starting at
2128  * index @start and up to index @end (inclusive).  The folios are returned
2129  * in @fbatch with an elevated reference count.
2130  *
2131  * The first folio may start before @start; if it does, it will contain
2132  * @start.  The final folio may extend beyond @end; if it does, it will
2133  * contain @end.  The folios have ascending indices.  There may be gaps
2134  * between the folios if there are indices which have no folio in the
2135  * page cache.  If folios are added to or removed from the page cache
2136  * while this is running, they may or may not be found by this call.
2137  *
2138  * Return: The number of folios which were found.
2139  * We also update @start to index the next folio for the traversal.
2140  */
2141 unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start,
2142 		pgoff_t end, struct folio_batch *fbatch)
2143 {
2144 	XA_STATE(xas, &mapping->i_pages, *start);
2145 	struct folio *folio;
2146 
2147 	rcu_read_lock();
2148 	while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2149 		/* Skip over shadow, swap and DAX entries */
2150 		if (xa_is_value(folio))
2151 			continue;
2152 		if (!folio_batch_add(fbatch, folio)) {
2153 			unsigned long nr = folio_nr_pages(folio);
2154 
2155 			if (folio_test_hugetlb(folio))
2156 				nr = 1;
2157 			*start = folio->index + nr;
2158 			goto out;
2159 		}
2160 	}
2161 
2162 	/*
2163 	 * We come here when there is no page beyond @end. We take care to not
2164 	 * overflow the index @start as it confuses some of the callers. This
2165 	 * breaks the iteration when there is a page at index -1 but that is
2166 	 * already broken anyway.
2167 	 */
2168 	if (end == (pgoff_t)-1)
2169 		*start = (pgoff_t)-1;
2170 	else
2171 		*start = end + 1;
2172 out:
2173 	rcu_read_unlock();
2174 
2175 	return folio_batch_count(fbatch);
2176 }
2177 EXPORT_SYMBOL(filemap_get_folios);
2178 
2179 static inline
2180 bool folio_more_pages(struct folio *folio, pgoff_t index, pgoff_t max)
2181 {
2182 	if (!folio_test_large(folio) || folio_test_hugetlb(folio))
2183 		return false;
2184 	if (index >= max)
2185 		return false;
2186 	return index < folio->index + folio_nr_pages(folio) - 1;
2187 }
2188 
2189 /**
2190  * filemap_get_folios_contig - Get a batch of contiguous folios
2191  * @mapping:	The address_space to search
2192  * @start:	The starting page index
2193  * @end:	The final page index (inclusive)
2194  * @fbatch:	The batch to fill
2195  *
2196  * filemap_get_folios_contig() works exactly like filemap_get_folios(),
2197  * except the returned folios are guaranteed to be contiguous. This may
2198  * not return all contiguous folios if the batch gets filled up.
2199  *
2200  * Return: The number of folios found.
2201  * Also update @start to be positioned for traversal of the next folio.
2202  */
2203 
2204 unsigned filemap_get_folios_contig(struct address_space *mapping,
2205 		pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
2206 {
2207 	XA_STATE(xas, &mapping->i_pages, *start);
2208 	unsigned long nr;
2209 	struct folio *folio;
2210 
2211 	rcu_read_lock();
2212 
2213 	for (folio = xas_load(&xas); folio && xas.xa_index <= end;
2214 			folio = xas_next(&xas)) {
2215 		if (xas_retry(&xas, folio))
2216 			continue;
2217 		/*
2218 		 * If the entry has been swapped out, we can stop looking.
2219 		 * No current caller is looking for DAX entries.
2220 		 */
2221 		if (xa_is_value(folio))
2222 			goto update_start;
2223 
2224 		if (!folio_try_get_rcu(folio))
2225 			goto retry;
2226 
2227 		if (unlikely(folio != xas_reload(&xas)))
2228 			goto put_folio;
2229 
2230 		if (!folio_batch_add(fbatch, folio)) {
2231 			nr = folio_nr_pages(folio);
2232 
2233 			if (folio_test_hugetlb(folio))
2234 				nr = 1;
2235 			*start = folio->index + nr;
2236 			goto out;
2237 		}
2238 		continue;
2239 put_folio:
2240 		folio_put(folio);
2241 
2242 retry:
2243 		xas_reset(&xas);
2244 	}
2245 
2246 update_start:
2247 	nr = folio_batch_count(fbatch);
2248 
2249 	if (nr) {
2250 		folio = fbatch->folios[nr - 1];
2251 		if (folio_test_hugetlb(folio))
2252 			*start = folio->index + 1;
2253 		else
2254 			*start = folio->index + folio_nr_pages(folio);
2255 	}
2256 out:
2257 	rcu_read_unlock();
2258 	return folio_batch_count(fbatch);
2259 }
2260 EXPORT_SYMBOL(filemap_get_folios_contig);
2261 
2262 /**
2263  * find_get_pages_range_tag - Find and return head pages matching @tag.
2264  * @mapping:	the address_space to search
2265  * @index:	the starting page index
2266  * @end:	The final page index (inclusive)
2267  * @tag:	the tag index
2268  * @nr_pages:	the maximum number of pages
2269  * @pages:	where the resulting pages are placed
2270  *
2271  * Like find_get_pages_range(), except we only return head pages which are
2272  * tagged with @tag.  @index is updated to the index immediately after the
2273  * last page we return, ready for the next iteration.
2274  *
2275  * Return: the number of pages which were found.
2276  */
2277 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
2278 			pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
2279 			struct page **pages)
2280 {
2281 	XA_STATE(xas, &mapping->i_pages, *index);
2282 	struct folio *folio;
2283 	unsigned ret = 0;
2284 
2285 	if (unlikely(!nr_pages))
2286 		return 0;
2287 
2288 	rcu_read_lock();
2289 	while ((folio = find_get_entry(&xas, end, tag))) {
2290 		/*
2291 		 * Shadow entries should never be tagged, but this iteration
2292 		 * is lockless so there is a window for page reclaim to evict
2293 		 * a page we saw tagged.  Skip over it.
2294 		 */
2295 		if (xa_is_value(folio))
2296 			continue;
2297 
2298 		pages[ret] = &folio->page;
2299 		if (++ret == nr_pages) {
2300 			*index = folio->index + folio_nr_pages(folio);
2301 			goto out;
2302 		}
2303 	}
2304 
2305 	/*
2306 	 * We come here when we got to @end. We take care to not overflow the
2307 	 * index @index as it confuses some of the callers. This breaks the
2308 	 * iteration when there is a page at index -1 but that is already
2309 	 * broken anyway.
2310 	 */
2311 	if (end == (pgoff_t)-1)
2312 		*index = (pgoff_t)-1;
2313 	else
2314 		*index = end + 1;
2315 out:
2316 	rcu_read_unlock();
2317 
2318 	return ret;
2319 }
2320 EXPORT_SYMBOL(find_get_pages_range_tag);
2321 
2322 /*
2323  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2324  * a _large_ part of the i/o request. Imagine the worst scenario:
2325  *
2326  *      ---R__________________________________________B__________
2327  *         ^ reading here                             ^ bad block(assume 4k)
2328  *
2329  * read(R) => miss => readahead(R...B) => media error => frustrating retries
2330  * => failing the whole request => read(R) => read(R+1) =>
2331  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2332  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2333  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2334  *
2335  * It is going insane. Fix it by quickly scaling down the readahead size.
2336  */
2337 static void shrink_readahead_size_eio(struct file_ra_state *ra)
2338 {
2339 	ra->ra_pages /= 4;
2340 }
2341 
2342 /*
2343  * filemap_get_read_batch - Get a batch of folios for read
2344  *
2345  * Get a batch of folios which represent a contiguous range of bytes in
2346  * the file.  No exceptional entries will be returned.  If @index is in
2347  * the middle of a folio, the entire folio will be returned.  The last
2348  * folio in the batch may have the readahead flag set or the uptodate flag
2349  * clear so that the caller can take the appropriate action.
2350  */
2351 static void filemap_get_read_batch(struct address_space *mapping,
2352 		pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2353 {
2354 	XA_STATE(xas, &mapping->i_pages, index);
2355 	struct folio *folio;
2356 
2357 	rcu_read_lock();
2358 	for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2359 		if (xas_retry(&xas, folio))
2360 			continue;
2361 		if (xas.xa_index > max || xa_is_value(folio))
2362 			break;
2363 		if (xa_is_sibling(folio))
2364 			break;
2365 		if (!folio_try_get_rcu(folio))
2366 			goto retry;
2367 
2368 		if (unlikely(folio != xas_reload(&xas)))
2369 			goto put_folio;
2370 
2371 		if (!folio_batch_add(fbatch, folio))
2372 			break;
2373 		if (!folio_test_uptodate(folio))
2374 			break;
2375 		if (folio_test_readahead(folio))
2376 			break;
2377 		xas_advance(&xas, folio->index + folio_nr_pages(folio) - 1);
2378 		continue;
2379 put_folio:
2380 		folio_put(folio);
2381 retry:
2382 		xas_reset(&xas);
2383 	}
2384 	rcu_read_unlock();
2385 }
2386 
2387 static int filemap_read_folio(struct file *file, filler_t filler,
2388 		struct folio *folio)
2389 {
2390 	int error;
2391 
2392 	/*
2393 	 * A previous I/O error may have been due to temporary failures,
2394 	 * eg. multipath errors.  PG_error will be set again if read_folio
2395 	 * fails.
2396 	 */
2397 	folio_clear_error(folio);
2398 	/* Start the actual read. The read will unlock the page. */
2399 	error = filler(file, folio);
2400 	if (error)
2401 		return error;
2402 
2403 	error = folio_wait_locked_killable(folio);
2404 	if (error)
2405 		return error;
2406 	if (folio_test_uptodate(folio))
2407 		return 0;
2408 	if (file)
2409 		shrink_readahead_size_eio(&file->f_ra);
2410 	return -EIO;
2411 }
2412 
2413 static bool filemap_range_uptodate(struct address_space *mapping,
2414 		loff_t pos, struct iov_iter *iter, struct folio *folio)
2415 {
2416 	int count;
2417 
2418 	if (folio_test_uptodate(folio))
2419 		return true;
2420 	/* pipes can't handle partially uptodate pages */
2421 	if (iov_iter_is_pipe(iter))
2422 		return false;
2423 	if (!mapping->a_ops->is_partially_uptodate)
2424 		return false;
2425 	if (mapping->host->i_blkbits >= folio_shift(folio))
2426 		return false;
2427 
2428 	count = iter->count;
2429 	if (folio_pos(folio) > pos) {
2430 		count -= folio_pos(folio) - pos;
2431 		pos = 0;
2432 	} else {
2433 		pos -= folio_pos(folio);
2434 	}
2435 
2436 	return mapping->a_ops->is_partially_uptodate(folio, pos, count);
2437 }
2438 
2439 static int filemap_update_page(struct kiocb *iocb,
2440 		struct address_space *mapping, struct iov_iter *iter,
2441 		struct folio *folio)
2442 {
2443 	int error;
2444 
2445 	if (iocb->ki_flags & IOCB_NOWAIT) {
2446 		if (!filemap_invalidate_trylock_shared(mapping))
2447 			return -EAGAIN;
2448 	} else {
2449 		filemap_invalidate_lock_shared(mapping);
2450 	}
2451 
2452 	if (!folio_trylock(folio)) {
2453 		error = -EAGAIN;
2454 		if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2455 			goto unlock_mapping;
2456 		if (!(iocb->ki_flags & IOCB_WAITQ)) {
2457 			filemap_invalidate_unlock_shared(mapping);
2458 			/*
2459 			 * This is where we usually end up waiting for a
2460 			 * previously submitted readahead to finish.
2461 			 */
2462 			folio_put_wait_locked(folio, TASK_KILLABLE);
2463 			return AOP_TRUNCATED_PAGE;
2464 		}
2465 		error = __folio_lock_async(folio, iocb->ki_waitq);
2466 		if (error)
2467 			goto unlock_mapping;
2468 	}
2469 
2470 	error = AOP_TRUNCATED_PAGE;
2471 	if (!folio->mapping)
2472 		goto unlock;
2473 
2474 	error = 0;
2475 	if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, folio))
2476 		goto unlock;
2477 
2478 	error = -EAGAIN;
2479 	if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2480 		goto unlock;
2481 
2482 	error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio,
2483 			folio);
2484 	goto unlock_mapping;
2485 unlock:
2486 	folio_unlock(folio);
2487 unlock_mapping:
2488 	filemap_invalidate_unlock_shared(mapping);
2489 	if (error == AOP_TRUNCATED_PAGE)
2490 		folio_put(folio);
2491 	return error;
2492 }
2493 
2494 static int filemap_create_folio(struct file *file,
2495 		struct address_space *mapping, pgoff_t index,
2496 		struct folio_batch *fbatch)
2497 {
2498 	struct folio *folio;
2499 	int error;
2500 
2501 	folio = filemap_alloc_folio(mapping_gfp_mask(mapping), 0);
2502 	if (!folio)
2503 		return -ENOMEM;
2504 
2505 	/*
2506 	 * Protect against truncate / hole punch. Grabbing invalidate_lock
2507 	 * here assures we cannot instantiate and bring uptodate new
2508 	 * pagecache folios after evicting page cache during truncate
2509 	 * and before actually freeing blocks.	Note that we could
2510 	 * release invalidate_lock after inserting the folio into
2511 	 * the page cache as the locked folio would then be enough to
2512 	 * synchronize with hole punching. But there are code paths
2513 	 * such as filemap_update_page() filling in partially uptodate
2514 	 * pages or ->readahead() that need to hold invalidate_lock
2515 	 * while mapping blocks for IO so let's hold the lock here as
2516 	 * well to keep locking rules simple.
2517 	 */
2518 	filemap_invalidate_lock_shared(mapping);
2519 	error = filemap_add_folio(mapping, folio, index,
2520 			mapping_gfp_constraint(mapping, GFP_KERNEL));
2521 	if (error == -EEXIST)
2522 		error = AOP_TRUNCATED_PAGE;
2523 	if (error)
2524 		goto error;
2525 
2526 	error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
2527 	if (error)
2528 		goto error;
2529 
2530 	filemap_invalidate_unlock_shared(mapping);
2531 	folio_batch_add(fbatch, folio);
2532 	return 0;
2533 error:
2534 	filemap_invalidate_unlock_shared(mapping);
2535 	folio_put(folio);
2536 	return error;
2537 }
2538 
2539 static int filemap_readahead(struct kiocb *iocb, struct file *file,
2540 		struct address_space *mapping, struct folio *folio,
2541 		pgoff_t last_index)
2542 {
2543 	DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
2544 
2545 	if (iocb->ki_flags & IOCB_NOIO)
2546 		return -EAGAIN;
2547 	page_cache_async_ra(&ractl, folio, last_index - folio->index);
2548 	return 0;
2549 }
2550 
2551 static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
2552 		struct folio_batch *fbatch)
2553 {
2554 	struct file *filp = iocb->ki_filp;
2555 	struct address_space *mapping = filp->f_mapping;
2556 	struct file_ra_state *ra = &filp->f_ra;
2557 	pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2558 	pgoff_t last_index;
2559 	struct folio *folio;
2560 	int err = 0;
2561 
2562 	last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2563 retry:
2564 	if (fatal_signal_pending(current))
2565 		return -EINTR;
2566 
2567 	filemap_get_read_batch(mapping, index, last_index, fbatch);
2568 	if (!folio_batch_count(fbatch)) {
2569 		if (iocb->ki_flags & IOCB_NOIO)
2570 			return -EAGAIN;
2571 		page_cache_sync_readahead(mapping, ra, filp, index,
2572 				last_index - index);
2573 		filemap_get_read_batch(mapping, index, last_index, fbatch);
2574 	}
2575 	if (!folio_batch_count(fbatch)) {
2576 		if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2577 			return -EAGAIN;
2578 		err = filemap_create_folio(filp, mapping,
2579 				iocb->ki_pos >> PAGE_SHIFT, fbatch);
2580 		if (err == AOP_TRUNCATED_PAGE)
2581 			goto retry;
2582 		return err;
2583 	}
2584 
2585 	folio = fbatch->folios[folio_batch_count(fbatch) - 1];
2586 	if (folio_test_readahead(folio)) {
2587 		err = filemap_readahead(iocb, filp, mapping, folio, last_index);
2588 		if (err)
2589 			goto err;
2590 	}
2591 	if (!folio_test_uptodate(folio)) {
2592 		if ((iocb->ki_flags & IOCB_WAITQ) &&
2593 		    folio_batch_count(fbatch) > 1)
2594 			iocb->ki_flags |= IOCB_NOWAIT;
2595 		err = filemap_update_page(iocb, mapping, iter, folio);
2596 		if (err)
2597 			goto err;
2598 	}
2599 
2600 	return 0;
2601 err:
2602 	if (err < 0)
2603 		folio_put(folio);
2604 	if (likely(--fbatch->nr))
2605 		return 0;
2606 	if (err == AOP_TRUNCATED_PAGE)
2607 		goto retry;
2608 	return err;
2609 }
2610 
2611 static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)
2612 {
2613 	unsigned int shift = folio_shift(folio);
2614 
2615 	return (pos1 >> shift == pos2 >> shift);
2616 }
2617 
2618 /**
2619  * filemap_read - Read data from the page cache.
2620  * @iocb: The iocb to read.
2621  * @iter: Destination for the data.
2622  * @already_read: Number of bytes already read by the caller.
2623  *
2624  * Copies data from the page cache.  If the data is not currently present,
2625  * uses the readahead and read_folio address_space operations to fetch it.
2626  *
2627  * Return: Total number of bytes copied, including those already read by
2628  * the caller.  If an error happens before any bytes are copied, returns
2629  * a negative error number.
2630  */
2631 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2632 		ssize_t already_read)
2633 {
2634 	struct file *filp = iocb->ki_filp;
2635 	struct file_ra_state *ra = &filp->f_ra;
2636 	struct address_space *mapping = filp->f_mapping;
2637 	struct inode *inode = mapping->host;
2638 	struct folio_batch fbatch;
2639 	int i, error = 0;
2640 	bool writably_mapped;
2641 	loff_t isize, end_offset;
2642 
2643 	if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2644 		return 0;
2645 	if (unlikely(!iov_iter_count(iter)))
2646 		return 0;
2647 
2648 	iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2649 	folio_batch_init(&fbatch);
2650 
2651 	do {
2652 		cond_resched();
2653 
2654 		/*
2655 		 * If we've already successfully copied some data, then we
2656 		 * can no longer safely return -EIOCBQUEUED. Hence mark
2657 		 * an async read NOWAIT at that point.
2658 		 */
2659 		if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
2660 			iocb->ki_flags |= IOCB_NOWAIT;
2661 
2662 		if (unlikely(iocb->ki_pos >= i_size_read(inode)))
2663 			break;
2664 
2665 		error = filemap_get_pages(iocb, iter, &fbatch);
2666 		if (error < 0)
2667 			break;
2668 
2669 		/*
2670 		 * i_size must be checked after we know the pages are Uptodate.
2671 		 *
2672 		 * Checking i_size after the check allows us to calculate
2673 		 * the correct value for "nr", which means the zero-filled
2674 		 * part of the page is not copied back to userspace (unless
2675 		 * another truncate extends the file - this is desired though).
2676 		 */
2677 		isize = i_size_read(inode);
2678 		if (unlikely(iocb->ki_pos >= isize))
2679 			goto put_folios;
2680 		end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2681 
2682 		/*
2683 		 * Once we start copying data, we don't want to be touching any
2684 		 * cachelines that might be contended:
2685 		 */
2686 		writably_mapped = mapping_writably_mapped(mapping);
2687 
2688 		/*
2689 		 * When a read accesses the same folio several times, only
2690 		 * mark it as accessed the first time.
2691 		 */
2692 		if (!pos_same_folio(iocb->ki_pos, ra->prev_pos - 1,
2693 							fbatch.folios[0]))
2694 			folio_mark_accessed(fbatch.folios[0]);
2695 
2696 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
2697 			struct folio *folio = fbatch.folios[i];
2698 			size_t fsize = folio_size(folio);
2699 			size_t offset = iocb->ki_pos & (fsize - 1);
2700 			size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2701 					     fsize - offset);
2702 			size_t copied;
2703 
2704 			if (end_offset < folio_pos(folio))
2705 				break;
2706 			if (i > 0)
2707 				folio_mark_accessed(folio);
2708 			/*
2709 			 * If users can be writing to this folio using arbitrary
2710 			 * virtual addresses, take care of potential aliasing
2711 			 * before reading the folio on the kernel side.
2712 			 */
2713 			if (writably_mapped)
2714 				flush_dcache_folio(folio);
2715 
2716 			copied = copy_folio_to_iter(folio, offset, bytes, iter);
2717 
2718 			already_read += copied;
2719 			iocb->ki_pos += copied;
2720 			ra->prev_pos = iocb->ki_pos;
2721 
2722 			if (copied < bytes) {
2723 				error = -EFAULT;
2724 				break;
2725 			}
2726 		}
2727 put_folios:
2728 		for (i = 0; i < folio_batch_count(&fbatch); i++)
2729 			folio_put(fbatch.folios[i]);
2730 		folio_batch_init(&fbatch);
2731 	} while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
2732 
2733 	file_accessed(filp);
2734 
2735 	return already_read ? already_read : error;
2736 }
2737 EXPORT_SYMBOL_GPL(filemap_read);
2738 
2739 /**
2740  * generic_file_read_iter - generic filesystem read routine
2741  * @iocb:	kernel I/O control block
2742  * @iter:	destination for the data read
2743  *
2744  * This is the "read_iter()" routine for all filesystems
2745  * that can use the page cache directly.
2746  *
2747  * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2748  * be returned when no data can be read without waiting for I/O requests
2749  * to complete; it doesn't prevent readahead.
2750  *
2751  * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2752  * requests shall be made for the read or for readahead.  When no data
2753  * can be read, -EAGAIN shall be returned.  When readahead would be
2754  * triggered, a partial, possibly empty read shall be returned.
2755  *
2756  * Return:
2757  * * number of bytes copied, even for partial reads
2758  * * negative error code (or 0 if IOCB_NOIO) if nothing was read
2759  */
2760 ssize_t
2761 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2762 {
2763 	size_t count = iov_iter_count(iter);
2764 	ssize_t retval = 0;
2765 
2766 	if (!count)
2767 		return 0; /* skip atime */
2768 
2769 	if (iocb->ki_flags & IOCB_DIRECT) {
2770 		struct file *file = iocb->ki_filp;
2771 		struct address_space *mapping = file->f_mapping;
2772 		struct inode *inode = mapping->host;
2773 
2774 		if (iocb->ki_flags & IOCB_NOWAIT) {
2775 			if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2776 						iocb->ki_pos + count - 1))
2777 				return -EAGAIN;
2778 		} else {
2779 			retval = filemap_write_and_wait_range(mapping,
2780 						iocb->ki_pos,
2781 					        iocb->ki_pos + count - 1);
2782 			if (retval < 0)
2783 				return retval;
2784 		}
2785 
2786 		file_accessed(file);
2787 
2788 		retval = mapping->a_ops->direct_IO(iocb, iter);
2789 		if (retval >= 0) {
2790 			iocb->ki_pos += retval;
2791 			count -= retval;
2792 		}
2793 		if (retval != -EIOCBQUEUED)
2794 			iov_iter_revert(iter, count - iov_iter_count(iter));
2795 
2796 		/*
2797 		 * Btrfs can have a short DIO read if we encounter
2798 		 * compressed extents, so if there was an error, or if
2799 		 * we've already read everything we wanted to, or if
2800 		 * there was a short read because we hit EOF, go ahead
2801 		 * and return.  Otherwise fallthrough to buffered io for
2802 		 * the rest of the read.  Buffered reads will not work for
2803 		 * DAX files, so don't bother trying.
2804 		 */
2805 		if (retval < 0 || !count || IS_DAX(inode))
2806 			return retval;
2807 		if (iocb->ki_pos >= i_size_read(inode))
2808 			return retval;
2809 	}
2810 
2811 	return filemap_read(iocb, iter, retval);
2812 }
2813 EXPORT_SYMBOL(generic_file_read_iter);
2814 
2815 static inline loff_t folio_seek_hole_data(struct xa_state *xas,
2816 		struct address_space *mapping, struct folio *folio,
2817 		loff_t start, loff_t end, bool seek_data)
2818 {
2819 	const struct address_space_operations *ops = mapping->a_ops;
2820 	size_t offset, bsz = i_blocksize(mapping->host);
2821 
2822 	if (xa_is_value(folio) || folio_test_uptodate(folio))
2823 		return seek_data ? start : end;
2824 	if (!ops->is_partially_uptodate)
2825 		return seek_data ? end : start;
2826 
2827 	xas_pause(xas);
2828 	rcu_read_unlock();
2829 	folio_lock(folio);
2830 	if (unlikely(folio->mapping != mapping))
2831 		goto unlock;
2832 
2833 	offset = offset_in_folio(folio, start) & ~(bsz - 1);
2834 
2835 	do {
2836 		if (ops->is_partially_uptodate(folio, offset, bsz) ==
2837 							seek_data)
2838 			break;
2839 		start = (start + bsz) & ~(bsz - 1);
2840 		offset += bsz;
2841 	} while (offset < folio_size(folio));
2842 unlock:
2843 	folio_unlock(folio);
2844 	rcu_read_lock();
2845 	return start;
2846 }
2847 
2848 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
2849 {
2850 	if (xa_is_value(folio))
2851 		return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2852 	return folio_size(folio);
2853 }
2854 
2855 /**
2856  * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2857  * @mapping: Address space to search.
2858  * @start: First byte to consider.
2859  * @end: Limit of search (exclusive).
2860  * @whence: Either SEEK_HOLE or SEEK_DATA.
2861  *
2862  * If the page cache knows which blocks contain holes and which blocks
2863  * contain data, your filesystem can use this function to implement
2864  * SEEK_HOLE and SEEK_DATA.  This is useful for filesystems which are
2865  * entirely memory-based such as tmpfs, and filesystems which support
2866  * unwritten extents.
2867  *
2868  * Return: The requested offset on success, or -ENXIO if @whence specifies
2869  * SEEK_DATA and there is no data after @start.  There is an implicit hole
2870  * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2871  * and @end contain data.
2872  */
2873 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2874 		loff_t end, int whence)
2875 {
2876 	XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
2877 	pgoff_t max = (end - 1) >> PAGE_SHIFT;
2878 	bool seek_data = (whence == SEEK_DATA);
2879 	struct folio *folio;
2880 
2881 	if (end <= start)
2882 		return -ENXIO;
2883 
2884 	rcu_read_lock();
2885 	while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
2886 		loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2887 		size_t seek_size;
2888 
2889 		if (start < pos) {
2890 			if (!seek_data)
2891 				goto unlock;
2892 			start = pos;
2893 		}
2894 
2895 		seek_size = seek_folio_size(&xas, folio);
2896 		pos = round_up((u64)pos + 1, seek_size);
2897 		start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
2898 				seek_data);
2899 		if (start < pos)
2900 			goto unlock;
2901 		if (start >= end)
2902 			break;
2903 		if (seek_size > PAGE_SIZE)
2904 			xas_set(&xas, pos >> PAGE_SHIFT);
2905 		if (!xa_is_value(folio))
2906 			folio_put(folio);
2907 	}
2908 	if (seek_data)
2909 		start = -ENXIO;
2910 unlock:
2911 	rcu_read_unlock();
2912 	if (folio && !xa_is_value(folio))
2913 		folio_put(folio);
2914 	if (start > end)
2915 		return end;
2916 	return start;
2917 }
2918 
2919 #ifdef CONFIG_MMU
2920 #define MMAP_LOTSAMISS  (100)
2921 /*
2922  * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
2923  * @vmf - the vm_fault for this fault.
2924  * @folio - the folio to lock.
2925  * @fpin - the pointer to the file we may pin (or is already pinned).
2926  *
2927  * This works similar to lock_folio_or_retry in that it can drop the
2928  * mmap_lock.  It differs in that it actually returns the folio locked
2929  * if it returns 1 and 0 if it couldn't lock the folio.  If we did have
2930  * to drop the mmap_lock then fpin will point to the pinned file and
2931  * needs to be fput()'ed at a later point.
2932  */
2933 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
2934 				     struct file **fpin)
2935 {
2936 	if (folio_trylock(folio))
2937 		return 1;
2938 
2939 	/*
2940 	 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2941 	 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
2942 	 * is supposed to work. We have way too many special cases..
2943 	 */
2944 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2945 		return 0;
2946 
2947 	*fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2948 	if (vmf->flags & FAULT_FLAG_KILLABLE) {
2949 		if (__folio_lock_killable(folio)) {
2950 			/*
2951 			 * We didn't have the right flags to drop the mmap_lock,
2952 			 * but all fault_handlers only check for fatal signals
2953 			 * if we return VM_FAULT_RETRY, so we need to drop the
2954 			 * mmap_lock here and return 0 if we don't have a fpin.
2955 			 */
2956 			if (*fpin == NULL)
2957 				mmap_read_unlock(vmf->vma->vm_mm);
2958 			return 0;
2959 		}
2960 	} else
2961 		__folio_lock(folio);
2962 
2963 	return 1;
2964 }
2965 
2966 /*
2967  * Synchronous readahead happens when we don't even find a page in the page
2968  * cache at all.  We don't want to perform IO under the mmap sem, so if we have
2969  * to drop the mmap sem we return the file that was pinned in order for us to do
2970  * that.  If we didn't pin a file then we return NULL.  The file that is
2971  * returned needs to be fput()'ed when we're done with it.
2972  */
2973 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
2974 {
2975 	struct file *file = vmf->vma->vm_file;
2976 	struct file_ra_state *ra = &file->f_ra;
2977 	struct address_space *mapping = file->f_mapping;
2978 	DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
2979 	struct file *fpin = NULL;
2980 	unsigned long vm_flags = vmf->vma->vm_flags;
2981 	unsigned int mmap_miss;
2982 
2983 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2984 	/* Use the readahead code, even if readahead is disabled */
2985 	if (vm_flags & VM_HUGEPAGE) {
2986 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2987 		ractl._index &= ~((unsigned long)HPAGE_PMD_NR - 1);
2988 		ra->size = HPAGE_PMD_NR;
2989 		/*
2990 		 * Fetch two PMD folios, so we get the chance to actually
2991 		 * readahead, unless we've been told not to.
2992 		 */
2993 		if (!(vm_flags & VM_RAND_READ))
2994 			ra->size *= 2;
2995 		ra->async_size = HPAGE_PMD_NR;
2996 		page_cache_ra_order(&ractl, ra, HPAGE_PMD_ORDER);
2997 		return fpin;
2998 	}
2999 #endif
3000 
3001 	/* If we don't want any read-ahead, don't bother */
3002 	if (vm_flags & VM_RAND_READ)
3003 		return fpin;
3004 	if (!ra->ra_pages)
3005 		return fpin;
3006 
3007 	if (vm_flags & VM_SEQ_READ) {
3008 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3009 		page_cache_sync_ra(&ractl, ra->ra_pages);
3010 		return fpin;
3011 	}
3012 
3013 	/* Avoid banging the cache line if not needed */
3014 	mmap_miss = READ_ONCE(ra->mmap_miss);
3015 	if (mmap_miss < MMAP_LOTSAMISS * 10)
3016 		WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
3017 
3018 	/*
3019 	 * Do we miss much more than hit in this file? If so,
3020 	 * stop bothering with read-ahead. It will only hurt.
3021 	 */
3022 	if (mmap_miss > MMAP_LOTSAMISS)
3023 		return fpin;
3024 
3025 	/*
3026 	 * mmap read-around
3027 	 */
3028 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3029 	ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
3030 	ra->size = ra->ra_pages;
3031 	ra->async_size = ra->ra_pages / 4;
3032 	ractl._index = ra->start;
3033 	page_cache_ra_order(&ractl, ra, 0);
3034 	return fpin;
3035 }
3036 
3037 /*
3038  * Asynchronous readahead happens when we find the page and PG_readahead,
3039  * so we want to possibly extend the readahead further.  We return the file that
3040  * was pinned if we have to drop the mmap_lock in order to do IO.
3041  */
3042 static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
3043 					    struct folio *folio)
3044 {
3045 	struct file *file = vmf->vma->vm_file;
3046 	struct file_ra_state *ra = &file->f_ra;
3047 	DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
3048 	struct file *fpin = NULL;
3049 	unsigned int mmap_miss;
3050 
3051 	/* If we don't want any read-ahead, don't bother */
3052 	if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
3053 		return fpin;
3054 
3055 	mmap_miss = READ_ONCE(ra->mmap_miss);
3056 	if (mmap_miss)
3057 		WRITE_ONCE(ra->mmap_miss, --mmap_miss);
3058 
3059 	if (folio_test_readahead(folio)) {
3060 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3061 		page_cache_async_ra(&ractl, folio, ra->ra_pages);
3062 	}
3063 	return fpin;
3064 }
3065 
3066 /**
3067  * filemap_fault - read in file data for page fault handling
3068  * @vmf:	struct vm_fault containing details of the fault
3069  *
3070  * filemap_fault() is invoked via the vma operations vector for a
3071  * mapped memory region to read in file data during a page fault.
3072  *
3073  * The goto's are kind of ugly, but this streamlines the normal case of having
3074  * it in the page cache, and handles the special cases reasonably without
3075  * having a lot of duplicated code.
3076  *
3077  * vma->vm_mm->mmap_lock must be held on entry.
3078  *
3079  * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
3080  * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
3081  *
3082  * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
3083  * has not been released.
3084  *
3085  * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3086  *
3087  * Return: bitwise-OR of %VM_FAULT_ codes.
3088  */
3089 vm_fault_t filemap_fault(struct vm_fault *vmf)
3090 {
3091 	int error;
3092 	struct file *file = vmf->vma->vm_file;
3093 	struct file *fpin = NULL;
3094 	struct address_space *mapping = file->f_mapping;
3095 	struct inode *inode = mapping->host;
3096 	pgoff_t max_idx, index = vmf->pgoff;
3097 	struct folio *folio;
3098 	vm_fault_t ret = 0;
3099 	bool mapping_locked = false;
3100 
3101 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3102 	if (unlikely(index >= max_idx))
3103 		return VM_FAULT_SIGBUS;
3104 
3105 	/*
3106 	 * Do we have something in the page cache already?
3107 	 */
3108 	folio = filemap_get_folio(mapping, index);
3109 	if (likely(folio)) {
3110 		/*
3111 		 * We found the page, so try async readahead before waiting for
3112 		 * the lock.
3113 		 */
3114 		if (!(vmf->flags & FAULT_FLAG_TRIED))
3115 			fpin = do_async_mmap_readahead(vmf, folio);
3116 		if (unlikely(!folio_test_uptodate(folio))) {
3117 			filemap_invalidate_lock_shared(mapping);
3118 			mapping_locked = true;
3119 		}
3120 	} else {
3121 		/* No page in the page cache at all */
3122 		count_vm_event(PGMAJFAULT);
3123 		count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3124 		ret = VM_FAULT_MAJOR;
3125 		fpin = do_sync_mmap_readahead(vmf);
3126 retry_find:
3127 		/*
3128 		 * See comment in filemap_create_folio() why we need
3129 		 * invalidate_lock
3130 		 */
3131 		if (!mapping_locked) {
3132 			filemap_invalidate_lock_shared(mapping);
3133 			mapping_locked = true;
3134 		}
3135 		folio = __filemap_get_folio(mapping, index,
3136 					  FGP_CREAT|FGP_FOR_MMAP,
3137 					  vmf->gfp_mask);
3138 		if (!folio) {
3139 			if (fpin)
3140 				goto out_retry;
3141 			filemap_invalidate_unlock_shared(mapping);
3142 			return VM_FAULT_OOM;
3143 		}
3144 	}
3145 
3146 	if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
3147 		goto out_retry;
3148 
3149 	/* Did it get truncated? */
3150 	if (unlikely(folio->mapping != mapping)) {
3151 		folio_unlock(folio);
3152 		folio_put(folio);
3153 		goto retry_find;
3154 	}
3155 	VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
3156 
3157 	/*
3158 	 * We have a locked page in the page cache, now we need to check
3159 	 * that it's up-to-date. If not, it is going to be due to an error.
3160 	 */
3161 	if (unlikely(!folio_test_uptodate(folio))) {
3162 		/*
3163 		 * The page was in cache and uptodate and now it is not.
3164 		 * Strange but possible since we didn't hold the page lock all
3165 		 * the time. Let's drop everything get the invalidate lock and
3166 		 * try again.
3167 		 */
3168 		if (!mapping_locked) {
3169 			folio_unlock(folio);
3170 			folio_put(folio);
3171 			goto retry_find;
3172 		}
3173 		goto page_not_uptodate;
3174 	}
3175 
3176 	/*
3177 	 * We've made it this far and we had to drop our mmap_lock, now is the
3178 	 * time to return to the upper layer and have it re-find the vma and
3179 	 * redo the fault.
3180 	 */
3181 	if (fpin) {
3182 		folio_unlock(folio);
3183 		goto out_retry;
3184 	}
3185 	if (mapping_locked)
3186 		filemap_invalidate_unlock_shared(mapping);
3187 
3188 	/*
3189 	 * Found the page and have a reference on it.
3190 	 * We must recheck i_size under page lock.
3191 	 */
3192 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3193 	if (unlikely(index >= max_idx)) {
3194 		folio_unlock(folio);
3195 		folio_put(folio);
3196 		return VM_FAULT_SIGBUS;
3197 	}
3198 
3199 	vmf->page = folio_file_page(folio, index);
3200 	return ret | VM_FAULT_LOCKED;
3201 
3202 page_not_uptodate:
3203 	/*
3204 	 * Umm, take care of errors if the page isn't up-to-date.
3205 	 * Try to re-read it _once_. We do this synchronously,
3206 	 * because there really aren't any performance issues here
3207 	 * and we need to check for errors.
3208 	 */
3209 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3210 	error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
3211 	if (fpin)
3212 		goto out_retry;
3213 	folio_put(folio);
3214 
3215 	if (!error || error == AOP_TRUNCATED_PAGE)
3216 		goto retry_find;
3217 	filemap_invalidate_unlock_shared(mapping);
3218 
3219 	return VM_FAULT_SIGBUS;
3220 
3221 out_retry:
3222 	/*
3223 	 * We dropped the mmap_lock, we need to return to the fault handler to
3224 	 * re-find the vma and come back and find our hopefully still populated
3225 	 * page.
3226 	 */
3227 	if (folio)
3228 		folio_put(folio);
3229 	if (mapping_locked)
3230 		filemap_invalidate_unlock_shared(mapping);
3231 	if (fpin)
3232 		fput(fpin);
3233 	return ret | VM_FAULT_RETRY;
3234 }
3235 EXPORT_SYMBOL(filemap_fault);
3236 
3237 static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
3238 {
3239 	struct mm_struct *mm = vmf->vma->vm_mm;
3240 
3241 	/* Huge page is mapped? No need to proceed. */
3242 	if (pmd_trans_huge(*vmf->pmd)) {
3243 		unlock_page(page);
3244 		put_page(page);
3245 		return true;
3246 	}
3247 
3248 	if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3249 		vm_fault_t ret = do_set_pmd(vmf, page);
3250 		if (!ret) {
3251 			/* The page is mapped successfully, reference consumed. */
3252 			unlock_page(page);
3253 			return true;
3254 		}
3255 	}
3256 
3257 	if (pmd_none(*vmf->pmd))
3258 		pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3259 
3260 	/* See comment in handle_pte_fault() */
3261 	if (pmd_devmap_trans_unstable(vmf->pmd)) {
3262 		unlock_page(page);
3263 		put_page(page);
3264 		return true;
3265 	}
3266 
3267 	return false;
3268 }
3269 
3270 static struct folio *next_uptodate_page(struct folio *folio,
3271 				       struct address_space *mapping,
3272 				       struct xa_state *xas, pgoff_t end_pgoff)
3273 {
3274 	unsigned long max_idx;
3275 
3276 	do {
3277 		if (!folio)
3278 			return NULL;
3279 		if (xas_retry(xas, folio))
3280 			continue;
3281 		if (xa_is_value(folio))
3282 			continue;
3283 		if (folio_test_locked(folio))
3284 			continue;
3285 		if (!folio_try_get_rcu(folio))
3286 			continue;
3287 		/* Has the page moved or been split? */
3288 		if (unlikely(folio != xas_reload(xas)))
3289 			goto skip;
3290 		if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3291 			goto skip;
3292 		if (!folio_trylock(folio))
3293 			goto skip;
3294 		if (folio->mapping != mapping)
3295 			goto unlock;
3296 		if (!folio_test_uptodate(folio))
3297 			goto unlock;
3298 		max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3299 		if (xas->xa_index >= max_idx)
3300 			goto unlock;
3301 		return folio;
3302 unlock:
3303 		folio_unlock(folio);
3304 skip:
3305 		folio_put(folio);
3306 	} while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3307 
3308 	return NULL;
3309 }
3310 
3311 static inline struct folio *first_map_page(struct address_space *mapping,
3312 					  struct xa_state *xas,
3313 					  pgoff_t end_pgoff)
3314 {
3315 	return next_uptodate_page(xas_find(xas, end_pgoff),
3316 				  mapping, xas, end_pgoff);
3317 }
3318 
3319 static inline struct folio *next_map_page(struct address_space *mapping,
3320 					 struct xa_state *xas,
3321 					 pgoff_t end_pgoff)
3322 {
3323 	return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3324 				  mapping, xas, end_pgoff);
3325 }
3326 
3327 vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3328 			     pgoff_t start_pgoff, pgoff_t end_pgoff)
3329 {
3330 	struct vm_area_struct *vma = vmf->vma;
3331 	struct file *file = vma->vm_file;
3332 	struct address_space *mapping = file->f_mapping;
3333 	pgoff_t last_pgoff = start_pgoff;
3334 	unsigned long addr;
3335 	XA_STATE(xas, &mapping->i_pages, start_pgoff);
3336 	struct folio *folio;
3337 	struct page *page;
3338 	unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
3339 	vm_fault_t ret = 0;
3340 
3341 	rcu_read_lock();
3342 	folio = first_map_page(mapping, &xas, end_pgoff);
3343 	if (!folio)
3344 		goto out;
3345 
3346 	if (filemap_map_pmd(vmf, &folio->page)) {
3347 		ret = VM_FAULT_NOPAGE;
3348 		goto out;
3349 	}
3350 
3351 	addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3352 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
3353 	do {
3354 again:
3355 		page = folio_file_page(folio, xas.xa_index);
3356 		if (PageHWPoison(page))
3357 			goto unlock;
3358 
3359 		if (mmap_miss > 0)
3360 			mmap_miss--;
3361 
3362 		addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3363 		vmf->pte += xas.xa_index - last_pgoff;
3364 		last_pgoff = xas.xa_index;
3365 
3366 		/*
3367 		 * NOTE: If there're PTE markers, we'll leave them to be
3368 		 * handled in the specific fault path, and it'll prohibit the
3369 		 * fault-around logic.
3370 		 */
3371 		if (!pte_none(*vmf->pte))
3372 			goto unlock;
3373 
3374 		/* We're about to handle the fault */
3375 		if (vmf->address == addr)
3376 			ret = VM_FAULT_NOPAGE;
3377 
3378 		do_set_pte(vmf, page, addr);
3379 		/* no need to invalidate: a not-present page won't be cached */
3380 		update_mmu_cache(vma, addr, vmf->pte);
3381 		if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3382 			xas.xa_index++;
3383 			folio_ref_inc(folio);
3384 			goto again;
3385 		}
3386 		folio_unlock(folio);
3387 		continue;
3388 unlock:
3389 		if (folio_more_pages(folio, xas.xa_index, end_pgoff)) {
3390 			xas.xa_index++;
3391 			goto again;
3392 		}
3393 		folio_unlock(folio);
3394 		folio_put(folio);
3395 	} while ((folio = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3396 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3397 out:
3398 	rcu_read_unlock();
3399 	WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
3400 	return ret;
3401 }
3402 EXPORT_SYMBOL(filemap_map_pages);
3403 
3404 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3405 {
3406 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3407 	struct folio *folio = page_folio(vmf->page);
3408 	vm_fault_t ret = VM_FAULT_LOCKED;
3409 
3410 	sb_start_pagefault(mapping->host->i_sb);
3411 	file_update_time(vmf->vma->vm_file);
3412 	folio_lock(folio);
3413 	if (folio->mapping != mapping) {
3414 		folio_unlock(folio);
3415 		ret = VM_FAULT_NOPAGE;
3416 		goto out;
3417 	}
3418 	/*
3419 	 * We mark the folio dirty already here so that when freeze is in
3420 	 * progress, we are guaranteed that writeback during freezing will
3421 	 * see the dirty folio and writeprotect it again.
3422 	 */
3423 	folio_mark_dirty(folio);
3424 	folio_wait_stable(folio);
3425 out:
3426 	sb_end_pagefault(mapping->host->i_sb);
3427 	return ret;
3428 }
3429 
3430 const struct vm_operations_struct generic_file_vm_ops = {
3431 	.fault		= filemap_fault,
3432 	.map_pages	= filemap_map_pages,
3433 	.page_mkwrite	= filemap_page_mkwrite,
3434 };
3435 
3436 /* This is used for a general mmap of a disk file */
3437 
3438 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3439 {
3440 	struct address_space *mapping = file->f_mapping;
3441 
3442 	if (!mapping->a_ops->read_folio)
3443 		return -ENOEXEC;
3444 	file_accessed(file);
3445 	vma->vm_ops = &generic_file_vm_ops;
3446 	return 0;
3447 }
3448 
3449 /*
3450  * This is for filesystems which do not implement ->writepage.
3451  */
3452 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3453 {
3454 	if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3455 		return -EINVAL;
3456 	return generic_file_mmap(file, vma);
3457 }
3458 #else
3459 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
3460 {
3461 	return VM_FAULT_SIGBUS;
3462 }
3463 int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
3464 {
3465 	return -ENOSYS;
3466 }
3467 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3468 {
3469 	return -ENOSYS;
3470 }
3471 #endif /* CONFIG_MMU */
3472 
3473 EXPORT_SYMBOL(filemap_page_mkwrite);
3474 EXPORT_SYMBOL(generic_file_mmap);
3475 EXPORT_SYMBOL(generic_file_readonly_mmap);
3476 
3477 static struct folio *do_read_cache_folio(struct address_space *mapping,
3478 		pgoff_t index, filler_t filler, struct file *file, gfp_t gfp)
3479 {
3480 	struct folio *folio;
3481 	int err;
3482 
3483 	if (!filler)
3484 		filler = mapping->a_ops->read_folio;
3485 repeat:
3486 	folio = filemap_get_folio(mapping, index);
3487 	if (!folio) {
3488 		folio = filemap_alloc_folio(gfp, 0);
3489 		if (!folio)
3490 			return ERR_PTR(-ENOMEM);
3491 		err = filemap_add_folio(mapping, folio, index, gfp);
3492 		if (unlikely(err)) {
3493 			folio_put(folio);
3494 			if (err == -EEXIST)
3495 				goto repeat;
3496 			/* Presumably ENOMEM for xarray node */
3497 			return ERR_PTR(err);
3498 		}
3499 
3500 		goto filler;
3501 	}
3502 	if (folio_test_uptodate(folio))
3503 		goto out;
3504 
3505 	if (!folio_trylock(folio)) {
3506 		folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
3507 		goto repeat;
3508 	}
3509 
3510 	/* Folio was truncated from mapping */
3511 	if (!folio->mapping) {
3512 		folio_unlock(folio);
3513 		folio_put(folio);
3514 		goto repeat;
3515 	}
3516 
3517 	/* Someone else locked and filled the page in a very small window */
3518 	if (folio_test_uptodate(folio)) {
3519 		folio_unlock(folio);
3520 		goto out;
3521 	}
3522 
3523 filler:
3524 	err = filemap_read_folio(file, filler, folio);
3525 	if (err) {
3526 		folio_put(folio);
3527 		if (err == AOP_TRUNCATED_PAGE)
3528 			goto repeat;
3529 		return ERR_PTR(err);
3530 	}
3531 
3532 out:
3533 	folio_mark_accessed(folio);
3534 	return folio;
3535 }
3536 
3537 /**
3538  * read_cache_folio - Read into page cache, fill it if needed.
3539  * @mapping: The address_space to read from.
3540  * @index: The index to read.
3541  * @filler: Function to perform the read, or NULL to use aops->read_folio().
3542  * @file: Passed to filler function, may be NULL if not required.
3543  *
3544  * Read one page into the page cache.  If it succeeds, the folio returned
3545  * will contain @index, but it may not be the first page of the folio.
3546  *
3547  * If the filler function returns an error, it will be returned to the
3548  * caller.
3549  *
3550  * Context: May sleep.  Expects mapping->invalidate_lock to be held.
3551  * Return: An uptodate folio on success, ERR_PTR() on failure.
3552  */
3553 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
3554 		filler_t filler, struct file *file)
3555 {
3556 	return do_read_cache_folio(mapping, index, filler, file,
3557 			mapping_gfp_mask(mapping));
3558 }
3559 EXPORT_SYMBOL(read_cache_folio);
3560 
3561 static struct page *do_read_cache_page(struct address_space *mapping,
3562 		pgoff_t index, filler_t *filler, struct file *file, gfp_t gfp)
3563 {
3564 	struct folio *folio;
3565 
3566 	folio = do_read_cache_folio(mapping, index, filler, file, gfp);
3567 	if (IS_ERR(folio))
3568 		return &folio->page;
3569 	return folio_file_page(folio, index);
3570 }
3571 
3572 struct page *read_cache_page(struct address_space *mapping,
3573 			pgoff_t index, filler_t *filler, struct file *file)
3574 {
3575 	return do_read_cache_page(mapping, index, filler, file,
3576 			mapping_gfp_mask(mapping));
3577 }
3578 EXPORT_SYMBOL(read_cache_page);
3579 
3580 /**
3581  * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3582  * @mapping:	the page's address_space
3583  * @index:	the page index
3584  * @gfp:	the page allocator flags to use if allocating
3585  *
3586  * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3587  * any new page allocations done using the specified allocation flags.
3588  *
3589  * If the page does not get brought uptodate, return -EIO.
3590  *
3591  * The function expects mapping->invalidate_lock to be already held.
3592  *
3593  * Return: up to date page on success, ERR_PTR() on failure.
3594  */
3595 struct page *read_cache_page_gfp(struct address_space *mapping,
3596 				pgoff_t index,
3597 				gfp_t gfp)
3598 {
3599 	return do_read_cache_page(mapping, index, NULL, NULL, gfp);
3600 }
3601 EXPORT_SYMBOL(read_cache_page_gfp);
3602 
3603 /*
3604  * Warn about a page cache invalidation failure during a direct I/O write.
3605  */
3606 void dio_warn_stale_pagecache(struct file *filp)
3607 {
3608 	static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3609 	char pathname[128];
3610 	char *path;
3611 
3612 	errseq_set(&filp->f_mapping->wb_err, -EIO);
3613 	if (__ratelimit(&_rs)) {
3614 		path = file_path(filp, pathname, sizeof(pathname));
3615 		if (IS_ERR(path))
3616 			path = "(unknown)";
3617 		pr_crit("Page cache invalidation failure on direct I/O.  Possible data corruption due to collision with buffered I/O!\n");
3618 		pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3619 			current->comm);
3620 	}
3621 }
3622 
3623 ssize_t
3624 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3625 {
3626 	struct file	*file = iocb->ki_filp;
3627 	struct address_space *mapping = file->f_mapping;
3628 	struct inode	*inode = mapping->host;
3629 	loff_t		pos = iocb->ki_pos;
3630 	ssize_t		written;
3631 	size_t		write_len;
3632 	pgoff_t		end;
3633 
3634 	write_len = iov_iter_count(from);
3635 	end = (pos + write_len - 1) >> PAGE_SHIFT;
3636 
3637 	if (iocb->ki_flags & IOCB_NOWAIT) {
3638 		/* If there are pages to writeback, return */
3639 		if (filemap_range_has_page(file->f_mapping, pos,
3640 					   pos + write_len - 1))
3641 			return -EAGAIN;
3642 	} else {
3643 		written = filemap_write_and_wait_range(mapping, pos,
3644 							pos + write_len - 1);
3645 		if (written)
3646 			goto out;
3647 	}
3648 
3649 	/*
3650 	 * After a write we want buffered reads to be sure to go to disk to get
3651 	 * the new data.  We invalidate clean cached page from the region we're
3652 	 * about to write.  We do this *before* the write so that we can return
3653 	 * without clobbering -EIOCBQUEUED from ->direct_IO().
3654 	 */
3655 	written = invalidate_inode_pages2_range(mapping,
3656 					pos >> PAGE_SHIFT, end);
3657 	/*
3658 	 * If a page can not be invalidated, return 0 to fall back
3659 	 * to buffered write.
3660 	 */
3661 	if (written) {
3662 		if (written == -EBUSY)
3663 			return 0;
3664 		goto out;
3665 	}
3666 
3667 	written = mapping->a_ops->direct_IO(iocb, from);
3668 
3669 	/*
3670 	 * Finally, try again to invalidate clean pages which might have been
3671 	 * cached by non-direct readahead, or faulted in by get_user_pages()
3672 	 * if the source of the write was an mmap'ed region of the file
3673 	 * we're writing.  Either one is a pretty crazy thing to do,
3674 	 * so we don't support it 100%.  If this invalidation
3675 	 * fails, tough, the write still worked...
3676 	 *
3677 	 * Most of the time we do not need this since dio_complete() will do
3678 	 * the invalidation for us. However there are some file systems that
3679 	 * do not end up with dio_complete() being called, so let's not break
3680 	 * them by removing it completely.
3681 	 *
3682 	 * Noticeable example is a blkdev_direct_IO().
3683 	 *
3684 	 * Skip invalidation for async writes or if mapping has no pages.
3685 	 */
3686 	if (written > 0 && mapping->nrpages &&
3687 	    invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3688 		dio_warn_stale_pagecache(file);
3689 
3690 	if (written > 0) {
3691 		pos += written;
3692 		write_len -= written;
3693 		if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3694 			i_size_write(inode, pos);
3695 			mark_inode_dirty(inode);
3696 		}
3697 		iocb->ki_pos = pos;
3698 	}
3699 	if (written != -EIOCBQUEUED)
3700 		iov_iter_revert(from, write_len - iov_iter_count(from));
3701 out:
3702 	return written;
3703 }
3704 EXPORT_SYMBOL(generic_file_direct_write);
3705 
3706 ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i)
3707 {
3708 	struct file *file = iocb->ki_filp;
3709 	loff_t pos = iocb->ki_pos;
3710 	struct address_space *mapping = file->f_mapping;
3711 	const struct address_space_operations *a_ops = mapping->a_ops;
3712 	long status = 0;
3713 	ssize_t written = 0;
3714 
3715 	do {
3716 		struct page *page;
3717 		unsigned long offset;	/* Offset into pagecache page */
3718 		unsigned long bytes;	/* Bytes to write to page */
3719 		size_t copied;		/* Bytes copied from user */
3720 		void *fsdata;
3721 
3722 		offset = (pos & (PAGE_SIZE - 1));
3723 		bytes = min_t(unsigned long, PAGE_SIZE - offset,
3724 						iov_iter_count(i));
3725 
3726 again:
3727 		/*
3728 		 * Bring in the user page that we will copy from _first_.
3729 		 * Otherwise there's a nasty deadlock on copying from the
3730 		 * same page as we're writing to, without it being marked
3731 		 * up-to-date.
3732 		 */
3733 		if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
3734 			status = -EFAULT;
3735 			break;
3736 		}
3737 
3738 		if (fatal_signal_pending(current)) {
3739 			status = -EINTR;
3740 			break;
3741 		}
3742 
3743 		status = a_ops->write_begin(file, mapping, pos, bytes,
3744 						&page, &fsdata);
3745 		if (unlikely(status < 0))
3746 			break;
3747 
3748 		if (mapping_writably_mapped(mapping))
3749 			flush_dcache_page(page);
3750 
3751 		copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3752 		flush_dcache_page(page);
3753 
3754 		status = a_ops->write_end(file, mapping, pos, bytes, copied,
3755 						page, fsdata);
3756 		if (unlikely(status != copied)) {
3757 			iov_iter_revert(i, copied - max(status, 0L));
3758 			if (unlikely(status < 0))
3759 				break;
3760 		}
3761 		cond_resched();
3762 
3763 		if (unlikely(status == 0)) {
3764 			/*
3765 			 * A short copy made ->write_end() reject the
3766 			 * thing entirely.  Might be memory poisoning
3767 			 * halfway through, might be a race with munmap,
3768 			 * might be severe memory pressure.
3769 			 */
3770 			if (copied)
3771 				bytes = copied;
3772 			goto again;
3773 		}
3774 		pos += status;
3775 		written += status;
3776 
3777 		balance_dirty_pages_ratelimited(mapping);
3778 	} while (iov_iter_count(i));
3779 
3780 	return written ? written : status;
3781 }
3782 EXPORT_SYMBOL(generic_perform_write);
3783 
3784 /**
3785  * __generic_file_write_iter - write data to a file
3786  * @iocb:	IO state structure (file, offset, etc.)
3787  * @from:	iov_iter with data to write
3788  *
3789  * This function does all the work needed for actually writing data to a
3790  * file. It does all basic checks, removes SUID from the file, updates
3791  * modification times and calls proper subroutines depending on whether we
3792  * do direct IO or a standard buffered write.
3793  *
3794  * It expects i_rwsem to be grabbed unless we work on a block device or similar
3795  * object which does not need locking at all.
3796  *
3797  * This function does *not* take care of syncing data in case of O_SYNC write.
3798  * A caller has to handle it. This is mainly due to the fact that we want to
3799  * avoid syncing under i_rwsem.
3800  *
3801  * Return:
3802  * * number of bytes written, even for truncated writes
3803  * * negative error code if no data has been written at all
3804  */
3805 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3806 {
3807 	struct file *file = iocb->ki_filp;
3808 	struct address_space *mapping = file->f_mapping;
3809 	struct inode 	*inode = mapping->host;
3810 	ssize_t		written = 0;
3811 	ssize_t		err;
3812 	ssize_t		status;
3813 
3814 	/* We can write back this queue in page reclaim */
3815 	current->backing_dev_info = inode_to_bdi(inode);
3816 	err = file_remove_privs(file);
3817 	if (err)
3818 		goto out;
3819 
3820 	err = file_update_time(file);
3821 	if (err)
3822 		goto out;
3823 
3824 	if (iocb->ki_flags & IOCB_DIRECT) {
3825 		loff_t pos, endbyte;
3826 
3827 		written = generic_file_direct_write(iocb, from);
3828 		/*
3829 		 * If the write stopped short of completing, fall back to
3830 		 * buffered writes.  Some filesystems do this for writes to
3831 		 * holes, for example.  For DAX files, a buffered write will
3832 		 * not succeed (even if it did, DAX does not handle dirty
3833 		 * page-cache pages correctly).
3834 		 */
3835 		if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3836 			goto out;
3837 
3838 		pos = iocb->ki_pos;
3839 		status = generic_perform_write(iocb, from);
3840 		/*
3841 		 * If generic_perform_write() returned a synchronous error
3842 		 * then we want to return the number of bytes which were
3843 		 * direct-written, or the error code if that was zero.  Note
3844 		 * that this differs from normal direct-io semantics, which
3845 		 * will return -EFOO even if some bytes were written.
3846 		 */
3847 		if (unlikely(status < 0)) {
3848 			err = status;
3849 			goto out;
3850 		}
3851 		/*
3852 		 * We need to ensure that the page cache pages are written to
3853 		 * disk and invalidated to preserve the expected O_DIRECT
3854 		 * semantics.
3855 		 */
3856 		endbyte = pos + status - 1;
3857 		err = filemap_write_and_wait_range(mapping, pos, endbyte);
3858 		if (err == 0) {
3859 			iocb->ki_pos = endbyte + 1;
3860 			written += status;
3861 			invalidate_mapping_pages(mapping,
3862 						 pos >> PAGE_SHIFT,
3863 						 endbyte >> PAGE_SHIFT);
3864 		} else {
3865 			/*
3866 			 * We don't know how much we wrote, so just return
3867 			 * the number of bytes which were direct-written
3868 			 */
3869 		}
3870 	} else {
3871 		written = generic_perform_write(iocb, from);
3872 		if (likely(written > 0))
3873 			iocb->ki_pos += written;
3874 	}
3875 out:
3876 	current->backing_dev_info = NULL;
3877 	return written ? written : err;
3878 }
3879 EXPORT_SYMBOL(__generic_file_write_iter);
3880 
3881 /**
3882  * generic_file_write_iter - write data to a file
3883  * @iocb:	IO state structure
3884  * @from:	iov_iter with data to write
3885  *
3886  * This is a wrapper around __generic_file_write_iter() to be used by most
3887  * filesystems. It takes care of syncing the file in case of O_SYNC file
3888  * and acquires i_rwsem as needed.
3889  * Return:
3890  * * negative error code if no data has been written at all of
3891  *   vfs_fsync_range() failed for a synchronous write
3892  * * number of bytes written, even for truncated writes
3893  */
3894 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3895 {
3896 	struct file *file = iocb->ki_filp;
3897 	struct inode *inode = file->f_mapping->host;
3898 	ssize_t ret;
3899 
3900 	inode_lock(inode);
3901 	ret = generic_write_checks(iocb, from);
3902 	if (ret > 0)
3903 		ret = __generic_file_write_iter(iocb, from);
3904 	inode_unlock(inode);
3905 
3906 	if (ret > 0)
3907 		ret = generic_write_sync(iocb, ret);
3908 	return ret;
3909 }
3910 EXPORT_SYMBOL(generic_file_write_iter);
3911 
3912 /**
3913  * filemap_release_folio() - Release fs-specific metadata on a folio.
3914  * @folio: The folio which the kernel is trying to free.
3915  * @gfp: Memory allocation flags (and I/O mode).
3916  *
3917  * The address_space is trying to release any data attached to a folio
3918  * (presumably at folio->private).
3919  *
3920  * This will also be called if the private_2 flag is set on a page,
3921  * indicating that the folio has other metadata associated with it.
3922  *
3923  * The @gfp argument specifies whether I/O may be performed to release
3924  * this page (__GFP_IO), and whether the call may block
3925  * (__GFP_RECLAIM & __GFP_FS).
3926  *
3927  * Return: %true if the release was successful, otherwise %false.
3928  */
3929 bool filemap_release_folio(struct folio *folio, gfp_t gfp)
3930 {
3931 	struct address_space * const mapping = folio->mapping;
3932 
3933 	BUG_ON(!folio_test_locked(folio));
3934 	if (folio_test_writeback(folio))
3935 		return false;
3936 
3937 	if (mapping && mapping->a_ops->release_folio)
3938 		return mapping->a_ops->release_folio(folio, gfp);
3939 	return try_to_free_buffers(folio);
3940 }
3941 EXPORT_SYMBOL(filemap_release_folio);
3942