~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/mm/filemap.c

Version: ~ [ linux-5.11 ] ~ [ linux-5.10.17 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.99 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.176 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.221 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.257 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.257 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp