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