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