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