개념 설명 전체 · v6.18.37 / mm/filemap.c

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