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