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