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