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