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