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