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