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