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