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