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