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