xref: /openbmc/linux/mm/filemap.c (revision afddba49d18f346e5cc2938b6ed7c512db18ca68)
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/module.h>
13 #include <linux/slab.h>
14 #include <linux/compiler.h>
15 #include <linux/fs.h>
16 #include <linux/uaccess.h>
17 #include <linux/aio.h>
18 #include <linux/capability.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/mm.h>
21 #include <linux/swap.h>
22 #include <linux/mman.h>
23 #include <linux/pagemap.h>
24 #include <linux/file.h>
25 #include <linux/uio.h>
26 #include <linux/hash.h>
27 #include <linux/writeback.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/security.h>
31 #include <linux/syscalls.h>
32 #include <linux/cpuset.h>
33 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
34 #include "internal.h"
35 
36 /*
37  * FIXME: remove all knowledge of the buffer layer from the core VM
38  */
39 #include <linux/buffer_head.h> /* for generic_osync_inode */
40 
41 #include <asm/mman.h>
42 
43 static ssize_t
44 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
45 	loff_t offset, unsigned long nr_segs);
46 
47 /*
48  * Shared mappings implemented 30.11.1994. It's not fully working yet,
49  * though.
50  *
51  * Shared mappings now work. 15.8.1995  Bruno.
52  *
53  * finished 'unifying' the page and buffer cache and SMP-threaded the
54  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
55  *
56  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
57  */
58 
59 /*
60  * Lock ordering:
61  *
62  *  ->i_mmap_lock		(vmtruncate)
63  *    ->private_lock		(__free_pte->__set_page_dirty_buffers)
64  *      ->swap_lock		(exclusive_swap_page, others)
65  *        ->mapping->tree_lock
66  *
67  *  ->i_mutex
68  *    ->i_mmap_lock		(truncate->unmap_mapping_range)
69  *
70  *  ->mmap_sem
71  *    ->i_mmap_lock
72  *      ->page_table_lock or pte_lock	(various, mainly in memory.c)
73  *        ->mapping->tree_lock	(arch-dependent flush_dcache_mmap_lock)
74  *
75  *  ->mmap_sem
76  *    ->lock_page		(access_process_vm)
77  *
78  *  ->i_mutex			(generic_file_buffered_write)
79  *    ->mmap_sem		(fault_in_pages_readable->do_page_fault)
80  *
81  *  ->i_mutex
82  *    ->i_alloc_sem             (various)
83  *
84  *  ->inode_lock
85  *    ->sb_lock			(fs/fs-writeback.c)
86  *    ->mapping->tree_lock	(__sync_single_inode)
87  *
88  *  ->i_mmap_lock
89  *    ->anon_vma.lock		(vma_adjust)
90  *
91  *  ->anon_vma.lock
92  *    ->page_table_lock or pte_lock	(anon_vma_prepare and various)
93  *
94  *  ->page_table_lock or pte_lock
95  *    ->swap_lock		(try_to_unmap_one)
96  *    ->private_lock		(try_to_unmap_one)
97  *    ->tree_lock		(try_to_unmap_one)
98  *    ->zone.lru_lock		(follow_page->mark_page_accessed)
99  *    ->zone.lru_lock		(check_pte_range->isolate_lru_page)
100  *    ->private_lock		(page_remove_rmap->set_page_dirty)
101  *    ->tree_lock		(page_remove_rmap->set_page_dirty)
102  *    ->inode_lock		(page_remove_rmap->set_page_dirty)
103  *    ->inode_lock		(zap_pte_range->set_page_dirty)
104  *    ->private_lock		(zap_pte_range->__set_page_dirty_buffers)
105  *
106  *  ->task->proc_lock
107  *    ->dcache_lock		(proc_pid_lookup)
108  */
109 
110 /*
111  * Remove a page from the page cache and free it. Caller has to make
112  * sure the page is locked and that nobody else uses it - or that usage
113  * is safe.  The caller must hold a write_lock on the mapping's tree_lock.
114  */
115 void __remove_from_page_cache(struct page *page)
116 {
117 	struct address_space *mapping = page->mapping;
118 
119 	radix_tree_delete(&mapping->page_tree, page->index);
120 	page->mapping = NULL;
121 	mapping->nrpages--;
122 	__dec_zone_page_state(page, NR_FILE_PAGES);
123 	BUG_ON(page_mapped(page));
124 }
125 
126 void remove_from_page_cache(struct page *page)
127 {
128 	struct address_space *mapping = page->mapping;
129 
130 	BUG_ON(!PageLocked(page));
131 
132 	write_lock_irq(&mapping->tree_lock);
133 	__remove_from_page_cache(page);
134 	write_unlock_irq(&mapping->tree_lock);
135 }
136 
137 static int sync_page(void *word)
138 {
139 	struct address_space *mapping;
140 	struct page *page;
141 
142 	page = container_of((unsigned long *)word, struct page, flags);
143 
144 	/*
145 	 * page_mapping() is being called without PG_locked held.
146 	 * Some knowledge of the state and use of the page is used to
147 	 * reduce the requirements down to a memory barrier.
148 	 * The danger here is of a stale page_mapping() return value
149 	 * indicating a struct address_space different from the one it's
150 	 * associated with when it is associated with one.
151 	 * After smp_mb(), it's either the correct page_mapping() for
152 	 * the page, or an old page_mapping() and the page's own
153 	 * page_mapping() has gone NULL.
154 	 * The ->sync_page() address_space operation must tolerate
155 	 * page_mapping() going NULL. By an amazing coincidence,
156 	 * this comes about because none of the users of the page
157 	 * in the ->sync_page() methods make essential use of the
158 	 * page_mapping(), merely passing the page down to the backing
159 	 * device's unplug functions when it's non-NULL, which in turn
160 	 * ignore it for all cases but swap, where only page_private(page) is
161 	 * of interest. When page_mapping() does go NULL, the entire
162 	 * call stack gracefully ignores the page and returns.
163 	 * -- wli
164 	 */
165 	smp_mb();
166 	mapping = page_mapping(page);
167 	if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
168 		mapping->a_ops->sync_page(page);
169 	io_schedule();
170 	return 0;
171 }
172 
173 /**
174  * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
175  * @mapping:	address space structure to write
176  * @start:	offset in bytes where the range starts
177  * @end:	offset in bytes where the range ends (inclusive)
178  * @sync_mode:	enable synchronous operation
179  *
180  * Start writeback against all of a mapping's dirty pages that lie
181  * within the byte offsets <start, end> inclusive.
182  *
183  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
184  * opposed to a regular memory cleansing writeback.  The difference between
185  * these two operations is that if a dirty page/buffer is encountered, it must
186  * be waited upon, and not just skipped over.
187  */
188 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
189 				loff_t end, int sync_mode)
190 {
191 	int ret;
192 	struct writeback_control wbc = {
193 		.sync_mode = sync_mode,
194 		.nr_to_write = mapping->nrpages * 2,
195 		.range_start = start,
196 		.range_end = end,
197 	};
198 
199 	if (!mapping_cap_writeback_dirty(mapping))
200 		return 0;
201 
202 	ret = do_writepages(mapping, &wbc);
203 	return ret;
204 }
205 
206 static inline int __filemap_fdatawrite(struct address_space *mapping,
207 	int sync_mode)
208 {
209 	return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
210 }
211 
212 int filemap_fdatawrite(struct address_space *mapping)
213 {
214 	return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
215 }
216 EXPORT_SYMBOL(filemap_fdatawrite);
217 
218 static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
219 				loff_t end)
220 {
221 	return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
222 }
223 
224 /**
225  * filemap_flush - mostly a non-blocking flush
226  * @mapping:	target address_space
227  *
228  * This is a mostly non-blocking flush.  Not suitable for data-integrity
229  * purposes - I/O may not be started against all dirty pages.
230  */
231 int filemap_flush(struct address_space *mapping)
232 {
233 	return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
234 }
235 EXPORT_SYMBOL(filemap_flush);
236 
237 /**
238  * wait_on_page_writeback_range - wait for writeback to complete
239  * @mapping:	target address_space
240  * @start:	beginning page index
241  * @end:	ending page index
242  *
243  * Wait for writeback to complete against pages indexed by start->end
244  * inclusive
245  */
246 int wait_on_page_writeback_range(struct address_space *mapping,
247 				pgoff_t start, pgoff_t end)
248 {
249 	struct pagevec pvec;
250 	int nr_pages;
251 	int ret = 0;
252 	pgoff_t index;
253 
254 	if (end < start)
255 		return 0;
256 
257 	pagevec_init(&pvec, 0);
258 	index = start;
259 	while ((index <= end) &&
260 			(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
261 			PAGECACHE_TAG_WRITEBACK,
262 			min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
263 		unsigned i;
264 
265 		for (i = 0; i < nr_pages; i++) {
266 			struct page *page = pvec.pages[i];
267 
268 			/* until radix tree lookup accepts end_index */
269 			if (page->index > end)
270 				continue;
271 
272 			wait_on_page_writeback(page);
273 			if (PageError(page))
274 				ret = -EIO;
275 		}
276 		pagevec_release(&pvec);
277 		cond_resched();
278 	}
279 
280 	/* Check for outstanding write errors */
281 	if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
282 		ret = -ENOSPC;
283 	if (test_and_clear_bit(AS_EIO, &mapping->flags))
284 		ret = -EIO;
285 
286 	return ret;
287 }
288 
289 /**
290  * sync_page_range - write and wait on all pages in the passed range
291  * @inode:	target inode
292  * @mapping:	target address_space
293  * @pos:	beginning offset in pages to write
294  * @count:	number of bytes to write
295  *
296  * Write and wait upon all the pages in the passed range.  This is a "data
297  * integrity" operation.  It waits upon in-flight writeout before starting and
298  * waiting upon new writeout.  If there was an IO error, return it.
299  *
300  * We need to re-take i_mutex during the generic_osync_inode list walk because
301  * it is otherwise livelockable.
302  */
303 int sync_page_range(struct inode *inode, struct address_space *mapping,
304 			loff_t pos, loff_t count)
305 {
306 	pgoff_t start = pos >> PAGE_CACHE_SHIFT;
307 	pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
308 	int ret;
309 
310 	if (!mapping_cap_writeback_dirty(mapping) || !count)
311 		return 0;
312 	ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
313 	if (ret == 0) {
314 		mutex_lock(&inode->i_mutex);
315 		ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
316 		mutex_unlock(&inode->i_mutex);
317 	}
318 	if (ret == 0)
319 		ret = wait_on_page_writeback_range(mapping, start, end);
320 	return ret;
321 }
322 EXPORT_SYMBOL(sync_page_range);
323 
324 /**
325  * sync_page_range_nolock
326  * @inode:	target inode
327  * @mapping:	target address_space
328  * @pos:	beginning offset in pages to write
329  * @count:	number of bytes to write
330  *
331  * Note: Holding i_mutex across sync_page_range_nolock() is not a good idea
332  * as it forces O_SYNC writers to different parts of the same file
333  * to be serialised right until io completion.
334  */
335 int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
336 			   loff_t pos, loff_t count)
337 {
338 	pgoff_t start = pos >> PAGE_CACHE_SHIFT;
339 	pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
340 	int ret;
341 
342 	if (!mapping_cap_writeback_dirty(mapping) || !count)
343 		return 0;
344 	ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
345 	if (ret == 0)
346 		ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
347 	if (ret == 0)
348 		ret = wait_on_page_writeback_range(mapping, start, end);
349 	return ret;
350 }
351 EXPORT_SYMBOL(sync_page_range_nolock);
352 
353 /**
354  * filemap_fdatawait - wait for all under-writeback pages to complete
355  * @mapping: address space structure to wait for
356  *
357  * Walk the list of under-writeback pages of the given address space
358  * and wait for all of them.
359  */
360 int filemap_fdatawait(struct address_space *mapping)
361 {
362 	loff_t i_size = i_size_read(mapping->host);
363 
364 	if (i_size == 0)
365 		return 0;
366 
367 	return wait_on_page_writeback_range(mapping, 0,
368 				(i_size - 1) >> PAGE_CACHE_SHIFT);
369 }
370 EXPORT_SYMBOL(filemap_fdatawait);
371 
372 int filemap_write_and_wait(struct address_space *mapping)
373 {
374 	int err = 0;
375 
376 	if (mapping->nrpages) {
377 		err = filemap_fdatawrite(mapping);
378 		/*
379 		 * Even if the above returned error, the pages may be
380 		 * written partially (e.g. -ENOSPC), so we wait for it.
381 		 * But the -EIO is special case, it may indicate the worst
382 		 * thing (e.g. bug) happened, so we avoid waiting for it.
383 		 */
384 		if (err != -EIO) {
385 			int err2 = filemap_fdatawait(mapping);
386 			if (!err)
387 				err = err2;
388 		}
389 	}
390 	return err;
391 }
392 EXPORT_SYMBOL(filemap_write_and_wait);
393 
394 /**
395  * filemap_write_and_wait_range - write out & wait on a file range
396  * @mapping:	the address_space for the pages
397  * @lstart:	offset in bytes where the range starts
398  * @lend:	offset in bytes where the range ends (inclusive)
399  *
400  * Write out and wait upon file offsets lstart->lend, inclusive.
401  *
402  * Note that `lend' is inclusive (describes the last byte to be written) so
403  * that this function can be used to write to the very end-of-file (end = -1).
404  */
405 int filemap_write_and_wait_range(struct address_space *mapping,
406 				 loff_t lstart, loff_t lend)
407 {
408 	int err = 0;
409 
410 	if (mapping->nrpages) {
411 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
412 						 WB_SYNC_ALL);
413 		/* See comment of filemap_write_and_wait() */
414 		if (err != -EIO) {
415 			int err2 = wait_on_page_writeback_range(mapping,
416 						lstart >> PAGE_CACHE_SHIFT,
417 						lend >> PAGE_CACHE_SHIFT);
418 			if (!err)
419 				err = err2;
420 		}
421 	}
422 	return err;
423 }
424 
425 /**
426  * add_to_page_cache - add newly allocated pagecache pages
427  * @page:	page to add
428  * @mapping:	the page's address_space
429  * @offset:	page index
430  * @gfp_mask:	page allocation mode
431  *
432  * This function is used to add newly allocated pagecache pages;
433  * the page is new, so we can just run SetPageLocked() against it.
434  * The other page state flags were set by rmqueue().
435  *
436  * This function does not add the page to the LRU.  The caller must do that.
437  */
438 int add_to_page_cache(struct page *page, struct address_space *mapping,
439 		pgoff_t offset, gfp_t gfp_mask)
440 {
441 	int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
442 
443 	if (error == 0) {
444 		write_lock_irq(&mapping->tree_lock);
445 		error = radix_tree_insert(&mapping->page_tree, offset, page);
446 		if (!error) {
447 			page_cache_get(page);
448 			SetPageLocked(page);
449 			page->mapping = mapping;
450 			page->index = offset;
451 			mapping->nrpages++;
452 			__inc_zone_page_state(page, NR_FILE_PAGES);
453 		}
454 		write_unlock_irq(&mapping->tree_lock);
455 		radix_tree_preload_end();
456 	}
457 	return error;
458 }
459 EXPORT_SYMBOL(add_to_page_cache);
460 
461 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
462 				pgoff_t offset, gfp_t gfp_mask)
463 {
464 	int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
465 	if (ret == 0)
466 		lru_cache_add(page);
467 	return ret;
468 }
469 
470 #ifdef CONFIG_NUMA
471 struct page *__page_cache_alloc(gfp_t gfp)
472 {
473 	if (cpuset_do_page_mem_spread()) {
474 		int n = cpuset_mem_spread_node();
475 		return alloc_pages_node(n, gfp, 0);
476 	}
477 	return alloc_pages(gfp, 0);
478 }
479 EXPORT_SYMBOL(__page_cache_alloc);
480 #endif
481 
482 static int __sleep_on_page_lock(void *word)
483 {
484 	io_schedule();
485 	return 0;
486 }
487 
488 /*
489  * In order to wait for pages to become available there must be
490  * waitqueues associated with pages. By using a hash table of
491  * waitqueues where the bucket discipline is to maintain all
492  * waiters on the same queue and wake all when any of the pages
493  * become available, and for the woken contexts to check to be
494  * sure the appropriate page became available, this saves space
495  * at a cost of "thundering herd" phenomena during rare hash
496  * collisions.
497  */
498 static wait_queue_head_t *page_waitqueue(struct page *page)
499 {
500 	const struct zone *zone = page_zone(page);
501 
502 	return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
503 }
504 
505 static inline void wake_up_page(struct page *page, int bit)
506 {
507 	__wake_up_bit(page_waitqueue(page), &page->flags, bit);
508 }
509 
510 void fastcall wait_on_page_bit(struct page *page, int bit_nr)
511 {
512 	DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
513 
514 	if (test_bit(bit_nr, &page->flags))
515 		__wait_on_bit(page_waitqueue(page), &wait, sync_page,
516 							TASK_UNINTERRUPTIBLE);
517 }
518 EXPORT_SYMBOL(wait_on_page_bit);
519 
520 /**
521  * unlock_page - unlock a locked page
522  * @page: the page
523  *
524  * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
525  * Also wakes sleepers in wait_on_page_writeback() because the wakeup
526  * mechananism between PageLocked pages and PageWriteback pages is shared.
527  * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
528  *
529  * The first mb is necessary to safely close the critical section opened by the
530  * TestSetPageLocked(), the second mb is necessary to enforce ordering between
531  * the clear_bit and the read of the waitqueue (to avoid SMP races with a
532  * parallel wait_on_page_locked()).
533  */
534 void fastcall unlock_page(struct page *page)
535 {
536 	smp_mb__before_clear_bit();
537 	if (!TestClearPageLocked(page))
538 		BUG();
539 	smp_mb__after_clear_bit();
540 	wake_up_page(page, PG_locked);
541 }
542 EXPORT_SYMBOL(unlock_page);
543 
544 /**
545  * end_page_writeback - end writeback against a page
546  * @page: the page
547  */
548 void end_page_writeback(struct page *page)
549 {
550 	if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
551 		if (!test_clear_page_writeback(page))
552 			BUG();
553 	}
554 	smp_mb__after_clear_bit();
555 	wake_up_page(page, PG_writeback);
556 }
557 EXPORT_SYMBOL(end_page_writeback);
558 
559 /**
560  * __lock_page - get a lock on the page, assuming we need to sleep to get it
561  * @page: the page to lock
562  *
563  * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary.  If some
564  * random driver's requestfn sets TASK_RUNNING, we could busywait.  However
565  * chances are that on the second loop, the block layer's plug list is empty,
566  * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
567  */
568 void fastcall __lock_page(struct page *page)
569 {
570 	DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
571 
572 	__wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
573 							TASK_UNINTERRUPTIBLE);
574 }
575 EXPORT_SYMBOL(__lock_page);
576 
577 /*
578  * Variant of lock_page that does not require the caller to hold a reference
579  * on the page's mapping.
580  */
581 void fastcall __lock_page_nosync(struct page *page)
582 {
583 	DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
584 	__wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
585 							TASK_UNINTERRUPTIBLE);
586 }
587 
588 /**
589  * find_get_page - find and get a page reference
590  * @mapping: the address_space to search
591  * @offset: the page index
592  *
593  * Is there a pagecache struct page at the given (mapping, offset) tuple?
594  * If yes, increment its refcount and return it; if no, return NULL.
595  */
596 struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
597 {
598 	struct page *page;
599 
600 	read_lock_irq(&mapping->tree_lock);
601 	page = radix_tree_lookup(&mapping->page_tree, offset);
602 	if (page)
603 		page_cache_get(page);
604 	read_unlock_irq(&mapping->tree_lock);
605 	return page;
606 }
607 EXPORT_SYMBOL(find_get_page);
608 
609 /**
610  * find_lock_page - locate, pin and lock a pagecache page
611  * @mapping: the address_space to search
612  * @offset: the page index
613  *
614  * Locates the desired pagecache page, locks it, increments its reference
615  * count and returns its address.
616  *
617  * Returns zero if the page was not present. find_lock_page() may sleep.
618  */
619 struct page *find_lock_page(struct address_space *mapping,
620 				pgoff_t offset)
621 {
622 	struct page *page;
623 
624 repeat:
625 	read_lock_irq(&mapping->tree_lock);
626 	page = radix_tree_lookup(&mapping->page_tree, offset);
627 	if (page) {
628 		page_cache_get(page);
629 		if (TestSetPageLocked(page)) {
630 			read_unlock_irq(&mapping->tree_lock);
631 			__lock_page(page);
632 
633 			/* Has the page been truncated while we slept? */
634 			if (unlikely(page->mapping != mapping)) {
635 				unlock_page(page);
636 				page_cache_release(page);
637 				goto repeat;
638 			}
639 			VM_BUG_ON(page->index != offset);
640 			goto out;
641 		}
642 	}
643 	read_unlock_irq(&mapping->tree_lock);
644 out:
645 	return page;
646 }
647 EXPORT_SYMBOL(find_lock_page);
648 
649 /**
650  * find_or_create_page - locate or add a pagecache page
651  * @mapping: the page's address_space
652  * @index: the page's index into the mapping
653  * @gfp_mask: page allocation mode
654  *
655  * Locates a page in the pagecache.  If the page is not present, a new page
656  * is allocated using @gfp_mask and is added to the pagecache and to the VM's
657  * LRU list.  The returned page is locked and has its reference count
658  * incremented.
659  *
660  * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
661  * allocation!
662  *
663  * find_or_create_page() returns the desired page's address, or zero on
664  * memory exhaustion.
665  */
666 struct page *find_or_create_page(struct address_space *mapping,
667 		pgoff_t index, gfp_t gfp_mask)
668 {
669 	struct page *page;
670 	int err;
671 repeat:
672 	page = find_lock_page(mapping, index);
673 	if (!page) {
674 		page = __page_cache_alloc(gfp_mask);
675 		if (!page)
676 			return NULL;
677 		err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
678 		if (unlikely(err)) {
679 			page_cache_release(page);
680 			page = NULL;
681 			if (err == -EEXIST)
682 				goto repeat;
683 		}
684 	}
685 	return page;
686 }
687 EXPORT_SYMBOL(find_or_create_page);
688 
689 /**
690  * find_get_pages - gang pagecache lookup
691  * @mapping:	The address_space to search
692  * @start:	The starting page index
693  * @nr_pages:	The maximum number of pages
694  * @pages:	Where the resulting pages are placed
695  *
696  * find_get_pages() will search for and return a group of up to
697  * @nr_pages pages in the mapping.  The pages are placed at @pages.
698  * find_get_pages() takes a reference against the returned pages.
699  *
700  * The search returns a group of mapping-contiguous pages with ascending
701  * indexes.  There may be holes in the indices due to not-present pages.
702  *
703  * find_get_pages() returns the number of pages which were found.
704  */
705 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
706 			    unsigned int nr_pages, struct page **pages)
707 {
708 	unsigned int i;
709 	unsigned int ret;
710 
711 	read_lock_irq(&mapping->tree_lock);
712 	ret = radix_tree_gang_lookup(&mapping->page_tree,
713 				(void **)pages, start, nr_pages);
714 	for (i = 0; i < ret; i++)
715 		page_cache_get(pages[i]);
716 	read_unlock_irq(&mapping->tree_lock);
717 	return ret;
718 }
719 
720 /**
721  * find_get_pages_contig - gang contiguous pagecache lookup
722  * @mapping:	The address_space to search
723  * @index:	The starting page index
724  * @nr_pages:	The maximum number of pages
725  * @pages:	Where the resulting pages are placed
726  *
727  * find_get_pages_contig() works exactly like find_get_pages(), except
728  * that the returned number of pages are guaranteed to be contiguous.
729  *
730  * find_get_pages_contig() returns the number of pages which were found.
731  */
732 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
733 			       unsigned int nr_pages, struct page **pages)
734 {
735 	unsigned int i;
736 	unsigned int ret;
737 
738 	read_lock_irq(&mapping->tree_lock);
739 	ret = radix_tree_gang_lookup(&mapping->page_tree,
740 				(void **)pages, index, nr_pages);
741 	for (i = 0; i < ret; i++) {
742 		if (pages[i]->mapping == NULL || pages[i]->index != index)
743 			break;
744 
745 		page_cache_get(pages[i]);
746 		index++;
747 	}
748 	read_unlock_irq(&mapping->tree_lock);
749 	return i;
750 }
751 EXPORT_SYMBOL(find_get_pages_contig);
752 
753 /**
754  * find_get_pages_tag - find and return pages that match @tag
755  * @mapping:	the address_space to search
756  * @index:	the starting page index
757  * @tag:	the tag index
758  * @nr_pages:	the maximum number of pages
759  * @pages:	where the resulting pages are placed
760  *
761  * Like find_get_pages, except we only return pages which are tagged with
762  * @tag.   We update @index to index the next page for the traversal.
763  */
764 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
765 			int tag, unsigned int nr_pages, struct page **pages)
766 {
767 	unsigned int i;
768 	unsigned int ret;
769 
770 	read_lock_irq(&mapping->tree_lock);
771 	ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
772 				(void **)pages, *index, nr_pages, tag);
773 	for (i = 0; i < ret; i++)
774 		page_cache_get(pages[i]);
775 	if (ret)
776 		*index = pages[ret - 1]->index + 1;
777 	read_unlock_irq(&mapping->tree_lock);
778 	return ret;
779 }
780 EXPORT_SYMBOL(find_get_pages_tag);
781 
782 /**
783  * grab_cache_page_nowait - returns locked page at given index in given cache
784  * @mapping: target address_space
785  * @index: the page index
786  *
787  * Same as grab_cache_page(), but do not wait if the page is unavailable.
788  * This is intended for speculative data generators, where the data can
789  * be regenerated if the page couldn't be grabbed.  This routine should
790  * be safe to call while holding the lock for another page.
791  *
792  * Clear __GFP_FS when allocating the page to avoid recursion into the fs
793  * and deadlock against the caller's locked page.
794  */
795 struct page *
796 grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
797 {
798 	struct page *page = find_get_page(mapping, index);
799 
800 	if (page) {
801 		if (!TestSetPageLocked(page))
802 			return page;
803 		page_cache_release(page);
804 		return NULL;
805 	}
806 	page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
807 	if (page && add_to_page_cache_lru(page, mapping, index, GFP_KERNEL)) {
808 		page_cache_release(page);
809 		page = NULL;
810 	}
811 	return page;
812 }
813 EXPORT_SYMBOL(grab_cache_page_nowait);
814 
815 /*
816  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
817  * a _large_ part of the i/o request. Imagine the worst scenario:
818  *
819  *      ---R__________________________________________B__________
820  *         ^ reading here                             ^ bad block(assume 4k)
821  *
822  * read(R) => miss => readahead(R...B) => media error => frustrating retries
823  * => failing the whole request => read(R) => read(R+1) =>
824  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
825  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
826  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
827  *
828  * It is going insane. Fix it by quickly scaling down the readahead size.
829  */
830 static void shrink_readahead_size_eio(struct file *filp,
831 					struct file_ra_state *ra)
832 {
833 	if (!ra->ra_pages)
834 		return;
835 
836 	ra->ra_pages /= 4;
837 }
838 
839 /**
840  * do_generic_mapping_read - generic file read routine
841  * @mapping:	address_space to be read
842  * @_ra:	file's readahead state
843  * @filp:	the file to read
844  * @ppos:	current file position
845  * @desc:	read_descriptor
846  * @actor:	read method
847  *
848  * This is a generic file read routine, and uses the
849  * mapping->a_ops->readpage() function for the actual low-level stuff.
850  *
851  * This is really ugly. But the goto's actually try to clarify some
852  * of the logic when it comes to error handling etc.
853  *
854  * Note the struct file* is only passed for the use of readpage.
855  * It may be NULL.
856  */
857 void do_generic_mapping_read(struct address_space *mapping,
858 			     struct file_ra_state *ra,
859 			     struct file *filp,
860 			     loff_t *ppos,
861 			     read_descriptor_t *desc,
862 			     read_actor_t actor)
863 {
864 	struct inode *inode = mapping->host;
865 	pgoff_t index;
866 	pgoff_t last_index;
867 	pgoff_t prev_index;
868 	unsigned long offset;      /* offset into pagecache page */
869 	unsigned int prev_offset;
870 	int error;
871 
872 	index = *ppos >> PAGE_CACHE_SHIFT;
873 	prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
874 	prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
875 	last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
876 	offset = *ppos & ~PAGE_CACHE_MASK;
877 
878 	for (;;) {
879 		struct page *page;
880 		pgoff_t end_index;
881 		loff_t isize;
882 		unsigned long nr, ret;
883 
884 		cond_resched();
885 find_page:
886 		page = find_get_page(mapping, index);
887 		if (!page) {
888 			page_cache_sync_readahead(mapping,
889 					ra, filp,
890 					index, last_index - index);
891 			page = find_get_page(mapping, index);
892 			if (unlikely(page == NULL))
893 				goto no_cached_page;
894 		}
895 		if (PageReadahead(page)) {
896 			page_cache_async_readahead(mapping,
897 					ra, filp, page,
898 					index, last_index - index);
899 		}
900 		if (!PageUptodate(page))
901 			goto page_not_up_to_date;
902 page_ok:
903 		/*
904 		 * i_size must be checked after we know the page is Uptodate.
905 		 *
906 		 * Checking i_size after the check allows us to calculate
907 		 * the correct value for "nr", which means the zero-filled
908 		 * part of the page is not copied back to userspace (unless
909 		 * another truncate extends the file - this is desired though).
910 		 */
911 
912 		isize = i_size_read(inode);
913 		end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
914 		if (unlikely(!isize || index > end_index)) {
915 			page_cache_release(page);
916 			goto out;
917 		}
918 
919 		/* nr is the maximum number of bytes to copy from this page */
920 		nr = PAGE_CACHE_SIZE;
921 		if (index == end_index) {
922 			nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
923 			if (nr <= offset) {
924 				page_cache_release(page);
925 				goto out;
926 			}
927 		}
928 		nr = nr - offset;
929 
930 		/* If users can be writing to this page using arbitrary
931 		 * virtual addresses, take care about potential aliasing
932 		 * before reading the page on the kernel side.
933 		 */
934 		if (mapping_writably_mapped(mapping))
935 			flush_dcache_page(page);
936 
937 		/*
938 		 * When a sequential read accesses a page several times,
939 		 * only mark it as accessed the first time.
940 		 */
941 		if (prev_index != index || offset != prev_offset)
942 			mark_page_accessed(page);
943 		prev_index = index;
944 
945 		/*
946 		 * Ok, we have the page, and it's up-to-date, so
947 		 * now we can copy it to user space...
948 		 *
949 		 * The actor routine returns how many bytes were actually used..
950 		 * NOTE! This may not be the same as how much of a user buffer
951 		 * we filled up (we may be padding etc), so we can only update
952 		 * "pos" here (the actor routine has to update the user buffer
953 		 * pointers and the remaining count).
954 		 */
955 		ret = actor(desc, page, offset, nr);
956 		offset += ret;
957 		index += offset >> PAGE_CACHE_SHIFT;
958 		offset &= ~PAGE_CACHE_MASK;
959 		prev_offset = offset;
960 
961 		page_cache_release(page);
962 		if (ret == nr && desc->count)
963 			continue;
964 		goto out;
965 
966 page_not_up_to_date:
967 		/* Get exclusive access to the page ... */
968 		lock_page(page);
969 
970 		/* Did it get truncated before we got the lock? */
971 		if (!page->mapping) {
972 			unlock_page(page);
973 			page_cache_release(page);
974 			continue;
975 		}
976 
977 		/* Did somebody else fill it already? */
978 		if (PageUptodate(page)) {
979 			unlock_page(page);
980 			goto page_ok;
981 		}
982 
983 readpage:
984 		/* Start the actual read. The read will unlock the page. */
985 		error = mapping->a_ops->readpage(filp, page);
986 
987 		if (unlikely(error)) {
988 			if (error == AOP_TRUNCATED_PAGE) {
989 				page_cache_release(page);
990 				goto find_page;
991 			}
992 			goto readpage_error;
993 		}
994 
995 		if (!PageUptodate(page)) {
996 			lock_page(page);
997 			if (!PageUptodate(page)) {
998 				if (page->mapping == NULL) {
999 					/*
1000 					 * invalidate_inode_pages got it
1001 					 */
1002 					unlock_page(page);
1003 					page_cache_release(page);
1004 					goto find_page;
1005 				}
1006 				unlock_page(page);
1007 				error = -EIO;
1008 				shrink_readahead_size_eio(filp, ra);
1009 				goto readpage_error;
1010 			}
1011 			unlock_page(page);
1012 		}
1013 
1014 		goto page_ok;
1015 
1016 readpage_error:
1017 		/* UHHUH! A synchronous read error occurred. Report it */
1018 		desc->error = error;
1019 		page_cache_release(page);
1020 		goto out;
1021 
1022 no_cached_page:
1023 		/*
1024 		 * Ok, it wasn't cached, so we need to create a new
1025 		 * page..
1026 		 */
1027 		page = page_cache_alloc_cold(mapping);
1028 		if (!page) {
1029 			desc->error = -ENOMEM;
1030 			goto out;
1031 		}
1032 		error = add_to_page_cache_lru(page, mapping,
1033 						index, GFP_KERNEL);
1034 		if (error) {
1035 			page_cache_release(page);
1036 			if (error == -EEXIST)
1037 				goto find_page;
1038 			desc->error = error;
1039 			goto out;
1040 		}
1041 		goto readpage;
1042 	}
1043 
1044 out:
1045 	ra->prev_pos = prev_index;
1046 	ra->prev_pos <<= PAGE_CACHE_SHIFT;
1047 	ra->prev_pos |= prev_offset;
1048 
1049 	*ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1050 	if (filp)
1051 		file_accessed(filp);
1052 }
1053 EXPORT_SYMBOL(do_generic_mapping_read);
1054 
1055 int file_read_actor(read_descriptor_t *desc, struct page *page,
1056 			unsigned long offset, unsigned long size)
1057 {
1058 	char *kaddr;
1059 	unsigned long left, count = desc->count;
1060 
1061 	if (size > count)
1062 		size = count;
1063 
1064 	/*
1065 	 * Faults on the destination of a read are common, so do it before
1066 	 * taking the kmap.
1067 	 */
1068 	if (!fault_in_pages_writeable(desc->arg.buf, size)) {
1069 		kaddr = kmap_atomic(page, KM_USER0);
1070 		left = __copy_to_user_inatomic(desc->arg.buf,
1071 						kaddr + offset, size);
1072 		kunmap_atomic(kaddr, KM_USER0);
1073 		if (left == 0)
1074 			goto success;
1075 	}
1076 
1077 	/* Do it the slow way */
1078 	kaddr = kmap(page);
1079 	left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
1080 	kunmap(page);
1081 
1082 	if (left) {
1083 		size -= left;
1084 		desc->error = -EFAULT;
1085 	}
1086 success:
1087 	desc->count = count - size;
1088 	desc->written += size;
1089 	desc->arg.buf += size;
1090 	return size;
1091 }
1092 
1093 /*
1094  * Performs necessary checks before doing a write
1095  * @iov:	io vector request
1096  * @nr_segs:	number of segments in the iovec
1097  * @count:	number of bytes to write
1098  * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
1099  *
1100  * Adjust number of segments and amount of bytes to write (nr_segs should be
1101  * properly initialized first). Returns appropriate error code that caller
1102  * should return or zero in case that write should be allowed.
1103  */
1104 int generic_segment_checks(const struct iovec *iov,
1105 			unsigned long *nr_segs, size_t *count, int access_flags)
1106 {
1107 	unsigned long   seg;
1108 	size_t cnt = 0;
1109 	for (seg = 0; seg < *nr_segs; seg++) {
1110 		const struct iovec *iv = &iov[seg];
1111 
1112 		/*
1113 		 * If any segment has a negative length, or the cumulative
1114 		 * length ever wraps negative then return -EINVAL.
1115 		 */
1116 		cnt += iv->iov_len;
1117 		if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
1118 			return -EINVAL;
1119 		if (access_ok(access_flags, iv->iov_base, iv->iov_len))
1120 			continue;
1121 		if (seg == 0)
1122 			return -EFAULT;
1123 		*nr_segs = seg;
1124 		cnt -= iv->iov_len;	/* This segment is no good */
1125 		break;
1126 	}
1127 	*count = cnt;
1128 	return 0;
1129 }
1130 EXPORT_SYMBOL(generic_segment_checks);
1131 
1132 /**
1133  * generic_file_aio_read - generic filesystem read routine
1134  * @iocb:	kernel I/O control block
1135  * @iov:	io vector request
1136  * @nr_segs:	number of segments in the iovec
1137  * @pos:	current file position
1138  *
1139  * This is the "read()" routine for all filesystems
1140  * that can use the page cache directly.
1141  */
1142 ssize_t
1143 generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
1144 		unsigned long nr_segs, loff_t pos)
1145 {
1146 	struct file *filp = iocb->ki_filp;
1147 	ssize_t retval;
1148 	unsigned long seg;
1149 	size_t count;
1150 	loff_t *ppos = &iocb->ki_pos;
1151 
1152 	count = 0;
1153 	retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
1154 	if (retval)
1155 		return retval;
1156 
1157 	/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
1158 	if (filp->f_flags & O_DIRECT) {
1159 		loff_t size;
1160 		struct address_space *mapping;
1161 		struct inode *inode;
1162 
1163 		mapping = filp->f_mapping;
1164 		inode = mapping->host;
1165 		retval = 0;
1166 		if (!count)
1167 			goto out; /* skip atime */
1168 		size = i_size_read(inode);
1169 		if (pos < size) {
1170 			retval = generic_file_direct_IO(READ, iocb,
1171 						iov, pos, nr_segs);
1172 			if (retval > 0)
1173 				*ppos = pos + retval;
1174 		}
1175 		if (likely(retval != 0)) {
1176 			file_accessed(filp);
1177 			goto out;
1178 		}
1179 	}
1180 
1181 	retval = 0;
1182 	if (count) {
1183 		for (seg = 0; seg < nr_segs; seg++) {
1184 			read_descriptor_t desc;
1185 
1186 			desc.written = 0;
1187 			desc.arg.buf = iov[seg].iov_base;
1188 			desc.count = iov[seg].iov_len;
1189 			if (desc.count == 0)
1190 				continue;
1191 			desc.error = 0;
1192 			do_generic_file_read(filp,ppos,&desc,file_read_actor);
1193 			retval += desc.written;
1194 			if (desc.error) {
1195 				retval = retval ?: desc.error;
1196 				break;
1197 			}
1198 			if (desc.count > 0)
1199 				break;
1200 		}
1201 	}
1202 out:
1203 	return retval;
1204 }
1205 EXPORT_SYMBOL(generic_file_aio_read);
1206 
1207 static ssize_t
1208 do_readahead(struct address_space *mapping, struct file *filp,
1209 	     pgoff_t index, unsigned long nr)
1210 {
1211 	if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
1212 		return -EINVAL;
1213 
1214 	force_page_cache_readahead(mapping, filp, index,
1215 					max_sane_readahead(nr));
1216 	return 0;
1217 }
1218 
1219 asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
1220 {
1221 	ssize_t ret;
1222 	struct file *file;
1223 
1224 	ret = -EBADF;
1225 	file = fget(fd);
1226 	if (file) {
1227 		if (file->f_mode & FMODE_READ) {
1228 			struct address_space *mapping = file->f_mapping;
1229 			pgoff_t start = offset >> PAGE_CACHE_SHIFT;
1230 			pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
1231 			unsigned long len = end - start + 1;
1232 			ret = do_readahead(mapping, file, start, len);
1233 		}
1234 		fput(file);
1235 	}
1236 	return ret;
1237 }
1238 
1239 #ifdef CONFIG_MMU
1240 /**
1241  * page_cache_read - adds requested page to the page cache if not already there
1242  * @file:	file to read
1243  * @offset:	page index
1244  *
1245  * This adds the requested page to the page cache if it isn't already there,
1246  * and schedules an I/O to read in its contents from disk.
1247  */
1248 static int fastcall page_cache_read(struct file * file, pgoff_t offset)
1249 {
1250 	struct address_space *mapping = file->f_mapping;
1251 	struct page *page;
1252 	int ret;
1253 
1254 	do {
1255 		page = page_cache_alloc_cold(mapping);
1256 		if (!page)
1257 			return -ENOMEM;
1258 
1259 		ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
1260 		if (ret == 0)
1261 			ret = mapping->a_ops->readpage(file, page);
1262 		else if (ret == -EEXIST)
1263 			ret = 0; /* losing race to add is OK */
1264 
1265 		page_cache_release(page);
1266 
1267 	} while (ret == AOP_TRUNCATED_PAGE);
1268 
1269 	return ret;
1270 }
1271 
1272 #define MMAP_LOTSAMISS  (100)
1273 
1274 /**
1275  * filemap_fault - read in file data for page fault handling
1276  * @vma:	vma in which the fault was taken
1277  * @vmf:	struct vm_fault containing details of the fault
1278  *
1279  * filemap_fault() is invoked via the vma operations vector for a
1280  * mapped memory region to read in file data during a page fault.
1281  *
1282  * The goto's are kind of ugly, but this streamlines the normal case of having
1283  * it in the page cache, and handles the special cases reasonably without
1284  * having a lot of duplicated code.
1285  */
1286 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1287 {
1288 	int error;
1289 	struct file *file = vma->vm_file;
1290 	struct address_space *mapping = file->f_mapping;
1291 	struct file_ra_state *ra = &file->f_ra;
1292 	struct inode *inode = mapping->host;
1293 	struct page *page;
1294 	unsigned long size;
1295 	int did_readaround = 0;
1296 	int ret = 0;
1297 
1298 	size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1299 	if (vmf->pgoff >= size)
1300 		goto outside_data_content;
1301 
1302 	/* If we don't want any read-ahead, don't bother */
1303 	if (VM_RandomReadHint(vma))
1304 		goto no_cached_page;
1305 
1306 	/*
1307 	 * Do we have something in the page cache already?
1308 	 */
1309 retry_find:
1310 	page = find_lock_page(mapping, vmf->pgoff);
1311 	/*
1312 	 * For sequential accesses, we use the generic readahead logic.
1313 	 */
1314 	if (VM_SequentialReadHint(vma)) {
1315 		if (!page) {
1316 			page_cache_sync_readahead(mapping, ra, file,
1317 							   vmf->pgoff, 1);
1318 			page = find_lock_page(mapping, vmf->pgoff);
1319 			if (!page)
1320 				goto no_cached_page;
1321 		}
1322 		if (PageReadahead(page)) {
1323 			page_cache_async_readahead(mapping, ra, file, page,
1324 							   vmf->pgoff, 1);
1325 		}
1326 	}
1327 
1328 	if (!page) {
1329 		unsigned long ra_pages;
1330 
1331 		ra->mmap_miss++;
1332 
1333 		/*
1334 		 * Do we miss much more than hit in this file? If so,
1335 		 * stop bothering with read-ahead. It will only hurt.
1336 		 */
1337 		if (ra->mmap_miss > MMAP_LOTSAMISS)
1338 			goto no_cached_page;
1339 
1340 		/*
1341 		 * To keep the pgmajfault counter straight, we need to
1342 		 * check did_readaround, as this is an inner loop.
1343 		 */
1344 		if (!did_readaround) {
1345 			ret = VM_FAULT_MAJOR;
1346 			count_vm_event(PGMAJFAULT);
1347 		}
1348 		did_readaround = 1;
1349 		ra_pages = max_sane_readahead(file->f_ra.ra_pages);
1350 		if (ra_pages) {
1351 			pgoff_t start = 0;
1352 
1353 			if (vmf->pgoff > ra_pages / 2)
1354 				start = vmf->pgoff - ra_pages / 2;
1355 			do_page_cache_readahead(mapping, file, start, ra_pages);
1356 		}
1357 		page = find_lock_page(mapping, vmf->pgoff);
1358 		if (!page)
1359 			goto no_cached_page;
1360 	}
1361 
1362 	if (!did_readaround)
1363 		ra->mmap_miss--;
1364 
1365 	/*
1366 	 * We have a locked page in the page cache, now we need to check
1367 	 * that it's up-to-date. If not, it is going to be due to an error.
1368 	 */
1369 	if (unlikely(!PageUptodate(page)))
1370 		goto page_not_uptodate;
1371 
1372 	/* Must recheck i_size under page lock */
1373 	size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1374 	if (unlikely(vmf->pgoff >= size)) {
1375 		unlock_page(page);
1376 		page_cache_release(page);
1377 		goto outside_data_content;
1378 	}
1379 
1380 	/*
1381 	 * Found the page and have a reference on it.
1382 	 */
1383 	mark_page_accessed(page);
1384 	ra->prev_pos = (loff_t)page->index << PAGE_CACHE_SHIFT;
1385 	vmf->page = page;
1386 	return ret | VM_FAULT_LOCKED;
1387 
1388 outside_data_content:
1389 	/*
1390 	 * An external ptracer can access pages that normally aren't
1391 	 * accessible..
1392 	 */
1393 	if (vma->vm_mm == current->mm)
1394 		return VM_FAULT_SIGBUS;
1395 
1396 	/* Fall through to the non-read-ahead case */
1397 no_cached_page:
1398 	/*
1399 	 * We're only likely to ever get here if MADV_RANDOM is in
1400 	 * effect.
1401 	 */
1402 	error = page_cache_read(file, vmf->pgoff);
1403 
1404 	/*
1405 	 * The page we want has now been added to the page cache.
1406 	 * In the unlikely event that someone removed it in the
1407 	 * meantime, we'll just come back here and read it again.
1408 	 */
1409 	if (error >= 0)
1410 		goto retry_find;
1411 
1412 	/*
1413 	 * An error return from page_cache_read can result if the
1414 	 * system is low on memory, or a problem occurs while trying
1415 	 * to schedule I/O.
1416 	 */
1417 	if (error == -ENOMEM)
1418 		return VM_FAULT_OOM;
1419 	return VM_FAULT_SIGBUS;
1420 
1421 page_not_uptodate:
1422 	/* IO error path */
1423 	if (!did_readaround) {
1424 		ret = VM_FAULT_MAJOR;
1425 		count_vm_event(PGMAJFAULT);
1426 	}
1427 
1428 	/*
1429 	 * Umm, take care of errors if the page isn't up-to-date.
1430 	 * Try to re-read it _once_. We do this synchronously,
1431 	 * because there really aren't any performance issues here
1432 	 * and we need to check for errors.
1433 	 */
1434 	ClearPageError(page);
1435 	error = mapping->a_ops->readpage(file, page);
1436 	page_cache_release(page);
1437 
1438 	if (!error || error == AOP_TRUNCATED_PAGE)
1439 		goto retry_find;
1440 
1441 	/* Things didn't work out. Return zero to tell the mm layer so. */
1442 	shrink_readahead_size_eio(file, ra);
1443 	return VM_FAULT_SIGBUS;
1444 }
1445 EXPORT_SYMBOL(filemap_fault);
1446 
1447 struct vm_operations_struct generic_file_vm_ops = {
1448 	.fault		= filemap_fault,
1449 };
1450 
1451 /* This is used for a general mmap of a disk file */
1452 
1453 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1454 {
1455 	struct address_space *mapping = file->f_mapping;
1456 
1457 	if (!mapping->a_ops->readpage)
1458 		return -ENOEXEC;
1459 	file_accessed(file);
1460 	vma->vm_ops = &generic_file_vm_ops;
1461 	vma->vm_flags |= VM_CAN_NONLINEAR;
1462 	return 0;
1463 }
1464 
1465 /*
1466  * This is for filesystems which do not implement ->writepage.
1467  */
1468 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
1469 {
1470 	if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
1471 		return -EINVAL;
1472 	return generic_file_mmap(file, vma);
1473 }
1474 #else
1475 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
1476 {
1477 	return -ENOSYS;
1478 }
1479 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
1480 {
1481 	return -ENOSYS;
1482 }
1483 #endif /* CONFIG_MMU */
1484 
1485 EXPORT_SYMBOL(generic_file_mmap);
1486 EXPORT_SYMBOL(generic_file_readonly_mmap);
1487 
1488 static struct page *__read_cache_page(struct address_space *mapping,
1489 				pgoff_t index,
1490 				int (*filler)(void *,struct page*),
1491 				void *data)
1492 {
1493 	struct page *page;
1494 	int err;
1495 repeat:
1496 	page = find_get_page(mapping, index);
1497 	if (!page) {
1498 		page = page_cache_alloc_cold(mapping);
1499 		if (!page)
1500 			return ERR_PTR(-ENOMEM);
1501 		err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
1502 		if (unlikely(err)) {
1503 			page_cache_release(page);
1504 			if (err == -EEXIST)
1505 				goto repeat;
1506 			/* Presumably ENOMEM for radix tree node */
1507 			return ERR_PTR(err);
1508 		}
1509 		err = filler(data, page);
1510 		if (err < 0) {
1511 			page_cache_release(page);
1512 			page = ERR_PTR(err);
1513 		}
1514 	}
1515 	return page;
1516 }
1517 
1518 /*
1519  * Same as read_cache_page, but don't wait for page to become unlocked
1520  * after submitting it to the filler.
1521  */
1522 struct page *read_cache_page_async(struct address_space *mapping,
1523 				pgoff_t index,
1524 				int (*filler)(void *,struct page*),
1525 				void *data)
1526 {
1527 	struct page *page;
1528 	int err;
1529 
1530 retry:
1531 	page = __read_cache_page(mapping, index, filler, data);
1532 	if (IS_ERR(page))
1533 		return page;
1534 	if (PageUptodate(page))
1535 		goto out;
1536 
1537 	lock_page(page);
1538 	if (!page->mapping) {
1539 		unlock_page(page);
1540 		page_cache_release(page);
1541 		goto retry;
1542 	}
1543 	if (PageUptodate(page)) {
1544 		unlock_page(page);
1545 		goto out;
1546 	}
1547 	err = filler(data, page);
1548 	if (err < 0) {
1549 		page_cache_release(page);
1550 		return ERR_PTR(err);
1551 	}
1552 out:
1553 	mark_page_accessed(page);
1554 	return page;
1555 }
1556 EXPORT_SYMBOL(read_cache_page_async);
1557 
1558 /**
1559  * read_cache_page - read into page cache, fill it if needed
1560  * @mapping:	the page's address_space
1561  * @index:	the page index
1562  * @filler:	function to perform the read
1563  * @data:	destination for read data
1564  *
1565  * Read into the page cache. If a page already exists, and PageUptodate() is
1566  * not set, try to fill the page then wait for it to become unlocked.
1567  *
1568  * If the page does not get brought uptodate, return -EIO.
1569  */
1570 struct page *read_cache_page(struct address_space *mapping,
1571 				pgoff_t index,
1572 				int (*filler)(void *,struct page*),
1573 				void *data)
1574 {
1575 	struct page *page;
1576 
1577 	page = read_cache_page_async(mapping, index, filler, data);
1578 	if (IS_ERR(page))
1579 		goto out;
1580 	wait_on_page_locked(page);
1581 	if (!PageUptodate(page)) {
1582 		page_cache_release(page);
1583 		page = ERR_PTR(-EIO);
1584 	}
1585  out:
1586 	return page;
1587 }
1588 EXPORT_SYMBOL(read_cache_page);
1589 
1590 /*
1591  * The logic we want is
1592  *
1593  *	if suid or (sgid and xgrp)
1594  *		remove privs
1595  */
1596 int should_remove_suid(struct dentry *dentry)
1597 {
1598 	mode_t mode = dentry->d_inode->i_mode;
1599 	int kill = 0;
1600 
1601 	/* suid always must be killed */
1602 	if (unlikely(mode & S_ISUID))
1603 		kill = ATTR_KILL_SUID;
1604 
1605 	/*
1606 	 * sgid without any exec bits is just a mandatory locking mark; leave
1607 	 * it alone.  If some exec bits are set, it's a real sgid; kill it.
1608 	 */
1609 	if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
1610 		kill |= ATTR_KILL_SGID;
1611 
1612 	if (unlikely(kill && !capable(CAP_FSETID)))
1613 		return kill;
1614 
1615 	return 0;
1616 }
1617 EXPORT_SYMBOL(should_remove_suid);
1618 
1619 int __remove_suid(struct dentry *dentry, int kill)
1620 {
1621 	struct iattr newattrs;
1622 
1623 	newattrs.ia_valid = ATTR_FORCE | kill;
1624 	return notify_change(dentry, &newattrs);
1625 }
1626 
1627 int remove_suid(struct dentry *dentry)
1628 {
1629 	int kill = should_remove_suid(dentry);
1630 
1631 	if (unlikely(kill))
1632 		return __remove_suid(dentry, kill);
1633 
1634 	return 0;
1635 }
1636 EXPORT_SYMBOL(remove_suid);
1637 
1638 static size_t __iovec_copy_from_user_inatomic(char *vaddr,
1639 			const struct iovec *iov, size_t base, size_t bytes)
1640 {
1641 	size_t copied = 0, left = 0;
1642 
1643 	while (bytes) {
1644 		char __user *buf = iov->iov_base + base;
1645 		int copy = min(bytes, iov->iov_len - base);
1646 
1647 		base = 0;
1648 		left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
1649 		copied += copy;
1650 		bytes -= copy;
1651 		vaddr += copy;
1652 		iov++;
1653 
1654 		if (unlikely(left))
1655 			break;
1656 	}
1657 	return copied - left;
1658 }
1659 
1660 /*
1661  * Copy as much as we can into the page and return the number of bytes which
1662  * were sucessfully copied.  If a fault is encountered then return the number of
1663  * bytes which were copied.
1664  */
1665 size_t iov_iter_copy_from_user_atomic(struct page *page,
1666 		struct iov_iter *i, unsigned long offset, size_t bytes)
1667 {
1668 	char *kaddr;
1669 	size_t copied;
1670 
1671 	BUG_ON(!in_atomic());
1672 	kaddr = kmap_atomic(page, KM_USER0);
1673 	if (likely(i->nr_segs == 1)) {
1674 		int left;
1675 		char __user *buf = i->iov->iov_base + i->iov_offset;
1676 		left = __copy_from_user_inatomic_nocache(kaddr + offset,
1677 							buf, bytes);
1678 		copied = bytes - left;
1679 	} else {
1680 		copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1681 						i->iov, i->iov_offset, bytes);
1682 	}
1683 	kunmap_atomic(kaddr, KM_USER0);
1684 
1685 	return copied;
1686 }
1687 
1688 /*
1689  * This has the same sideeffects and return value as
1690  * iov_iter_copy_from_user_atomic().
1691  * The difference is that it attempts to resolve faults.
1692  * Page must not be locked.
1693  */
1694 size_t iov_iter_copy_from_user(struct page *page,
1695 		struct iov_iter *i, unsigned long offset, size_t bytes)
1696 {
1697 	char *kaddr;
1698 	size_t copied;
1699 
1700 	kaddr = kmap(page);
1701 	if (likely(i->nr_segs == 1)) {
1702 		int left;
1703 		char __user *buf = i->iov->iov_base + i->iov_offset;
1704 		left = __copy_from_user_nocache(kaddr + offset, buf, bytes);
1705 		copied = bytes - left;
1706 	} else {
1707 		copied = __iovec_copy_from_user_inatomic(kaddr + offset,
1708 						i->iov, i->iov_offset, bytes);
1709 	}
1710 	kunmap(page);
1711 	return copied;
1712 }
1713 
1714 static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
1715 {
1716 	if (likely(i->nr_segs == 1)) {
1717 		i->iov_offset += bytes;
1718 	} else {
1719 		const struct iovec *iov = i->iov;
1720 		size_t base = i->iov_offset;
1721 
1722 		while (bytes) {
1723 			int copy = min(bytes, iov->iov_len - base);
1724 
1725 			bytes -= copy;
1726 			base += copy;
1727 			if (iov->iov_len == base) {
1728 				iov++;
1729 				base = 0;
1730 			}
1731 		}
1732 		i->iov = iov;
1733 		i->iov_offset = base;
1734 	}
1735 }
1736 
1737 void iov_iter_advance(struct iov_iter *i, size_t bytes)
1738 {
1739 	BUG_ON(i->count < bytes);
1740 
1741 	__iov_iter_advance_iov(i, bytes);
1742 	i->count -= bytes;
1743 }
1744 
1745 /*
1746  * Fault in the first iovec of the given iov_iter, to a maximum length
1747  * of bytes. Returns 0 on success, or non-zero if the memory could not be
1748  * accessed (ie. because it is an invalid address).
1749  *
1750  * writev-intensive code may want this to prefault several iovecs -- that
1751  * would be possible (callers must not rely on the fact that _only_ the
1752  * first iovec will be faulted with the current implementation).
1753  */
1754 int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
1755 {
1756 	char __user *buf = i->iov->iov_base + i->iov_offset;
1757 	bytes = min(bytes, i->iov->iov_len - i->iov_offset);
1758 	return fault_in_pages_readable(buf, bytes);
1759 }
1760 
1761 /*
1762  * Return the count of just the current iov_iter segment.
1763  */
1764 size_t iov_iter_single_seg_count(struct iov_iter *i)
1765 {
1766 	const struct iovec *iov = i->iov;
1767 	if (i->nr_segs == 1)
1768 		return i->count;
1769 	else
1770 		return min(i->count, iov->iov_len - i->iov_offset);
1771 }
1772 
1773 /*
1774  * Performs necessary checks before doing a write
1775  *
1776  * Can adjust writing position or amount of bytes to write.
1777  * Returns appropriate error code that caller should return or
1778  * zero in case that write should be allowed.
1779  */
1780 inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
1781 {
1782 	struct inode *inode = file->f_mapping->host;
1783 	unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
1784 
1785         if (unlikely(*pos < 0))
1786                 return -EINVAL;
1787 
1788 	if (!isblk) {
1789 		/* FIXME: this is for backwards compatibility with 2.4 */
1790 		if (file->f_flags & O_APPEND)
1791                         *pos = i_size_read(inode);
1792 
1793 		if (limit != RLIM_INFINITY) {
1794 			if (*pos >= limit) {
1795 				send_sig(SIGXFSZ, current, 0);
1796 				return -EFBIG;
1797 			}
1798 			if (*count > limit - (typeof(limit))*pos) {
1799 				*count = limit - (typeof(limit))*pos;
1800 			}
1801 		}
1802 	}
1803 
1804 	/*
1805 	 * LFS rule
1806 	 */
1807 	if (unlikely(*pos + *count > MAX_NON_LFS &&
1808 				!(file->f_flags & O_LARGEFILE))) {
1809 		if (*pos >= MAX_NON_LFS) {
1810 			return -EFBIG;
1811 		}
1812 		if (*count > MAX_NON_LFS - (unsigned long)*pos) {
1813 			*count = MAX_NON_LFS - (unsigned long)*pos;
1814 		}
1815 	}
1816 
1817 	/*
1818 	 * Are we about to exceed the fs block limit ?
1819 	 *
1820 	 * If we have written data it becomes a short write.  If we have
1821 	 * exceeded without writing data we send a signal and return EFBIG.
1822 	 * Linus frestrict idea will clean these up nicely..
1823 	 */
1824 	if (likely(!isblk)) {
1825 		if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
1826 			if (*count || *pos > inode->i_sb->s_maxbytes) {
1827 				return -EFBIG;
1828 			}
1829 			/* zero-length writes at ->s_maxbytes are OK */
1830 		}
1831 
1832 		if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
1833 			*count = inode->i_sb->s_maxbytes - *pos;
1834 	} else {
1835 #ifdef CONFIG_BLOCK
1836 		loff_t isize;
1837 		if (bdev_read_only(I_BDEV(inode)))
1838 			return -EPERM;
1839 		isize = i_size_read(inode);
1840 		if (*pos >= isize) {
1841 			if (*count || *pos > isize)
1842 				return -ENOSPC;
1843 		}
1844 
1845 		if (*pos + *count > isize)
1846 			*count = isize - *pos;
1847 #else
1848 		return -EPERM;
1849 #endif
1850 	}
1851 	return 0;
1852 }
1853 EXPORT_SYMBOL(generic_write_checks);
1854 
1855 int pagecache_write_begin(struct file *file, struct address_space *mapping,
1856 				loff_t pos, unsigned len, unsigned flags,
1857 				struct page **pagep, void **fsdata)
1858 {
1859 	const struct address_space_operations *aops = mapping->a_ops;
1860 
1861 	if (aops->write_begin) {
1862 		return aops->write_begin(file, mapping, pos, len, flags,
1863 							pagep, fsdata);
1864 	} else {
1865 		int ret;
1866 		pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1867 		unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1868 		struct inode *inode = mapping->host;
1869 		struct page *page;
1870 again:
1871 		page = __grab_cache_page(mapping, index);
1872 		*pagep = page;
1873 		if (!page)
1874 			return -ENOMEM;
1875 
1876 		if (flags & AOP_FLAG_UNINTERRUPTIBLE && !PageUptodate(page)) {
1877 			/*
1878 			 * There is no way to resolve a short write situation
1879 			 * for a !Uptodate page (except by double copying in
1880 			 * the caller done by generic_perform_write_2copy).
1881 			 *
1882 			 * Instead, we have to bring it uptodate here.
1883 			 */
1884 			ret = aops->readpage(file, page);
1885 			page_cache_release(page);
1886 			if (ret) {
1887 				if (ret == AOP_TRUNCATED_PAGE)
1888 					goto again;
1889 				return ret;
1890 			}
1891 			goto again;
1892 		}
1893 
1894 		ret = aops->prepare_write(file, page, offset, offset+len);
1895 		if (ret) {
1896 			if (ret != AOP_TRUNCATED_PAGE)
1897 				unlock_page(page);
1898 			page_cache_release(page);
1899 			if (pos + len > inode->i_size)
1900 				vmtruncate(inode, inode->i_size);
1901 			if (ret == AOP_TRUNCATED_PAGE)
1902 				goto again;
1903 		}
1904 		return ret;
1905 	}
1906 }
1907 EXPORT_SYMBOL(pagecache_write_begin);
1908 
1909 int pagecache_write_end(struct file *file, struct address_space *mapping,
1910 				loff_t pos, unsigned len, unsigned copied,
1911 				struct page *page, void *fsdata)
1912 {
1913 	const struct address_space_operations *aops = mapping->a_ops;
1914 	int ret;
1915 
1916 	if (aops->write_end) {
1917 		mark_page_accessed(page);
1918 		ret = aops->write_end(file, mapping, pos, len, copied,
1919 							page, fsdata);
1920 	} else {
1921 		unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
1922 		struct inode *inode = mapping->host;
1923 
1924 		flush_dcache_page(page);
1925 		ret = aops->commit_write(file, page, offset, offset+len);
1926 		unlock_page(page);
1927 		mark_page_accessed(page);
1928 		page_cache_release(page);
1929 		BUG_ON(ret == AOP_TRUNCATED_PAGE); /* can't deal with */
1930 
1931 		if (ret < 0) {
1932 			if (pos + len > inode->i_size)
1933 				vmtruncate(inode, inode->i_size);
1934 		} else if (ret > 0)
1935 			ret = min_t(size_t, copied, ret);
1936 		else
1937 			ret = copied;
1938 	}
1939 
1940 	return ret;
1941 }
1942 EXPORT_SYMBOL(pagecache_write_end);
1943 
1944 ssize_t
1945 generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
1946 		unsigned long *nr_segs, loff_t pos, loff_t *ppos,
1947 		size_t count, size_t ocount)
1948 {
1949 	struct file	*file = iocb->ki_filp;
1950 	struct address_space *mapping = file->f_mapping;
1951 	struct inode	*inode = mapping->host;
1952 	ssize_t		written;
1953 
1954 	if (count != ocount)
1955 		*nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
1956 
1957 	written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
1958 	if (written > 0) {
1959 		loff_t end = pos + written;
1960 		if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
1961 			i_size_write(inode,  end);
1962 			mark_inode_dirty(inode);
1963 		}
1964 		*ppos = end;
1965 	}
1966 
1967 	/*
1968 	 * Sync the fs metadata but not the minor inode changes and
1969 	 * of course not the data as we did direct DMA for the IO.
1970 	 * i_mutex is held, which protects generic_osync_inode() from
1971 	 * livelocking.  AIO O_DIRECT ops attempt to sync metadata here.
1972 	 */
1973 	if ((written >= 0 || written == -EIOCBQUEUED) &&
1974 	    ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
1975 		int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
1976 		if (err < 0)
1977 			written = err;
1978 	}
1979 	return written;
1980 }
1981 EXPORT_SYMBOL(generic_file_direct_write);
1982 
1983 /*
1984  * Find or create a page at the given pagecache position. Return the locked
1985  * page. This function is specifically for buffered writes.
1986  */
1987 struct page *__grab_cache_page(struct address_space *mapping, pgoff_t index)
1988 {
1989 	int status;
1990 	struct page *page;
1991 repeat:
1992 	page = find_lock_page(mapping, index);
1993 	if (likely(page))
1994 		return page;
1995 
1996 	page = page_cache_alloc(mapping);
1997 	if (!page)
1998 		return NULL;
1999 	status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
2000 	if (unlikely(status)) {
2001 		page_cache_release(page);
2002 		if (status == -EEXIST)
2003 			goto repeat;
2004 		return NULL;
2005 	}
2006 	return page;
2007 }
2008 EXPORT_SYMBOL(__grab_cache_page);
2009 
2010 static ssize_t generic_perform_write_2copy(struct file *file,
2011 				struct iov_iter *i, loff_t pos)
2012 {
2013 	struct address_space *mapping = file->f_mapping;
2014 	const struct address_space_operations *a_ops = mapping->a_ops;
2015 	struct inode *inode = mapping->host;
2016 	long status = 0;
2017 	ssize_t written = 0;
2018 
2019 	do {
2020 		struct page *src_page;
2021 		struct page *page;
2022 		pgoff_t index;		/* Pagecache index for current page */
2023 		unsigned long offset;	/* Offset into pagecache page */
2024 		unsigned long bytes;	/* Bytes to write to page */
2025 		size_t copied;		/* Bytes copied from user */
2026 
2027 		offset = (pos & (PAGE_CACHE_SIZE - 1));
2028 		index = pos >> PAGE_CACHE_SHIFT;
2029 		bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2030 						iov_iter_count(i));
2031 
2032 		/*
2033 		 * a non-NULL src_page indicates that we're doing the
2034 		 * copy via get_user_pages and kmap.
2035 		 */
2036 		src_page = NULL;
2037 
2038 		/*
2039 		 * Bring in the user page that we will copy from _first_.
2040 		 * Otherwise there's a nasty deadlock on copying from the
2041 		 * same page as we're writing to, without it being marked
2042 		 * up-to-date.
2043 		 *
2044 		 * Not only is this an optimisation, but it is also required
2045 		 * to check that the address is actually valid, when atomic
2046 		 * usercopies are used, below.
2047 		 */
2048 		if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2049 			status = -EFAULT;
2050 			break;
2051 		}
2052 
2053 		page = __grab_cache_page(mapping, index);
2054 		if (!page) {
2055 			status = -ENOMEM;
2056 			break;
2057 		}
2058 
2059 		/*
2060 		 * non-uptodate pages cannot cope with short copies, and we
2061 		 * cannot take a pagefault with the destination page locked.
2062 		 * So pin the source page to copy it.
2063 		 */
2064 		if (!PageUptodate(page)) {
2065 			unlock_page(page);
2066 
2067 			src_page = alloc_page(GFP_KERNEL);
2068 			if (!src_page) {
2069 				page_cache_release(page);
2070 				status = -ENOMEM;
2071 				break;
2072 			}
2073 
2074 			/*
2075 			 * Cannot get_user_pages with a page locked for the
2076 			 * same reason as we can't take a page fault with a
2077 			 * page locked (as explained below).
2078 			 */
2079 			copied = iov_iter_copy_from_user(src_page, i,
2080 								offset, bytes);
2081 			if (unlikely(copied == 0)) {
2082 				status = -EFAULT;
2083 				page_cache_release(page);
2084 				page_cache_release(src_page);
2085 				break;
2086 			}
2087 			bytes = copied;
2088 
2089 			lock_page(page);
2090 			/*
2091 			 * Can't handle the page going uptodate here, because
2092 			 * that means we would use non-atomic usercopies, which
2093 			 * zero out the tail of the page, which can cause
2094 			 * zeroes to become transiently visible. We could just
2095 			 * use a non-zeroing copy, but the APIs aren't too
2096 			 * consistent.
2097 			 */
2098 			if (unlikely(!page->mapping || PageUptodate(page))) {
2099 				unlock_page(page);
2100 				page_cache_release(page);
2101 				page_cache_release(src_page);
2102 				continue;
2103 			}
2104 		}
2105 
2106 		status = a_ops->prepare_write(file, page, offset, offset+bytes);
2107 		if (unlikely(status))
2108 			goto fs_write_aop_error;
2109 
2110 		if (!src_page) {
2111 			/*
2112 			 * Must not enter the pagefault handler here, because
2113 			 * we hold the page lock, so we might recursively
2114 			 * deadlock on the same lock, or get an ABBA deadlock
2115 			 * against a different lock, or against the mmap_sem
2116 			 * (which nests outside the page lock).  So increment
2117 			 * preempt count, and use _atomic usercopies.
2118 			 *
2119 			 * The page is uptodate so we are OK to encounter a
2120 			 * short copy: if unmodified parts of the page are
2121 			 * marked dirty and written out to disk, it doesn't
2122 			 * really matter.
2123 			 */
2124 			pagefault_disable();
2125 			copied = iov_iter_copy_from_user_atomic(page, i,
2126 								offset, bytes);
2127 			pagefault_enable();
2128 		} else {
2129 			void *src, *dst;
2130 			src = kmap_atomic(src_page, KM_USER0);
2131 			dst = kmap_atomic(page, KM_USER1);
2132 			memcpy(dst + offset, src + offset, bytes);
2133 			kunmap_atomic(dst, KM_USER1);
2134 			kunmap_atomic(src, KM_USER0);
2135 			copied = bytes;
2136 		}
2137 		flush_dcache_page(page);
2138 
2139 		status = a_ops->commit_write(file, page, offset, offset+bytes);
2140 		if (unlikely(status < 0 || status == AOP_TRUNCATED_PAGE))
2141 			goto fs_write_aop_error;
2142 		if (unlikely(status > 0)) /* filesystem did partial write */
2143 			copied = min_t(size_t, copied, status);
2144 
2145 		unlock_page(page);
2146 		mark_page_accessed(page);
2147 		page_cache_release(page);
2148 		if (src_page)
2149 			page_cache_release(src_page);
2150 
2151 		iov_iter_advance(i, copied);
2152 		pos += copied;
2153 		written += copied;
2154 
2155 		balance_dirty_pages_ratelimited(mapping);
2156 		cond_resched();
2157 		continue;
2158 
2159 fs_write_aop_error:
2160 		if (status != AOP_TRUNCATED_PAGE)
2161 			unlock_page(page);
2162 		page_cache_release(page);
2163 		if (src_page)
2164 			page_cache_release(src_page);
2165 
2166 		/*
2167 		 * prepare_write() may have instantiated a few blocks
2168 		 * outside i_size.  Trim these off again. Don't need
2169 		 * i_size_read because we hold i_mutex.
2170 		 */
2171 		if (pos + bytes > inode->i_size)
2172 			vmtruncate(inode, inode->i_size);
2173 		if (status == AOP_TRUNCATED_PAGE)
2174 			continue;
2175 		else
2176 			break;
2177 	} while (iov_iter_count(i));
2178 
2179 	return written ? written : status;
2180 }
2181 
2182 static ssize_t generic_perform_write(struct file *file,
2183 				struct iov_iter *i, loff_t pos)
2184 {
2185 	struct address_space *mapping = file->f_mapping;
2186 	const struct address_space_operations *a_ops = mapping->a_ops;
2187 	long status = 0;
2188 	ssize_t written = 0;
2189 
2190 	do {
2191 		struct page *page;
2192 		pgoff_t index;		/* Pagecache index for current page */
2193 		unsigned long offset;	/* Offset into pagecache page */
2194 		unsigned long bytes;	/* Bytes to write to page */
2195 		size_t copied;		/* Bytes copied from user */
2196 		void *fsdata;
2197 
2198 		offset = (pos & (PAGE_CACHE_SIZE - 1));
2199 		index = pos >> PAGE_CACHE_SHIFT;
2200 		bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2201 						iov_iter_count(i));
2202 
2203 again:
2204 
2205 		/*
2206 		 * Bring in the user page that we will copy from _first_.
2207 		 * Otherwise there's a nasty deadlock on copying from the
2208 		 * same page as we're writing to, without it being marked
2209 		 * up-to-date.
2210 		 *
2211 		 * Not only is this an optimisation, but it is also required
2212 		 * to check that the address is actually valid, when atomic
2213 		 * usercopies are used, below.
2214 		 */
2215 		if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2216 			status = -EFAULT;
2217 			break;
2218 		}
2219 
2220 		status = a_ops->write_begin(file, mapping, pos, bytes, 0,
2221 						&page, &fsdata);
2222 		if (unlikely(status))
2223 			break;
2224 
2225 		pagefault_disable();
2226 		copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2227 		pagefault_enable();
2228 		flush_dcache_page(page);
2229 
2230 		status = a_ops->write_end(file, mapping, pos, bytes, copied,
2231 						page, fsdata);
2232 		if (unlikely(status < 0))
2233 			break;
2234 		copied = status;
2235 
2236 		cond_resched();
2237 
2238 		if (unlikely(copied == 0)) {
2239 			/*
2240 			 * If we were unable to copy any data at all, we must
2241 			 * fall back to a single segment length write.
2242 			 *
2243 			 * If we didn't fallback here, we could livelock
2244 			 * because not all segments in the iov can be copied at
2245 			 * once without a pagefault.
2246 			 */
2247 			bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2248 						iov_iter_single_seg_count(i));
2249 			goto again;
2250 		}
2251 		iov_iter_advance(i, copied);
2252 		pos += copied;
2253 		written += copied;
2254 
2255 		balance_dirty_pages_ratelimited(mapping);
2256 
2257 	} while (iov_iter_count(i));
2258 
2259 	return written ? written : status;
2260 }
2261 
2262 ssize_t
2263 generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
2264 		unsigned long nr_segs, loff_t pos, loff_t *ppos,
2265 		size_t count, ssize_t written)
2266 {
2267 	struct file *file = iocb->ki_filp;
2268 	struct address_space *mapping = file->f_mapping;
2269 	const struct address_space_operations *a_ops = mapping->a_ops;
2270 	struct inode *inode = mapping->host;
2271 	ssize_t status;
2272 	struct iov_iter i;
2273 
2274 	iov_iter_init(&i, iov, nr_segs, count, written);
2275 	if (a_ops->write_begin)
2276 		status = generic_perform_write(file, &i, pos);
2277 	else
2278 		status = generic_perform_write_2copy(file, &i, pos);
2279 
2280 	if (likely(status >= 0)) {
2281 		written += status;
2282 		*ppos = pos + status;
2283 
2284 		/*
2285 		 * For now, when the user asks for O_SYNC, we'll actually give
2286 		 * O_DSYNC
2287 		 */
2288 		if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2289 			if (!a_ops->writepage || !is_sync_kiocb(iocb))
2290 				status = generic_osync_inode(inode, mapping,
2291 						OSYNC_METADATA|OSYNC_DATA);
2292 		}
2293   	}
2294 
2295 	/*
2296 	 * If we get here for O_DIRECT writes then we must have fallen through
2297 	 * to buffered writes (block instantiation inside i_size).  So we sync
2298 	 * the file data here, to try to honour O_DIRECT expectations.
2299 	 */
2300 	if (unlikely(file->f_flags & O_DIRECT) && written)
2301 		status = filemap_write_and_wait(mapping);
2302 
2303 	return written ? written : status;
2304 }
2305 EXPORT_SYMBOL(generic_file_buffered_write);
2306 
2307 static ssize_t
2308 __generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
2309 				unsigned long nr_segs, loff_t *ppos)
2310 {
2311 	struct file *file = iocb->ki_filp;
2312 	struct address_space * mapping = file->f_mapping;
2313 	size_t ocount;		/* original count */
2314 	size_t count;		/* after file limit checks */
2315 	struct inode 	*inode = mapping->host;
2316 	loff_t		pos;
2317 	ssize_t		written;
2318 	ssize_t		err;
2319 
2320 	ocount = 0;
2321 	err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
2322 	if (err)
2323 		return err;
2324 
2325 	count = ocount;
2326 	pos = *ppos;
2327 
2328 	vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2329 
2330 	/* We can write back this queue in page reclaim */
2331 	current->backing_dev_info = mapping->backing_dev_info;
2332 	written = 0;
2333 
2334 	err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2335 	if (err)
2336 		goto out;
2337 
2338 	if (count == 0)
2339 		goto out;
2340 
2341 	err = remove_suid(file->f_path.dentry);
2342 	if (err)
2343 		goto out;
2344 
2345 	file_update_time(file);
2346 
2347 	/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
2348 	if (unlikely(file->f_flags & O_DIRECT)) {
2349 		loff_t endbyte;
2350 		ssize_t written_buffered;
2351 
2352 		written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
2353 							ppos, count, ocount);
2354 		if (written < 0 || written == count)
2355 			goto out;
2356 		/*
2357 		 * direct-io write to a hole: fall through to buffered I/O
2358 		 * for completing the rest of the request.
2359 		 */
2360 		pos += written;
2361 		count -= written;
2362 		written_buffered = generic_file_buffered_write(iocb, iov,
2363 						nr_segs, pos, ppos, count,
2364 						written);
2365 		/*
2366 		 * If generic_file_buffered_write() retuned a synchronous error
2367 		 * then we want to return the number of bytes which were
2368 		 * direct-written, or the error code if that was zero.  Note
2369 		 * that this differs from normal direct-io semantics, which
2370 		 * will return -EFOO even if some bytes were written.
2371 		 */
2372 		if (written_buffered < 0) {
2373 			err = written_buffered;
2374 			goto out;
2375 		}
2376 
2377 		/*
2378 		 * We need to ensure that the page cache pages are written to
2379 		 * disk and invalidated to preserve the expected O_DIRECT
2380 		 * semantics.
2381 		 */
2382 		endbyte = pos + written_buffered - written - 1;
2383 		err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
2384 					    SYNC_FILE_RANGE_WAIT_BEFORE|
2385 					    SYNC_FILE_RANGE_WRITE|
2386 					    SYNC_FILE_RANGE_WAIT_AFTER);
2387 		if (err == 0) {
2388 			written = written_buffered;
2389 			invalidate_mapping_pages(mapping,
2390 						 pos >> PAGE_CACHE_SHIFT,
2391 						 endbyte >> PAGE_CACHE_SHIFT);
2392 		} else {
2393 			/*
2394 			 * We don't know how much we wrote, so just return
2395 			 * the number of bytes which were direct-written
2396 			 */
2397 		}
2398 	} else {
2399 		written = generic_file_buffered_write(iocb, iov, nr_segs,
2400 				pos, ppos, count, written);
2401 	}
2402 out:
2403 	current->backing_dev_info = NULL;
2404 	return written ? written : err;
2405 }
2406 
2407 ssize_t generic_file_aio_write_nolock(struct kiocb *iocb,
2408 		const struct iovec *iov, unsigned long nr_segs, loff_t pos)
2409 {
2410 	struct file *file = iocb->ki_filp;
2411 	struct address_space *mapping = file->f_mapping;
2412 	struct inode *inode = mapping->host;
2413 	ssize_t ret;
2414 
2415 	BUG_ON(iocb->ki_pos != pos);
2416 
2417 	ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2418 			&iocb->ki_pos);
2419 
2420 	if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2421 		ssize_t err;
2422 
2423 		err = sync_page_range_nolock(inode, mapping, pos, ret);
2424 		if (err < 0)
2425 			ret = err;
2426 	}
2427 	return ret;
2428 }
2429 EXPORT_SYMBOL(generic_file_aio_write_nolock);
2430 
2431 ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2432 		unsigned long nr_segs, loff_t pos)
2433 {
2434 	struct file *file = iocb->ki_filp;
2435 	struct address_space *mapping = file->f_mapping;
2436 	struct inode *inode = mapping->host;
2437 	ssize_t ret;
2438 
2439 	BUG_ON(iocb->ki_pos != pos);
2440 
2441 	mutex_lock(&inode->i_mutex);
2442 	ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
2443 			&iocb->ki_pos);
2444 	mutex_unlock(&inode->i_mutex);
2445 
2446 	if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
2447 		ssize_t err;
2448 
2449 		err = sync_page_range(inode, mapping, pos, ret);
2450 		if (err < 0)
2451 			ret = err;
2452 	}
2453 	return ret;
2454 }
2455 EXPORT_SYMBOL(generic_file_aio_write);
2456 
2457 /*
2458  * Called under i_mutex for writes to S_ISREG files.   Returns -EIO if something
2459  * went wrong during pagecache shootdown.
2460  */
2461 static ssize_t
2462 generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2463 	loff_t offset, unsigned long nr_segs)
2464 {
2465 	struct file *file = iocb->ki_filp;
2466 	struct address_space *mapping = file->f_mapping;
2467 	ssize_t retval;
2468 	size_t write_len;
2469 	pgoff_t end = 0; /* silence gcc */
2470 
2471 	/*
2472 	 * If it's a write, unmap all mmappings of the file up-front.  This
2473 	 * will cause any pte dirty bits to be propagated into the pageframes
2474 	 * for the subsequent filemap_write_and_wait().
2475 	 */
2476 	if (rw == WRITE) {
2477 		write_len = iov_length(iov, nr_segs);
2478 		end = (offset + write_len - 1) >> PAGE_CACHE_SHIFT;
2479 	       	if (mapping_mapped(mapping))
2480 			unmap_mapping_range(mapping, offset, write_len, 0);
2481 	}
2482 
2483 	retval = filemap_write_and_wait(mapping);
2484 	if (retval)
2485 		goto out;
2486 
2487 	/*
2488 	 * After a write we want buffered reads to be sure to go to disk to get
2489 	 * the new data.  We invalidate clean cached page from the region we're
2490 	 * about to write.  We do this *before* the write so that we can return
2491 	 * -EIO without clobbering -EIOCBQUEUED from ->direct_IO().
2492 	 */
2493 	if (rw == WRITE && mapping->nrpages) {
2494 		retval = invalidate_inode_pages2_range(mapping,
2495 					offset >> PAGE_CACHE_SHIFT, end);
2496 		if (retval)
2497 			goto out;
2498 	}
2499 
2500 	retval = mapping->a_ops->direct_IO(rw, iocb, iov, offset, nr_segs);
2501 	if (retval)
2502 		goto out;
2503 
2504 	/*
2505 	 * Finally, try again to invalidate clean pages which might have been
2506 	 * faulted in by get_user_pages() if the source of the write was an
2507 	 * mmap()ed region of the file we're writing.  That's a pretty crazy
2508 	 * thing to do, so we don't support it 100%.  If this invalidation
2509 	 * fails and we have -EIOCBQUEUED we ignore the failure.
2510 	 */
2511 	if (rw == WRITE && mapping->nrpages) {
2512 		int err = invalidate_inode_pages2_range(mapping,
2513 					      offset >> PAGE_CACHE_SHIFT, end);
2514 		if (err && retval >= 0)
2515 			retval = err;
2516 	}
2517 out:
2518 	return retval;
2519 }
2520 
2521 /**
2522  * try_to_release_page() - release old fs-specific metadata on a page
2523  *
2524  * @page: the page which the kernel is trying to free
2525  * @gfp_mask: memory allocation flags (and I/O mode)
2526  *
2527  * The address_space is to try to release any data against the page
2528  * (presumably at page->private).  If the release was successful, return `1'.
2529  * Otherwise return zero.
2530  *
2531  * The @gfp_mask argument specifies whether I/O may be performed to release
2532  * this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
2533  *
2534  * NOTE: @gfp_mask may go away, and this function may become non-blocking.
2535  */
2536 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2537 {
2538 	struct address_space * const mapping = page->mapping;
2539 
2540 	BUG_ON(!PageLocked(page));
2541 	if (PageWriteback(page))
2542 		return 0;
2543 
2544 	if (mapping && mapping->a_ops->releasepage)
2545 		return mapping->a_ops->releasepage(page, gfp_mask);
2546 	return try_to_free_buffers(page);
2547 }
2548 
2549 EXPORT_SYMBOL(try_to_release_page);
2550