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