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