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