4 * Copyright (C) 1994-1999 Linus Torvalds
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)
12 #include <linux/export.h>
13 #include <linux/compiler.h>
14 #include <linux/dax.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>
22 #include <linux/swap.h>
23 #include <linux/mman.h>
24 #include <linux/pagemap.h>
25 #include <linux/file.h>
26 #include <linux/uio.h>
27 #include <linux/hash.h>
28 #include <linux/writeback.h>
29 #include <linux/backing-dev.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/security.h>
33 #include <linux/cpuset.h>
34 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
35 #include <linux/hugetlb.h>
36 #include <linux/memcontrol.h>
37 #include <linux/cleancache.h>
38 #include <linux/rmap.h>
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/filemap.h>
45 * FIXME: remove all knowledge of the buffer layer from the core VM
47 #include <linux/buffer_head.h> /* for try_to_free_buffers */
52 * Shared mappings implemented 30.11.1994. It's not fully working yet,
55 * Shared mappings now work. 15.8.1995 Bruno.
57 * finished 'unifying' the page and buffer cache and SMP-threaded the
58 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
60 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
66 * ->i_mmap_rwsem (truncate_pagecache)
67 * ->private_lock (__free_pte->__set_page_dirty_buffers)
68 * ->swap_lock (exclusive_swap_page, others)
69 * ->mapping->tree_lock
72 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
76 * ->page_table_lock or pte_lock (various, mainly in memory.c)
77 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
80 * ->lock_page (access_process_vm)
82 * ->i_mutex (generic_perform_write)
83 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
86 * sb_lock (fs/fs-writeback.c)
87 * ->mapping->tree_lock (__sync_single_inode)
90 * ->anon_vma.lock (vma_adjust)
93 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
95 * ->page_table_lock or pte_lock
96 * ->swap_lock (try_to_unmap_one)
97 * ->private_lock (try_to_unmap_one)
98 * ->tree_lock (try_to_unmap_one)
99 * ->zone_lru_lock(zone) (follow_page->mark_page_accessed)
100 * ->zone_lru_lock(zone) (check_pte_range->isolate_lru_page)
101 * ->private_lock (page_remove_rmap->set_page_dirty)
102 * ->tree_lock (page_remove_rmap->set_page_dirty)
103 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
104 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
105 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
106 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
107 * ->inode->i_lock (zap_pte_range->set_page_dirty)
108 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
111 * ->tasklist_lock (memory_failure, collect_procs_ao)
114 static int page_cache_tree_insert(struct address_space *mapping,
115 struct page *page, void **shadowp)
117 struct radix_tree_node *node;
121 error = __radix_tree_create(&mapping->page_tree, page->index, 0,
128 p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
129 if (!radix_tree_exceptional_entry(p))
132 mapping->nrexceptional--;
133 if (!dax_mapping(mapping)) {
137 /* DAX can replace empty locked entry with a hole */
139 dax_radix_locked_entry(0, RADIX_DAX_EMPTY));
140 /* Wakeup waiters for exceptional entry lock */
141 dax_wake_mapping_entry_waiter(mapping, page->index, p,
145 __radix_tree_replace(&mapping->page_tree, node, slot, page,
146 workingset_update_node, mapping);
151 static void page_cache_tree_delete(struct address_space *mapping,
152 struct page *page, void *shadow)
156 /* hugetlb pages are represented by one entry in the radix tree */
157 nr = PageHuge(page) ? 1 : hpage_nr_pages(page);
159 VM_BUG_ON_PAGE(!PageLocked(page), page);
160 VM_BUG_ON_PAGE(PageTail(page), page);
161 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
163 for (i = 0; i < nr; i++) {
164 struct radix_tree_node *node;
167 __radix_tree_lookup(&mapping->page_tree, page->index + i,
170 VM_BUG_ON_PAGE(!node && nr != 1, page);
172 radix_tree_clear_tags(&mapping->page_tree, node, slot);
173 __radix_tree_replace(&mapping->page_tree, node, slot, shadow,
174 workingset_update_node, mapping);
178 mapping->nrexceptional += nr;
180 * Make sure the nrexceptional update is committed before
181 * the nrpages update so that final truncate racing
182 * with reclaim does not see both counters 0 at the
183 * same time and miss a shadow entry.
187 mapping->nrpages -= nr;
191 * Delete a page from the page cache and free it. Caller has to make
192 * sure the page is locked and that nobody else uses it - or that usage
193 * is safe. The caller must hold the mapping's tree_lock.
195 void __delete_from_page_cache(struct page *page, void *shadow)
197 struct address_space *mapping = page->mapping;
198 int nr = hpage_nr_pages(page);
200 trace_mm_filemap_delete_from_page_cache(page);
202 * if we're uptodate, flush out into the cleancache, otherwise
203 * invalidate any existing cleancache entries. We can't leave
204 * stale data around in the cleancache once our page is gone
206 if (PageUptodate(page) && PageMappedToDisk(page))
207 cleancache_put_page(page);
209 cleancache_invalidate_page(mapping, page);
211 VM_BUG_ON_PAGE(PageTail(page), page);
212 VM_BUG_ON_PAGE(page_mapped(page), page);
213 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
216 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
217 current->comm, page_to_pfn(page));
218 dump_page(page, "still mapped when deleted");
220 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
222 mapcount = page_mapcount(page);
223 if (mapping_exiting(mapping) &&
224 page_count(page) >= mapcount + 2) {
226 * All vmas have already been torn down, so it's
227 * a good bet that actually the page is unmapped,
228 * and we'd prefer not to leak it: if we're wrong,
229 * some other bad page check should catch it later.
231 page_mapcount_reset(page);
232 page_ref_sub(page, mapcount);
236 page_cache_tree_delete(mapping, page, shadow);
238 page->mapping = NULL;
239 /* Leave page->index set: truncation lookup relies upon it */
241 /* hugetlb pages do not participate in page cache accounting. */
243 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
244 if (PageSwapBacked(page)) {
245 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
246 if (PageTransHuge(page))
247 __dec_node_page_state(page, NR_SHMEM_THPS);
249 VM_BUG_ON_PAGE(PageTransHuge(page) && !PageHuge(page), page);
253 * At this point page must be either written or cleaned by truncate.
254 * Dirty page here signals a bug and loss of unwritten data.
256 * This fixes dirty accounting after removing the page entirely but
257 * leaves PageDirty set: it has no effect for truncated page and
258 * anyway will be cleared before returning page into buddy allocator.
260 if (WARN_ON_ONCE(PageDirty(page)))
261 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
265 * delete_from_page_cache - delete page from page cache
266 * @page: the page which the kernel is trying to remove from page cache
268 * This must be called only on pages that have been verified to be in the page
269 * cache and locked. It will never put the page into the free list, the caller
270 * has a reference on the page.
272 void delete_from_page_cache(struct page *page)
274 struct address_space *mapping = page_mapping(page);
276 void (*freepage)(struct page *);
278 BUG_ON(!PageLocked(page));
280 freepage = mapping->a_ops->freepage;
282 spin_lock_irqsave(&mapping->tree_lock, flags);
283 __delete_from_page_cache(page, NULL);
284 spin_unlock_irqrestore(&mapping->tree_lock, flags);
289 if (PageTransHuge(page) && !PageHuge(page)) {
290 page_ref_sub(page, HPAGE_PMD_NR);
291 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
296 EXPORT_SYMBOL(delete_from_page_cache);
298 int filemap_check_errors(struct address_space *mapping)
301 /* Check for outstanding write errors */
302 if (test_bit(AS_ENOSPC, &mapping->flags) &&
303 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
305 if (test_bit(AS_EIO, &mapping->flags) &&
306 test_and_clear_bit(AS_EIO, &mapping->flags))
310 EXPORT_SYMBOL(filemap_check_errors);
312 static int filemap_check_and_keep_errors(struct address_space *mapping)
314 /* Check for outstanding write errors */
315 if (test_bit(AS_EIO, &mapping->flags))
317 if (test_bit(AS_ENOSPC, &mapping->flags))
323 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
324 * @mapping: address space structure to write
325 * @start: offset in bytes where the range starts
326 * @end: offset in bytes where the range ends (inclusive)
327 * @sync_mode: enable synchronous operation
329 * Start writeback against all of a mapping's dirty pages that lie
330 * within the byte offsets <start, end> inclusive.
332 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
333 * opposed to a regular memory cleansing writeback. The difference between
334 * these two operations is that if a dirty page/buffer is encountered, it must
335 * be waited upon, and not just skipped over.
337 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
338 loff_t end, int sync_mode)
341 struct writeback_control wbc = {
342 .sync_mode = sync_mode,
343 .nr_to_write = LONG_MAX,
344 .range_start = start,
348 if (!mapping_cap_writeback_dirty(mapping))
351 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
352 ret = do_writepages(mapping, &wbc);
353 wbc_detach_inode(&wbc);
357 static inline int __filemap_fdatawrite(struct address_space *mapping,
360 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
363 int filemap_fdatawrite(struct address_space *mapping)
365 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
367 EXPORT_SYMBOL(filemap_fdatawrite);
369 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
372 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
374 EXPORT_SYMBOL(filemap_fdatawrite_range);
377 * filemap_flush - mostly a non-blocking flush
378 * @mapping: target address_space
380 * This is a mostly non-blocking flush. Not suitable for data-integrity
381 * purposes - I/O may not be started against all dirty pages.
383 int filemap_flush(struct address_space *mapping)
385 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
387 EXPORT_SYMBOL(filemap_flush);
389 static void __filemap_fdatawait_range(struct address_space *mapping,
390 loff_t start_byte, loff_t end_byte)
392 pgoff_t index = start_byte >> PAGE_SHIFT;
393 pgoff_t end = end_byte >> PAGE_SHIFT;
397 if (end_byte < start_byte)
400 pagevec_init(&pvec, 0);
401 while ((index <= end) &&
402 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
403 PAGECACHE_TAG_WRITEBACK,
404 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
407 for (i = 0; i < nr_pages; i++) {
408 struct page *page = pvec.pages[i];
410 /* until radix tree lookup accepts end_index */
411 if (page->index > end)
414 wait_on_page_writeback(page);
415 ClearPageError(page);
417 pagevec_release(&pvec);
423 * filemap_fdatawait_range - wait for writeback to complete
424 * @mapping: address space structure to wait for
425 * @start_byte: offset in bytes where the range starts
426 * @end_byte: offset in bytes where the range ends (inclusive)
428 * Walk the list of under-writeback pages of the given address space
429 * in the given range and wait for all of them. Check error status of
430 * the address space and return it.
432 * Since the error status of the address space is cleared by this function,
433 * callers are responsible for checking the return value and handling and/or
434 * reporting the error.
436 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
439 __filemap_fdatawait_range(mapping, start_byte, end_byte);
440 return filemap_check_errors(mapping);
442 EXPORT_SYMBOL(filemap_fdatawait_range);
445 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
446 * @mapping: address space structure to wait for
448 * Walk the list of under-writeback pages of the given address space
449 * and wait for all of them. Unlike filemap_fdatawait(), this function
450 * does not clear error status of the address space.
452 * Use this function if callers don't handle errors themselves. Expected
453 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
456 int filemap_fdatawait_keep_errors(struct address_space *mapping)
458 loff_t i_size = i_size_read(mapping->host);
463 __filemap_fdatawait_range(mapping, 0, i_size - 1);
464 return filemap_check_and_keep_errors(mapping);
466 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
469 * filemap_fdatawait - wait for all under-writeback pages to complete
470 * @mapping: address space structure to wait for
472 * Walk the list of under-writeback pages of the given address space
473 * and wait for all of them. Check error status of the address space
476 * Since the error status of the address space is cleared by this function,
477 * callers are responsible for checking the return value and handling and/or
478 * reporting the error.
480 int filemap_fdatawait(struct address_space *mapping)
482 loff_t i_size = i_size_read(mapping->host);
487 return filemap_fdatawait_range(mapping, 0, i_size - 1);
489 EXPORT_SYMBOL(filemap_fdatawait);
491 int filemap_write_and_wait(struct address_space *mapping)
495 if ((!dax_mapping(mapping) && mapping->nrpages) ||
496 (dax_mapping(mapping) && mapping->nrexceptional)) {
497 err = filemap_fdatawrite(mapping);
499 * Even if the above returned error, the pages may be
500 * written partially (e.g. -ENOSPC), so we wait for it.
501 * But the -EIO is special case, it may indicate the worst
502 * thing (e.g. bug) happened, so we avoid waiting for it.
505 int err2 = filemap_fdatawait(mapping);
509 /* Clear any previously stored errors */
510 filemap_check_errors(mapping);
513 err = filemap_check_errors(mapping);
517 EXPORT_SYMBOL(filemap_write_and_wait);
520 * filemap_write_and_wait_range - write out & wait on a file range
521 * @mapping: the address_space for the pages
522 * @lstart: offset in bytes where the range starts
523 * @lend: offset in bytes where the range ends (inclusive)
525 * Write out and wait upon file offsets lstart->lend, inclusive.
527 * Note that @lend is inclusive (describes the last byte to be written) so
528 * that this function can be used to write to the very end-of-file (end = -1).
530 int filemap_write_and_wait_range(struct address_space *mapping,
531 loff_t lstart, loff_t lend)
535 if ((!dax_mapping(mapping) && mapping->nrpages) ||
536 (dax_mapping(mapping) && mapping->nrexceptional)) {
537 err = __filemap_fdatawrite_range(mapping, lstart, lend,
539 /* See comment of filemap_write_and_wait() */
541 int err2 = filemap_fdatawait_range(mapping,
546 /* Clear any previously stored errors */
547 filemap_check_errors(mapping);
550 err = filemap_check_errors(mapping);
554 EXPORT_SYMBOL(filemap_write_and_wait_range);
557 * replace_page_cache_page - replace a pagecache page with a new one
558 * @old: page to be replaced
559 * @new: page to replace with
560 * @gfp_mask: allocation mode
562 * This function replaces a page in the pagecache with a new one. On
563 * success it acquires the pagecache reference for the new page and
564 * drops it for the old page. Both the old and new pages must be
565 * locked. This function does not add the new page to the LRU, the
566 * caller must do that.
568 * The remove + add is atomic. The only way this function can fail is
569 * memory allocation failure.
571 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
575 VM_BUG_ON_PAGE(!PageLocked(old), old);
576 VM_BUG_ON_PAGE(!PageLocked(new), new);
577 VM_BUG_ON_PAGE(new->mapping, new);
579 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
581 struct address_space *mapping = old->mapping;
582 void (*freepage)(struct page *);
585 pgoff_t offset = old->index;
586 freepage = mapping->a_ops->freepage;
589 new->mapping = mapping;
592 spin_lock_irqsave(&mapping->tree_lock, flags);
593 __delete_from_page_cache(old, NULL);
594 error = page_cache_tree_insert(mapping, new, NULL);
598 * hugetlb pages do not participate in page cache accounting.
601 __inc_node_page_state(new, NR_FILE_PAGES);
602 if (PageSwapBacked(new))
603 __inc_node_page_state(new, NR_SHMEM);
604 spin_unlock_irqrestore(&mapping->tree_lock, flags);
605 mem_cgroup_migrate(old, new);
606 radix_tree_preload_end();
614 EXPORT_SYMBOL_GPL(replace_page_cache_page);
616 static int __add_to_page_cache_locked(struct page *page,
617 struct address_space *mapping,
618 pgoff_t offset, gfp_t gfp_mask,
621 int huge = PageHuge(page);
622 struct mem_cgroup *memcg;
625 VM_BUG_ON_PAGE(!PageLocked(page), page);
626 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
629 error = mem_cgroup_try_charge(page, current->mm,
630 gfp_mask, &memcg, false);
635 error = radix_tree_maybe_preload(gfp_mask & ~__GFP_HIGHMEM);
638 mem_cgroup_cancel_charge(page, memcg, false);
643 page->mapping = mapping;
644 page->index = offset;
646 spin_lock_irq(&mapping->tree_lock);
647 error = page_cache_tree_insert(mapping, page, shadowp);
648 radix_tree_preload_end();
652 /* hugetlb pages do not participate in page cache accounting. */
654 __inc_node_page_state(page, NR_FILE_PAGES);
655 spin_unlock_irq(&mapping->tree_lock);
657 mem_cgroup_commit_charge(page, memcg, false, false);
658 trace_mm_filemap_add_to_page_cache(page);
661 page->mapping = NULL;
662 /* Leave page->index set: truncation relies upon it */
663 spin_unlock_irq(&mapping->tree_lock);
665 mem_cgroup_cancel_charge(page, memcg, false);
671 * add_to_page_cache_locked - add a locked page to the pagecache
673 * @mapping: the page's address_space
674 * @offset: page index
675 * @gfp_mask: page allocation mode
677 * This function is used to add a page to the pagecache. It must be locked.
678 * This function does not add the page to the LRU. The caller must do that.
680 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
681 pgoff_t offset, gfp_t gfp_mask)
683 return __add_to_page_cache_locked(page, mapping, offset,
686 EXPORT_SYMBOL(add_to_page_cache_locked);
688 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
689 pgoff_t offset, gfp_t gfp_mask)
694 __SetPageLocked(page);
695 ret = __add_to_page_cache_locked(page, mapping, offset,
698 __ClearPageLocked(page);
701 * The page might have been evicted from cache only
702 * recently, in which case it should be activated like
703 * any other repeatedly accessed page.
704 * The exception is pages getting rewritten; evicting other
705 * data from the working set, only to cache data that will
706 * get overwritten with something else, is a waste of memory.
708 if (!(gfp_mask & __GFP_WRITE) &&
709 shadow && workingset_refault(shadow)) {
711 workingset_activation(page);
713 ClearPageActive(page);
718 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
721 struct page *__page_cache_alloc(gfp_t gfp)
726 if (cpuset_do_page_mem_spread()) {
727 unsigned int cpuset_mems_cookie;
729 cpuset_mems_cookie = read_mems_allowed_begin();
730 n = cpuset_mem_spread_node();
731 page = __alloc_pages_node(n, gfp, 0);
732 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
736 return alloc_pages(gfp, 0);
738 EXPORT_SYMBOL(__page_cache_alloc);
742 * In order to wait for pages to become available there must be
743 * waitqueues associated with pages. By using a hash table of
744 * waitqueues where the bucket discipline is to maintain all
745 * waiters on the same queue and wake all when any of the pages
746 * become available, and for the woken contexts to check to be
747 * sure the appropriate page became available, this saves space
748 * at a cost of "thundering herd" phenomena during rare hash
751 #define PAGE_WAIT_TABLE_BITS 8
752 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
753 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
755 static wait_queue_head_t *page_waitqueue(struct page *page)
757 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
760 void __init pagecache_init(void)
764 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
765 init_waitqueue_head(&page_wait_table[i]);
767 page_writeback_init();
770 struct wait_page_key {
776 struct wait_page_queue {
782 static int wake_page_function(wait_queue_t *wait, unsigned mode, int sync, void *arg)
784 struct wait_page_key *key = arg;
785 struct wait_page_queue *wait_page
786 = container_of(wait, struct wait_page_queue, wait);
788 if (wait_page->page != key->page)
792 if (wait_page->bit_nr != key->bit_nr)
794 if (test_bit(key->bit_nr, &key->page->flags))
797 return autoremove_wake_function(wait, mode, sync, key);
800 static void wake_up_page_bit(struct page *page, int bit_nr)
802 wait_queue_head_t *q = page_waitqueue(page);
803 struct wait_page_key key;
810 spin_lock_irqsave(&q->lock, flags);
811 __wake_up_locked_key(q, TASK_NORMAL, &key);
813 * It is possible for other pages to have collided on the waitqueue
814 * hash, so in that case check for a page match. That prevents a long-
817 * It is still possible to miss a case here, when we woke page waiters
818 * and removed them from the waitqueue, but there are still other
821 if (!waitqueue_active(q) || !key.page_match) {
822 ClearPageWaiters(page);
824 * It's possible to miss clearing Waiters here, when we woke
825 * our page waiters, but the hashed waitqueue has waiters for
828 * That's okay, it's a rare case. The next waker will clear it.
831 spin_unlock_irqrestore(&q->lock, flags);
834 static void wake_up_page(struct page *page, int bit)
836 if (!PageWaiters(page))
838 wake_up_page_bit(page, bit);
841 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
842 struct page *page, int bit_nr, int state, bool lock)
844 struct wait_page_queue wait_page;
845 wait_queue_t *wait = &wait_page.wait;
849 wait->func = wake_page_function;
850 wait_page.page = page;
851 wait_page.bit_nr = bit_nr;
854 spin_lock_irq(&q->lock);
856 if (likely(list_empty(&wait->task_list))) {
858 __add_wait_queue_tail_exclusive(q, wait);
860 __add_wait_queue(q, wait);
861 SetPageWaiters(page);
864 set_current_state(state);
866 spin_unlock_irq(&q->lock);
868 if (likely(test_bit(bit_nr, &page->flags))) {
870 if (unlikely(signal_pending_state(state, current))) {
877 if (!test_and_set_bit_lock(bit_nr, &page->flags))
880 if (!test_bit(bit_nr, &page->flags))
885 finish_wait(q, wait);
888 * A signal could leave PageWaiters set. Clearing it here if
889 * !waitqueue_active would be possible (by open-coding finish_wait),
890 * but still fail to catch it in the case of wait hash collision. We
891 * already can fail to clear wait hash collision cases, so don't
892 * bother with signals either.
898 void wait_on_page_bit(struct page *page, int bit_nr)
900 wait_queue_head_t *q = page_waitqueue(page);
901 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, false);
903 EXPORT_SYMBOL(wait_on_page_bit);
905 int wait_on_page_bit_killable(struct page *page, int bit_nr)
907 wait_queue_head_t *q = page_waitqueue(page);
908 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, false);
912 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
913 * @page: Page defining the wait queue of interest
914 * @waiter: Waiter to add to the queue
916 * Add an arbitrary @waiter to the wait queue for the nominated @page.
918 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
920 wait_queue_head_t *q = page_waitqueue(page);
923 spin_lock_irqsave(&q->lock, flags);
924 __add_wait_queue(q, waiter);
925 SetPageWaiters(page);
926 spin_unlock_irqrestore(&q->lock, flags);
928 EXPORT_SYMBOL_GPL(add_page_wait_queue);
930 #ifndef clear_bit_unlock_is_negative_byte
933 * PG_waiters is the high bit in the same byte as PG_lock.
935 * On x86 (and on many other architectures), we can clear PG_lock and
936 * test the sign bit at the same time. But if the architecture does
937 * not support that special operation, we just do this all by hand
940 * The read of PG_waiters has to be after (or concurrently with) PG_locked
941 * being cleared, but a memory barrier should be unneccssary since it is
942 * in the same byte as PG_locked.
944 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
946 clear_bit_unlock(nr, mem);
947 /* smp_mb__after_atomic(); */
948 return test_bit(PG_waiters, mem);
954 * unlock_page - unlock a locked page
957 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
958 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
959 * mechanism between PageLocked pages and PageWriteback pages is shared.
960 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
962 * Note that this depends on PG_waiters being the sign bit in the byte
963 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
964 * clear the PG_locked bit and test PG_waiters at the same time fairly
965 * portably (architectures that do LL/SC can test any bit, while x86 can
966 * test the sign bit).
968 void unlock_page(struct page *page)
970 BUILD_BUG_ON(PG_waiters != 7);
971 page = compound_head(page);
972 VM_BUG_ON_PAGE(!PageLocked(page), page);
973 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
974 wake_up_page_bit(page, PG_locked);
976 EXPORT_SYMBOL(unlock_page);
979 * end_page_writeback - end writeback against a page
982 void end_page_writeback(struct page *page)
985 * TestClearPageReclaim could be used here but it is an atomic
986 * operation and overkill in this particular case. Failing to
987 * shuffle a page marked for immediate reclaim is too mild to
988 * justify taking an atomic operation penalty at the end of
989 * ever page writeback.
991 if (PageReclaim(page)) {
992 ClearPageReclaim(page);
993 rotate_reclaimable_page(page);
996 if (!test_clear_page_writeback(page))
999 smp_mb__after_atomic();
1000 wake_up_page(page, PG_writeback);
1002 EXPORT_SYMBOL(end_page_writeback);
1005 * After completing I/O on a page, call this routine to update the page
1006 * flags appropriately
1008 void page_endio(struct page *page, bool is_write, int err)
1012 SetPageUptodate(page);
1014 ClearPageUptodate(page);
1020 struct address_space *mapping;
1023 mapping = page_mapping(page);
1025 mapping_set_error(mapping, err);
1027 end_page_writeback(page);
1030 EXPORT_SYMBOL_GPL(page_endio);
1033 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1034 * @__page: the page to lock
1036 void __lock_page(struct page *__page)
1038 struct page *page = compound_head(__page);
1039 wait_queue_head_t *q = page_waitqueue(page);
1040 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, true);
1042 EXPORT_SYMBOL(__lock_page);
1044 int __lock_page_killable(struct page *__page)
1046 struct page *page = compound_head(__page);
1047 wait_queue_head_t *q = page_waitqueue(page);
1048 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE, true);
1050 EXPORT_SYMBOL_GPL(__lock_page_killable);
1054 * 1 - page is locked; mmap_sem is still held.
1055 * 0 - page is not locked.
1056 * mmap_sem has been released (up_read()), unless flags had both
1057 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1058 * which case mmap_sem is still held.
1060 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1061 * with the page locked and the mmap_sem unperturbed.
1063 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1066 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1068 * CAUTION! In this case, mmap_sem is not released
1069 * even though return 0.
1071 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1074 up_read(&mm->mmap_sem);
1075 if (flags & FAULT_FLAG_KILLABLE)
1076 wait_on_page_locked_killable(page);
1078 wait_on_page_locked(page);
1081 if (flags & FAULT_FLAG_KILLABLE) {
1084 ret = __lock_page_killable(page);
1086 up_read(&mm->mmap_sem);
1096 * page_cache_next_hole - find the next hole (not-present entry)
1099 * @max_scan: maximum range to search
1101 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1102 * lowest indexed hole.
1104 * Returns: the index of the hole if found, otherwise returns an index
1105 * outside of the set specified (in which case 'return - index >=
1106 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1109 * page_cache_next_hole may be called under rcu_read_lock. However,
1110 * like radix_tree_gang_lookup, this will not atomically search a
1111 * snapshot of the tree at a single point in time. For example, if a
1112 * hole is created at index 5, then subsequently a hole is created at
1113 * index 10, page_cache_next_hole covering both indexes may return 10
1114 * if called under rcu_read_lock.
1116 pgoff_t page_cache_next_hole(struct address_space *mapping,
1117 pgoff_t index, unsigned long max_scan)
1121 for (i = 0; i < max_scan; i++) {
1124 page = radix_tree_lookup(&mapping->page_tree, index);
1125 if (!page || radix_tree_exceptional_entry(page))
1134 EXPORT_SYMBOL(page_cache_next_hole);
1137 * page_cache_prev_hole - find the prev hole (not-present entry)
1140 * @max_scan: maximum range to search
1142 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1145 * Returns: the index of the hole if found, otherwise returns an index
1146 * outside of the set specified (in which case 'index - return >=
1147 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1150 * page_cache_prev_hole may be called under rcu_read_lock. However,
1151 * like radix_tree_gang_lookup, this will not atomically search a
1152 * snapshot of the tree at a single point in time. For example, if a
1153 * hole is created at index 10, then subsequently a hole is created at
1154 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1155 * called under rcu_read_lock.
1157 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1158 pgoff_t index, unsigned long max_scan)
1162 for (i = 0; i < max_scan; i++) {
1165 page = radix_tree_lookup(&mapping->page_tree, index);
1166 if (!page || radix_tree_exceptional_entry(page))
1169 if (index == ULONG_MAX)
1175 EXPORT_SYMBOL(page_cache_prev_hole);
1178 * find_get_entry - find and get a page cache entry
1179 * @mapping: the address_space to search
1180 * @offset: the page cache index
1182 * Looks up the page cache slot at @mapping & @offset. If there is a
1183 * page cache page, it is returned with an increased refcount.
1185 * If the slot holds a shadow entry of a previously evicted page, or a
1186 * swap entry from shmem/tmpfs, it is returned.
1188 * Otherwise, %NULL is returned.
1190 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1193 struct page *head, *page;
1198 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1200 page = radix_tree_deref_slot(pagep);
1201 if (unlikely(!page))
1203 if (radix_tree_exception(page)) {
1204 if (radix_tree_deref_retry(page))
1207 * A shadow entry of a recently evicted page,
1208 * or a swap entry from shmem/tmpfs. Return
1209 * it without attempting to raise page count.
1214 head = compound_head(page);
1215 if (!page_cache_get_speculative(head))
1218 /* The page was split under us? */
1219 if (compound_head(page) != head) {
1225 * Has the page moved?
1226 * This is part of the lockless pagecache protocol. See
1227 * include/linux/pagemap.h for details.
1229 if (unlikely(page != *pagep)) {
1239 EXPORT_SYMBOL(find_get_entry);
1242 * find_lock_entry - locate, pin and lock a page cache entry
1243 * @mapping: the address_space to search
1244 * @offset: the page cache index
1246 * Looks up the page cache slot at @mapping & @offset. If there is a
1247 * page cache page, it is returned locked and with an increased
1250 * If the slot holds a shadow entry of a previously evicted page, or a
1251 * swap entry from shmem/tmpfs, it is returned.
1253 * Otherwise, %NULL is returned.
1255 * find_lock_entry() may sleep.
1257 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1262 page = find_get_entry(mapping, offset);
1263 if (page && !radix_tree_exception(page)) {
1265 /* Has the page been truncated? */
1266 if (unlikely(page_mapping(page) != mapping)) {
1271 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1275 EXPORT_SYMBOL(find_lock_entry);
1278 * pagecache_get_page - find and get a page reference
1279 * @mapping: the address_space to search
1280 * @offset: the page index
1281 * @fgp_flags: PCG flags
1282 * @gfp_mask: gfp mask to use for the page cache data page allocation
1284 * Looks up the page cache slot at @mapping & @offset.
1286 * PCG flags modify how the page is returned.
1288 * @fgp_flags can be:
1290 * - FGP_ACCESSED: the page will be marked accessed
1291 * - FGP_LOCK: Page is return locked
1292 * - FGP_CREAT: If page is not present then a new page is allocated using
1293 * @gfp_mask and added to the page cache and the VM's LRU
1294 * list. The page is returned locked and with an increased
1295 * refcount. Otherwise, NULL is returned.
1297 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1298 * if the GFP flags specified for FGP_CREAT are atomic.
1300 * If there is a page cache page, it is returned with an increased refcount.
1302 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1303 int fgp_flags, gfp_t gfp_mask)
1308 page = find_get_entry(mapping, offset);
1309 if (radix_tree_exceptional_entry(page))
1314 if (fgp_flags & FGP_LOCK) {
1315 if (fgp_flags & FGP_NOWAIT) {
1316 if (!trylock_page(page)) {
1324 /* Has the page been truncated? */
1325 if (unlikely(page->mapping != mapping)) {
1330 VM_BUG_ON_PAGE(page->index != offset, page);
1333 if (page && (fgp_flags & FGP_ACCESSED))
1334 mark_page_accessed(page);
1337 if (!page && (fgp_flags & FGP_CREAT)) {
1339 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1340 gfp_mask |= __GFP_WRITE;
1341 if (fgp_flags & FGP_NOFS)
1342 gfp_mask &= ~__GFP_FS;
1344 page = __page_cache_alloc(gfp_mask);
1348 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1349 fgp_flags |= FGP_LOCK;
1351 /* Init accessed so avoid atomic mark_page_accessed later */
1352 if (fgp_flags & FGP_ACCESSED)
1353 __SetPageReferenced(page);
1355 err = add_to_page_cache_lru(page, mapping, offset,
1356 gfp_mask & GFP_RECLAIM_MASK);
1357 if (unlikely(err)) {
1367 EXPORT_SYMBOL(pagecache_get_page);
1370 * find_get_entries - gang pagecache lookup
1371 * @mapping: The address_space to search
1372 * @start: The starting page cache index
1373 * @nr_entries: The maximum number of entries
1374 * @entries: Where the resulting entries are placed
1375 * @indices: The cache indices corresponding to the entries in @entries
1377 * find_get_entries() will search for and return a group of up to
1378 * @nr_entries entries in the mapping. The entries are placed at
1379 * @entries. find_get_entries() takes a reference against any actual
1382 * The search returns a group of mapping-contiguous page cache entries
1383 * with ascending indexes. There may be holes in the indices due to
1384 * not-present pages.
1386 * Any shadow entries of evicted pages, or swap entries from
1387 * shmem/tmpfs, are included in the returned array.
1389 * find_get_entries() returns the number of pages and shadow entries
1392 unsigned find_get_entries(struct address_space *mapping,
1393 pgoff_t start, unsigned int nr_entries,
1394 struct page **entries, pgoff_t *indices)
1397 unsigned int ret = 0;
1398 struct radix_tree_iter iter;
1404 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1405 struct page *head, *page;
1407 page = radix_tree_deref_slot(slot);
1408 if (unlikely(!page))
1410 if (radix_tree_exception(page)) {
1411 if (radix_tree_deref_retry(page)) {
1412 slot = radix_tree_iter_retry(&iter);
1416 * A shadow entry of a recently evicted page, a swap
1417 * entry from shmem/tmpfs or a DAX entry. Return it
1418 * without attempting to raise page count.
1423 head = compound_head(page);
1424 if (!page_cache_get_speculative(head))
1427 /* The page was split under us? */
1428 if (compound_head(page) != head) {
1433 /* Has the page moved? */
1434 if (unlikely(page != *slot)) {
1439 indices[ret] = iter.index;
1440 entries[ret] = page;
1441 if (++ret == nr_entries)
1449 * find_get_pages - gang pagecache lookup
1450 * @mapping: The address_space to search
1451 * @start: The starting page index
1452 * @nr_pages: The maximum number of pages
1453 * @pages: Where the resulting pages are placed
1455 * find_get_pages() will search for and return a group of up to
1456 * @nr_pages pages in the mapping. The pages are placed at @pages.
1457 * find_get_pages() takes a reference against the returned pages.
1459 * The search returns a group of mapping-contiguous pages with ascending
1460 * indexes. There may be holes in the indices due to not-present pages.
1462 * find_get_pages() returns the number of pages which were found.
1464 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
1465 unsigned int nr_pages, struct page **pages)
1467 struct radix_tree_iter iter;
1471 if (unlikely(!nr_pages))
1475 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1476 struct page *head, *page;
1478 page = radix_tree_deref_slot(slot);
1479 if (unlikely(!page))
1482 if (radix_tree_exception(page)) {
1483 if (radix_tree_deref_retry(page)) {
1484 slot = radix_tree_iter_retry(&iter);
1488 * A shadow entry of a recently evicted page,
1489 * or a swap entry from shmem/tmpfs. Skip
1495 head = compound_head(page);
1496 if (!page_cache_get_speculative(head))
1499 /* The page was split under us? */
1500 if (compound_head(page) != head) {
1505 /* Has the page moved? */
1506 if (unlikely(page != *slot)) {
1512 if (++ret == nr_pages)
1521 * find_get_pages_contig - gang contiguous pagecache lookup
1522 * @mapping: The address_space to search
1523 * @index: The starting page index
1524 * @nr_pages: The maximum number of pages
1525 * @pages: Where the resulting pages are placed
1527 * find_get_pages_contig() works exactly like find_get_pages(), except
1528 * that the returned number of pages are guaranteed to be contiguous.
1530 * find_get_pages_contig() returns the number of pages which were found.
1532 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1533 unsigned int nr_pages, struct page **pages)
1535 struct radix_tree_iter iter;
1537 unsigned int ret = 0;
1539 if (unlikely(!nr_pages))
1543 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1544 struct page *head, *page;
1546 page = radix_tree_deref_slot(slot);
1547 /* The hole, there no reason to continue */
1548 if (unlikely(!page))
1551 if (radix_tree_exception(page)) {
1552 if (radix_tree_deref_retry(page)) {
1553 slot = radix_tree_iter_retry(&iter);
1557 * A shadow entry of a recently evicted page,
1558 * or a swap entry from shmem/tmpfs. Stop
1559 * looking for contiguous pages.
1564 head = compound_head(page);
1565 if (!page_cache_get_speculative(head))
1568 /* The page was split under us? */
1569 if (compound_head(page) != head) {
1574 /* Has the page moved? */
1575 if (unlikely(page != *slot)) {
1581 * must check mapping and index after taking the ref.
1582 * otherwise we can get both false positives and false
1583 * negatives, which is just confusing to the caller.
1585 if (page->mapping == NULL || page_to_pgoff(page) != iter.index) {
1591 if (++ret == nr_pages)
1597 EXPORT_SYMBOL(find_get_pages_contig);
1600 * find_get_pages_tag - find and return pages that match @tag
1601 * @mapping: the address_space to search
1602 * @index: the starting page index
1603 * @tag: the tag index
1604 * @nr_pages: the maximum number of pages
1605 * @pages: where the resulting pages are placed
1607 * Like find_get_pages, except we only return pages which are tagged with
1608 * @tag. We update @index to index the next page for the traversal.
1610 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1611 int tag, unsigned int nr_pages, struct page **pages)
1613 struct radix_tree_iter iter;
1617 if (unlikely(!nr_pages))
1621 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1622 &iter, *index, tag) {
1623 struct page *head, *page;
1625 page = radix_tree_deref_slot(slot);
1626 if (unlikely(!page))
1629 if (radix_tree_exception(page)) {
1630 if (radix_tree_deref_retry(page)) {
1631 slot = radix_tree_iter_retry(&iter);
1635 * A shadow entry of a recently evicted page.
1637 * Those entries should never be tagged, but
1638 * this tree walk is lockless and the tags are
1639 * looked up in bulk, one radix tree node at a
1640 * time, so there is a sizable window for page
1641 * reclaim to evict a page we saw tagged.
1648 head = compound_head(page);
1649 if (!page_cache_get_speculative(head))
1652 /* The page was split under us? */
1653 if (compound_head(page) != head) {
1658 /* Has the page moved? */
1659 if (unlikely(page != *slot)) {
1665 if (++ret == nr_pages)
1672 *index = pages[ret - 1]->index + 1;
1676 EXPORT_SYMBOL(find_get_pages_tag);
1679 * find_get_entries_tag - find and return entries that match @tag
1680 * @mapping: the address_space to search
1681 * @start: the starting page cache index
1682 * @tag: the tag index
1683 * @nr_entries: the maximum number of entries
1684 * @entries: where the resulting entries are placed
1685 * @indices: the cache indices corresponding to the entries in @entries
1687 * Like find_get_entries, except we only return entries which are tagged with
1690 unsigned find_get_entries_tag(struct address_space *mapping, pgoff_t start,
1691 int tag, unsigned int nr_entries,
1692 struct page **entries, pgoff_t *indices)
1695 unsigned int ret = 0;
1696 struct radix_tree_iter iter;
1702 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1703 &iter, start, tag) {
1704 struct page *head, *page;
1706 page = radix_tree_deref_slot(slot);
1707 if (unlikely(!page))
1709 if (radix_tree_exception(page)) {
1710 if (radix_tree_deref_retry(page)) {
1711 slot = radix_tree_iter_retry(&iter);
1716 * A shadow entry of a recently evicted page, a swap
1717 * entry from shmem/tmpfs or a DAX entry. Return it
1718 * without attempting to raise page count.
1723 head = compound_head(page);
1724 if (!page_cache_get_speculative(head))
1727 /* The page was split under us? */
1728 if (compound_head(page) != head) {
1733 /* Has the page moved? */
1734 if (unlikely(page != *slot)) {
1739 indices[ret] = iter.index;
1740 entries[ret] = page;
1741 if (++ret == nr_entries)
1747 EXPORT_SYMBOL(find_get_entries_tag);
1750 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1751 * a _large_ part of the i/o request. Imagine the worst scenario:
1753 * ---R__________________________________________B__________
1754 * ^ reading here ^ bad block(assume 4k)
1756 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1757 * => failing the whole request => read(R) => read(R+1) =>
1758 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1759 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1760 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1762 * It is going insane. Fix it by quickly scaling down the readahead size.
1764 static void shrink_readahead_size_eio(struct file *filp,
1765 struct file_ra_state *ra)
1771 * do_generic_file_read - generic file read routine
1772 * @filp: the file to read
1773 * @ppos: current file position
1774 * @iter: data destination
1775 * @written: already copied
1777 * This is a generic file read routine, and uses the
1778 * mapping->a_ops->readpage() function for the actual low-level stuff.
1780 * This is really ugly. But the goto's actually try to clarify some
1781 * of the logic when it comes to error handling etc.
1783 static ssize_t do_generic_file_read(struct file *filp, loff_t *ppos,
1784 struct iov_iter *iter, ssize_t written)
1786 struct address_space *mapping = filp->f_mapping;
1787 struct inode *inode = mapping->host;
1788 struct file_ra_state *ra = &filp->f_ra;
1792 unsigned long offset; /* offset into pagecache page */
1793 unsigned int prev_offset;
1796 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
1798 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
1800 index = *ppos >> PAGE_SHIFT;
1801 prev_index = ra->prev_pos >> PAGE_SHIFT;
1802 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
1803 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
1804 offset = *ppos & ~PAGE_MASK;
1810 unsigned long nr, ret;
1814 if (fatal_signal_pending(current)) {
1819 page = find_get_page(mapping, index);
1821 page_cache_sync_readahead(mapping,
1823 index, last_index - index);
1824 page = find_get_page(mapping, index);
1825 if (unlikely(page == NULL))
1826 goto no_cached_page;
1828 if (PageReadahead(page)) {
1829 page_cache_async_readahead(mapping,
1831 index, last_index - index);
1833 if (!PageUptodate(page)) {
1835 * See comment in do_read_cache_page on why
1836 * wait_on_page_locked is used to avoid unnecessarily
1837 * serialisations and why it's safe.
1839 error = wait_on_page_locked_killable(page);
1840 if (unlikely(error))
1841 goto readpage_error;
1842 if (PageUptodate(page))
1845 if (inode->i_blkbits == PAGE_SHIFT ||
1846 !mapping->a_ops->is_partially_uptodate)
1847 goto page_not_up_to_date;
1848 /* pipes can't handle partially uptodate pages */
1849 if (unlikely(iter->type & ITER_PIPE))
1850 goto page_not_up_to_date;
1851 if (!trylock_page(page))
1852 goto page_not_up_to_date;
1853 /* Did it get truncated before we got the lock? */
1855 goto page_not_up_to_date_locked;
1856 if (!mapping->a_ops->is_partially_uptodate(page,
1857 offset, iter->count))
1858 goto page_not_up_to_date_locked;
1863 * i_size must be checked after we know the page is Uptodate.
1865 * Checking i_size after the check allows us to calculate
1866 * the correct value for "nr", which means the zero-filled
1867 * part of the page is not copied back to userspace (unless
1868 * another truncate extends the file - this is desired though).
1871 isize = i_size_read(inode);
1872 end_index = (isize - 1) >> PAGE_SHIFT;
1873 if (unlikely(!isize || index > end_index)) {
1878 /* nr is the maximum number of bytes to copy from this page */
1880 if (index == end_index) {
1881 nr = ((isize - 1) & ~PAGE_MASK) + 1;
1889 /* If users can be writing to this page using arbitrary
1890 * virtual addresses, take care about potential aliasing
1891 * before reading the page on the kernel side.
1893 if (mapping_writably_mapped(mapping))
1894 flush_dcache_page(page);
1897 * When a sequential read accesses a page several times,
1898 * only mark it as accessed the first time.
1900 if (prev_index != index || offset != prev_offset)
1901 mark_page_accessed(page);
1905 * Ok, we have the page, and it's up-to-date, so
1906 * now we can copy it to user space...
1909 ret = copy_page_to_iter(page, offset, nr, iter);
1911 index += offset >> PAGE_SHIFT;
1912 offset &= ~PAGE_MASK;
1913 prev_offset = offset;
1917 if (!iov_iter_count(iter))
1925 page_not_up_to_date:
1926 /* Get exclusive access to the page ... */
1927 error = lock_page_killable(page);
1928 if (unlikely(error))
1929 goto readpage_error;
1931 page_not_up_to_date_locked:
1932 /* Did it get truncated before we got the lock? */
1933 if (!page->mapping) {
1939 /* Did somebody else fill it already? */
1940 if (PageUptodate(page)) {
1947 * A previous I/O error may have been due to temporary
1948 * failures, eg. multipath errors.
1949 * PG_error will be set again if readpage fails.
1951 ClearPageError(page);
1952 /* Start the actual read. The read will unlock the page. */
1953 error = mapping->a_ops->readpage(filp, page);
1955 if (unlikely(error)) {
1956 if (error == AOP_TRUNCATED_PAGE) {
1961 goto readpage_error;
1964 if (!PageUptodate(page)) {
1965 error = lock_page_killable(page);
1966 if (unlikely(error))
1967 goto readpage_error;
1968 if (!PageUptodate(page)) {
1969 if (page->mapping == NULL) {
1971 * invalidate_mapping_pages got it
1978 shrink_readahead_size_eio(filp, ra);
1980 goto readpage_error;
1988 /* UHHUH! A synchronous read error occurred. Report it */
1994 * Ok, it wasn't cached, so we need to create a new
1997 page = page_cache_alloc_cold(mapping);
2002 error = add_to_page_cache_lru(page, mapping, index,
2003 mapping_gfp_constraint(mapping, GFP_KERNEL));
2006 if (error == -EEXIST) {
2016 ra->prev_pos = prev_index;
2017 ra->prev_pos <<= PAGE_SHIFT;
2018 ra->prev_pos |= prev_offset;
2020 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2021 file_accessed(filp);
2022 return written ? written : error;
2026 * generic_file_read_iter - generic filesystem read routine
2027 * @iocb: kernel I/O control block
2028 * @iter: destination for the data read
2030 * This is the "read_iter()" routine for all filesystems
2031 * that can use the page cache directly.
2034 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2036 struct file *file = iocb->ki_filp;
2038 size_t count = iov_iter_count(iter);
2041 goto out; /* skip atime */
2043 if (iocb->ki_flags & IOCB_DIRECT) {
2044 struct address_space *mapping = file->f_mapping;
2045 struct inode *inode = mapping->host;
2048 size = i_size_read(inode);
2049 retval = filemap_write_and_wait_range(mapping, iocb->ki_pos,
2050 iocb->ki_pos + count - 1);
2054 file_accessed(file);
2056 retval = mapping->a_ops->direct_IO(iocb, iter);
2058 iocb->ki_pos += retval;
2061 iov_iter_revert(iter, count - iov_iter_count(iter));
2064 * Btrfs can have a short DIO read if we encounter
2065 * compressed extents, so if there was an error, or if
2066 * we've already read everything we wanted to, or if
2067 * there was a short read because we hit EOF, go ahead
2068 * and return. Otherwise fallthrough to buffered io for
2069 * the rest of the read. Buffered reads will not work for
2070 * DAX files, so don't bother trying.
2072 if (retval < 0 || !count || iocb->ki_pos >= size ||
2077 retval = do_generic_file_read(file, &iocb->ki_pos, iter, retval);
2081 EXPORT_SYMBOL(generic_file_read_iter);
2085 * page_cache_read - adds requested page to the page cache if not already there
2086 * @file: file to read
2087 * @offset: page index
2088 * @gfp_mask: memory allocation flags
2090 * This adds the requested page to the page cache if it isn't already there,
2091 * and schedules an I/O to read in its contents from disk.
2093 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
2095 struct address_space *mapping = file->f_mapping;
2100 page = __page_cache_alloc(gfp_mask|__GFP_COLD);
2104 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask & GFP_KERNEL);
2106 ret = mapping->a_ops->readpage(file, page);
2107 else if (ret == -EEXIST)
2108 ret = 0; /* losing race to add is OK */
2112 } while (ret == AOP_TRUNCATED_PAGE);
2117 #define MMAP_LOTSAMISS (100)
2120 * Synchronous readahead happens when we don't even find
2121 * a page in the page cache at all.
2123 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
2124 struct file_ra_state *ra,
2128 struct address_space *mapping = file->f_mapping;
2130 /* If we don't want any read-ahead, don't bother */
2131 if (vma->vm_flags & VM_RAND_READ)
2136 if (vma->vm_flags & VM_SEQ_READ) {
2137 page_cache_sync_readahead(mapping, ra, file, offset,
2142 /* Avoid banging the cache line if not needed */
2143 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2147 * Do we miss much more than hit in this file? If so,
2148 * stop bothering with read-ahead. It will only hurt.
2150 if (ra->mmap_miss > MMAP_LOTSAMISS)
2156 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2157 ra->size = ra->ra_pages;
2158 ra->async_size = ra->ra_pages / 4;
2159 ra_submit(ra, mapping, file);
2163 * Asynchronous readahead happens when we find the page and PG_readahead,
2164 * so we want to possibly extend the readahead further..
2166 static void do_async_mmap_readahead(struct vm_area_struct *vma,
2167 struct file_ra_state *ra,
2172 struct address_space *mapping = file->f_mapping;
2174 /* If we don't want any read-ahead, don't bother */
2175 if (vma->vm_flags & VM_RAND_READ)
2177 if (ra->mmap_miss > 0)
2179 if (PageReadahead(page))
2180 page_cache_async_readahead(mapping, ra, file,
2181 page, offset, ra->ra_pages);
2185 * filemap_fault - read in file data for page fault handling
2186 * @vmf: struct vm_fault containing details of the fault
2188 * filemap_fault() is invoked via the vma operations vector for a
2189 * mapped memory region to read in file data during a page fault.
2191 * The goto's are kind of ugly, but this streamlines the normal case of having
2192 * it in the page cache, and handles the special cases reasonably without
2193 * having a lot of duplicated code.
2195 * vma->vm_mm->mmap_sem must be held on entry.
2197 * If our return value has VM_FAULT_RETRY set, it's because
2198 * lock_page_or_retry() returned 0.
2199 * The mmap_sem has usually been released in this case.
2200 * See __lock_page_or_retry() for the exception.
2202 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2203 * has not been released.
2205 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2207 int filemap_fault(struct vm_fault *vmf)
2210 struct file *file = vmf->vma->vm_file;
2211 struct address_space *mapping = file->f_mapping;
2212 struct file_ra_state *ra = &file->f_ra;
2213 struct inode *inode = mapping->host;
2214 pgoff_t offset = vmf->pgoff;
2219 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2220 if (unlikely(offset >= max_off))
2221 return VM_FAULT_SIGBUS;
2224 * Do we have something in the page cache already?
2226 page = find_get_page(mapping, offset);
2227 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2229 * We found the page, so try async readahead before
2230 * waiting for the lock.
2232 do_async_mmap_readahead(vmf->vma, ra, file, page, offset);
2234 /* No page in the page cache at all */
2235 do_sync_mmap_readahead(vmf->vma, ra, file, offset);
2236 count_vm_event(PGMAJFAULT);
2237 mem_cgroup_count_vm_event(vmf->vma->vm_mm, PGMAJFAULT);
2238 ret = VM_FAULT_MAJOR;
2240 page = find_get_page(mapping, offset);
2242 goto no_cached_page;
2245 if (!lock_page_or_retry(page, vmf->vma->vm_mm, vmf->flags)) {
2247 return ret | VM_FAULT_RETRY;
2250 /* Did it get truncated? */
2251 if (unlikely(page->mapping != mapping)) {
2256 VM_BUG_ON_PAGE(page->index != offset, page);
2259 * We have a locked page in the page cache, now we need to check
2260 * that it's up-to-date. If not, it is going to be due to an error.
2262 if (unlikely(!PageUptodate(page)))
2263 goto page_not_uptodate;
2266 * Found the page and have a reference on it.
2267 * We must recheck i_size under page lock.
2269 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2270 if (unlikely(offset >= max_off)) {
2273 return VM_FAULT_SIGBUS;
2277 return ret | VM_FAULT_LOCKED;
2281 * We're only likely to ever get here if MADV_RANDOM is in
2284 error = page_cache_read(file, offset, vmf->gfp_mask);
2287 * The page we want has now been added to the page cache.
2288 * In the unlikely event that someone removed it in the
2289 * meantime, we'll just come back here and read it again.
2295 * An error return from page_cache_read can result if the
2296 * system is low on memory, or a problem occurs while trying
2299 if (error == -ENOMEM)
2300 return VM_FAULT_OOM;
2301 return VM_FAULT_SIGBUS;
2305 * Umm, take care of errors if the page isn't up-to-date.
2306 * Try to re-read it _once_. We do this synchronously,
2307 * because there really aren't any performance issues here
2308 * and we need to check for errors.
2310 ClearPageError(page);
2311 error = mapping->a_ops->readpage(file, page);
2313 wait_on_page_locked(page);
2314 if (!PageUptodate(page))
2319 if (!error || error == AOP_TRUNCATED_PAGE)
2322 /* Things didn't work out. Return zero to tell the mm layer so. */
2323 shrink_readahead_size_eio(file, ra);
2324 return VM_FAULT_SIGBUS;
2326 EXPORT_SYMBOL(filemap_fault);
2328 void filemap_map_pages(struct vm_fault *vmf,
2329 pgoff_t start_pgoff, pgoff_t end_pgoff)
2331 struct radix_tree_iter iter;
2333 struct file *file = vmf->vma->vm_file;
2334 struct address_space *mapping = file->f_mapping;
2335 pgoff_t last_pgoff = start_pgoff;
2336 unsigned long max_idx;
2337 struct page *head, *page;
2340 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter,
2342 if (iter.index > end_pgoff)
2345 page = radix_tree_deref_slot(slot);
2346 if (unlikely(!page))
2348 if (radix_tree_exception(page)) {
2349 if (radix_tree_deref_retry(page)) {
2350 slot = radix_tree_iter_retry(&iter);
2356 head = compound_head(page);
2357 if (!page_cache_get_speculative(head))
2360 /* The page was split under us? */
2361 if (compound_head(page) != head) {
2366 /* Has the page moved? */
2367 if (unlikely(page != *slot)) {
2372 if (!PageUptodate(page) ||
2373 PageReadahead(page) ||
2376 if (!trylock_page(page))
2379 if (page->mapping != mapping || !PageUptodate(page))
2382 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2383 if (page->index >= max_idx)
2386 if (file->f_ra.mmap_miss > 0)
2387 file->f_ra.mmap_miss--;
2389 vmf->address += (iter.index - last_pgoff) << PAGE_SHIFT;
2391 vmf->pte += iter.index - last_pgoff;
2392 last_pgoff = iter.index;
2393 if (alloc_set_pte(vmf, NULL, page))
2402 /* Huge page is mapped? No need to proceed. */
2403 if (pmd_trans_huge(*vmf->pmd))
2405 if (iter.index == end_pgoff)
2410 EXPORT_SYMBOL(filemap_map_pages);
2412 int filemap_page_mkwrite(struct vm_fault *vmf)
2414 struct page *page = vmf->page;
2415 struct inode *inode = file_inode(vmf->vma->vm_file);
2416 int ret = VM_FAULT_LOCKED;
2418 sb_start_pagefault(inode->i_sb);
2419 file_update_time(vmf->vma->vm_file);
2421 if (page->mapping != inode->i_mapping) {
2423 ret = VM_FAULT_NOPAGE;
2427 * We mark the page dirty already here so that when freeze is in
2428 * progress, we are guaranteed that writeback during freezing will
2429 * see the dirty page and writeprotect it again.
2431 set_page_dirty(page);
2432 wait_for_stable_page(page);
2434 sb_end_pagefault(inode->i_sb);
2437 EXPORT_SYMBOL(filemap_page_mkwrite);
2439 const struct vm_operations_struct generic_file_vm_ops = {
2440 .fault = filemap_fault,
2441 .map_pages = filemap_map_pages,
2442 .page_mkwrite = filemap_page_mkwrite,
2445 /* This is used for a general mmap of a disk file */
2447 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2449 struct address_space *mapping = file->f_mapping;
2451 if (!mapping->a_ops->readpage)
2453 file_accessed(file);
2454 vma->vm_ops = &generic_file_vm_ops;
2459 * This is for filesystems which do not implement ->writepage.
2461 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2463 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2465 return generic_file_mmap(file, vma);
2468 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2472 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2476 #endif /* CONFIG_MMU */
2478 EXPORT_SYMBOL(generic_file_mmap);
2479 EXPORT_SYMBOL(generic_file_readonly_mmap);
2481 static struct page *wait_on_page_read(struct page *page)
2483 if (!IS_ERR(page)) {
2484 wait_on_page_locked(page);
2485 if (!PageUptodate(page)) {
2487 page = ERR_PTR(-EIO);
2493 static struct page *do_read_cache_page(struct address_space *mapping,
2495 int (*filler)(void *, struct page *),
2502 page = find_get_page(mapping, index);
2504 page = __page_cache_alloc(gfp | __GFP_COLD);
2506 return ERR_PTR(-ENOMEM);
2507 err = add_to_page_cache_lru(page, mapping, index, gfp);
2508 if (unlikely(err)) {
2512 /* Presumably ENOMEM for radix tree node */
2513 return ERR_PTR(err);
2517 err = filler(data, page);
2520 return ERR_PTR(err);
2523 page = wait_on_page_read(page);
2528 if (PageUptodate(page))
2532 * Page is not up to date and may be locked due one of the following
2533 * case a: Page is being filled and the page lock is held
2534 * case b: Read/write error clearing the page uptodate status
2535 * case c: Truncation in progress (page locked)
2536 * case d: Reclaim in progress
2538 * Case a, the page will be up to date when the page is unlocked.
2539 * There is no need to serialise on the page lock here as the page
2540 * is pinned so the lock gives no additional protection. Even if the
2541 * the page is truncated, the data is still valid if PageUptodate as
2542 * it's a race vs truncate race.
2543 * Case b, the page will not be up to date
2544 * Case c, the page may be truncated but in itself, the data may still
2545 * be valid after IO completes as it's a read vs truncate race. The
2546 * operation must restart if the page is not uptodate on unlock but
2547 * otherwise serialising on page lock to stabilise the mapping gives
2548 * no additional guarantees to the caller as the page lock is
2549 * released before return.
2550 * Case d, similar to truncation. If reclaim holds the page lock, it
2551 * will be a race with remove_mapping that determines if the mapping
2552 * is valid on unlock but otherwise the data is valid and there is
2553 * no need to serialise with page lock.
2555 * As the page lock gives no additional guarantee, we optimistically
2556 * wait on the page to be unlocked and check if it's up to date and
2557 * use the page if it is. Otherwise, the page lock is required to
2558 * distinguish between the different cases. The motivation is that we
2559 * avoid spurious serialisations and wakeups when multiple processes
2560 * wait on the same page for IO to complete.
2562 wait_on_page_locked(page);
2563 if (PageUptodate(page))
2566 /* Distinguish between all the cases under the safety of the lock */
2569 /* Case c or d, restart the operation */
2570 if (!page->mapping) {
2576 /* Someone else locked and filled the page in a very small window */
2577 if (PageUptodate(page)) {
2584 mark_page_accessed(page);
2589 * read_cache_page - read into page cache, fill it if needed
2590 * @mapping: the page's address_space
2591 * @index: the page index
2592 * @filler: function to perform the read
2593 * @data: first arg to filler(data, page) function, often left as NULL
2595 * Read into the page cache. If a page already exists, and PageUptodate() is
2596 * not set, try to fill the page and wait for it to become unlocked.
2598 * If the page does not get brought uptodate, return -EIO.
2600 struct page *read_cache_page(struct address_space *mapping,
2602 int (*filler)(void *, struct page *),
2605 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2607 EXPORT_SYMBOL(read_cache_page);
2610 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2611 * @mapping: the page's address_space
2612 * @index: the page index
2613 * @gfp: the page allocator flags to use if allocating
2615 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2616 * any new page allocations done using the specified allocation flags.
2618 * If the page does not get brought uptodate, return -EIO.
2620 struct page *read_cache_page_gfp(struct address_space *mapping,
2624 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2626 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2628 EXPORT_SYMBOL(read_cache_page_gfp);
2631 * Performs necessary checks before doing a write
2633 * Can adjust writing position or amount of bytes to write.
2634 * Returns appropriate error code that caller should return or
2635 * zero in case that write should be allowed.
2637 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2639 struct file *file = iocb->ki_filp;
2640 struct inode *inode = file->f_mapping->host;
2641 unsigned long limit = rlimit(RLIMIT_FSIZE);
2644 if (!iov_iter_count(from))
2647 /* FIXME: this is for backwards compatibility with 2.4 */
2648 if (iocb->ki_flags & IOCB_APPEND)
2649 iocb->ki_pos = i_size_read(inode);
2653 if (limit != RLIM_INFINITY) {
2654 if (iocb->ki_pos >= limit) {
2655 send_sig(SIGXFSZ, current, 0);
2658 iov_iter_truncate(from, limit - (unsigned long)pos);
2664 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2665 !(file->f_flags & O_LARGEFILE))) {
2666 if (pos >= MAX_NON_LFS)
2668 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2672 * Are we about to exceed the fs block limit ?
2674 * If we have written data it becomes a short write. If we have
2675 * exceeded without writing data we send a signal and return EFBIG.
2676 * Linus frestrict idea will clean these up nicely..
2678 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2681 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2682 return iov_iter_count(from);
2684 EXPORT_SYMBOL(generic_write_checks);
2686 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2687 loff_t pos, unsigned len, unsigned flags,
2688 struct page **pagep, void **fsdata)
2690 const struct address_space_operations *aops = mapping->a_ops;
2692 return aops->write_begin(file, mapping, pos, len, flags,
2695 EXPORT_SYMBOL(pagecache_write_begin);
2697 int pagecache_write_end(struct file *file, struct address_space *mapping,
2698 loff_t pos, unsigned len, unsigned copied,
2699 struct page *page, void *fsdata)
2701 const struct address_space_operations *aops = mapping->a_ops;
2703 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2705 EXPORT_SYMBOL(pagecache_write_end);
2708 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
2710 struct file *file = iocb->ki_filp;
2711 struct address_space *mapping = file->f_mapping;
2712 struct inode *inode = mapping->host;
2713 loff_t pos = iocb->ki_pos;
2718 write_len = iov_iter_count(from);
2719 end = (pos + write_len - 1) >> PAGE_SHIFT;
2721 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2726 * After a write we want buffered reads to be sure to go to disk to get
2727 * the new data. We invalidate clean cached page from the region we're
2728 * about to write. We do this *before* the write so that we can return
2729 * without clobbering -EIOCBQUEUED from ->direct_IO().
2731 written = invalidate_inode_pages2_range(mapping,
2732 pos >> PAGE_SHIFT, end);
2734 * If a page can not be invalidated, return 0 to fall back
2735 * to buffered write.
2738 if (written == -EBUSY)
2743 written = mapping->a_ops->direct_IO(iocb, from);
2746 * Finally, try again to invalidate clean pages which might have been
2747 * cached by non-direct readahead, or faulted in by get_user_pages()
2748 * if the source of the write was an mmap'ed region of the file
2749 * we're writing. Either one is a pretty crazy thing to do,
2750 * so we don't support it 100%. If this invalidation
2751 * fails, tough, the write still worked...
2753 invalidate_inode_pages2_range(mapping,
2754 pos >> PAGE_SHIFT, end);
2758 write_len -= written;
2759 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2760 i_size_write(inode, pos);
2761 mark_inode_dirty(inode);
2765 iov_iter_revert(from, write_len - iov_iter_count(from));
2769 EXPORT_SYMBOL(generic_file_direct_write);
2772 * Find or create a page at the given pagecache position. Return the locked
2773 * page. This function is specifically for buffered writes.
2775 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2776 pgoff_t index, unsigned flags)
2779 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
2781 if (flags & AOP_FLAG_NOFS)
2782 fgp_flags |= FGP_NOFS;
2784 page = pagecache_get_page(mapping, index, fgp_flags,
2785 mapping_gfp_mask(mapping));
2787 wait_for_stable_page(page);
2791 EXPORT_SYMBOL(grab_cache_page_write_begin);
2793 ssize_t generic_perform_write(struct file *file,
2794 struct iov_iter *i, loff_t pos)
2796 struct address_space *mapping = file->f_mapping;
2797 const struct address_space_operations *a_ops = mapping->a_ops;
2799 ssize_t written = 0;
2800 unsigned int flags = 0;
2804 unsigned long offset; /* Offset into pagecache page */
2805 unsigned long bytes; /* Bytes to write to page */
2806 size_t copied; /* Bytes copied from user */
2809 offset = (pos & (PAGE_SIZE - 1));
2810 bytes = min_t(unsigned long, PAGE_SIZE - offset,
2815 * Bring in the user page that we will copy from _first_.
2816 * Otherwise there's a nasty deadlock on copying from the
2817 * same page as we're writing to, without it being marked
2820 * Not only is this an optimisation, but it is also required
2821 * to check that the address is actually valid, when atomic
2822 * usercopies are used, below.
2824 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2829 if (fatal_signal_pending(current)) {
2834 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2836 if (unlikely(status < 0))
2839 if (mapping_writably_mapped(mapping))
2840 flush_dcache_page(page);
2842 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2843 flush_dcache_page(page);
2845 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2847 if (unlikely(status < 0))
2853 iov_iter_advance(i, copied);
2854 if (unlikely(copied == 0)) {
2856 * If we were unable to copy any data at all, we must
2857 * fall back to a single segment length write.
2859 * If we didn't fallback here, we could livelock
2860 * because not all segments in the iov can be copied at
2861 * once without a pagefault.
2863 bytes = min_t(unsigned long, PAGE_SIZE - offset,
2864 iov_iter_single_seg_count(i));
2870 balance_dirty_pages_ratelimited(mapping);
2871 } while (iov_iter_count(i));
2873 return written ? written : status;
2875 EXPORT_SYMBOL(generic_perform_write);
2878 * __generic_file_write_iter - write data to a file
2879 * @iocb: IO state structure (file, offset, etc.)
2880 * @from: iov_iter with data to write
2882 * This function does all the work needed for actually writing data to a
2883 * file. It does all basic checks, removes SUID from the file, updates
2884 * modification times and calls proper subroutines depending on whether we
2885 * do direct IO or a standard buffered write.
2887 * It expects i_mutex to be grabbed unless we work on a block device or similar
2888 * object which does not need locking at all.
2890 * This function does *not* take care of syncing data in case of O_SYNC write.
2891 * A caller has to handle it. This is mainly due to the fact that we want to
2892 * avoid syncing under i_mutex.
2894 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2896 struct file *file = iocb->ki_filp;
2897 struct address_space * mapping = file->f_mapping;
2898 struct inode *inode = mapping->host;
2899 ssize_t written = 0;
2903 /* We can write back this queue in page reclaim */
2904 current->backing_dev_info = inode_to_bdi(inode);
2905 err = file_remove_privs(file);
2909 err = file_update_time(file);
2913 if (iocb->ki_flags & IOCB_DIRECT) {
2914 loff_t pos, endbyte;
2916 written = generic_file_direct_write(iocb, from);
2918 * If the write stopped short of completing, fall back to
2919 * buffered writes. Some filesystems do this for writes to
2920 * holes, for example. For DAX files, a buffered write will
2921 * not succeed (even if it did, DAX does not handle dirty
2922 * page-cache pages correctly).
2924 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
2927 status = generic_perform_write(file, from, pos = iocb->ki_pos);
2929 * If generic_perform_write() returned a synchronous error
2930 * then we want to return the number of bytes which were
2931 * direct-written, or the error code if that was zero. Note
2932 * that this differs from normal direct-io semantics, which
2933 * will return -EFOO even if some bytes were written.
2935 if (unlikely(status < 0)) {
2940 * We need to ensure that the page cache pages are written to
2941 * disk and invalidated to preserve the expected O_DIRECT
2944 endbyte = pos + status - 1;
2945 err = filemap_write_and_wait_range(mapping, pos, endbyte);
2947 iocb->ki_pos = endbyte + 1;
2949 invalidate_mapping_pages(mapping,
2951 endbyte >> PAGE_SHIFT);
2954 * We don't know how much we wrote, so just return
2955 * the number of bytes which were direct-written
2959 written = generic_perform_write(file, from, iocb->ki_pos);
2960 if (likely(written > 0))
2961 iocb->ki_pos += written;
2964 current->backing_dev_info = NULL;
2965 return written ? written : err;
2967 EXPORT_SYMBOL(__generic_file_write_iter);
2970 * generic_file_write_iter - write data to a file
2971 * @iocb: IO state structure
2972 * @from: iov_iter with data to write
2974 * This is a wrapper around __generic_file_write_iter() to be used by most
2975 * filesystems. It takes care of syncing the file in case of O_SYNC file
2976 * and acquires i_mutex as needed.
2978 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2980 struct file *file = iocb->ki_filp;
2981 struct inode *inode = file->f_mapping->host;
2985 ret = generic_write_checks(iocb, from);
2987 ret = __generic_file_write_iter(iocb, from);
2988 inode_unlock(inode);
2991 ret = generic_write_sync(iocb, ret);
2994 EXPORT_SYMBOL(generic_file_write_iter);
2997 * try_to_release_page() - release old fs-specific metadata on a page
2999 * @page: the page which the kernel is trying to free
3000 * @gfp_mask: memory allocation flags (and I/O mode)
3002 * The address_space is to try to release any data against the page
3003 * (presumably at page->private). If the release was successful, return '1'.
3004 * Otherwise return zero.
3006 * This may also be called if PG_fscache is set on a page, indicating that the
3007 * page is known to the local caching routines.
3009 * The @gfp_mask argument specifies whether I/O may be performed to release
3010 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3013 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3015 struct address_space * const mapping = page->mapping;
3017 BUG_ON(!PageLocked(page));
3018 if (PageWriteback(page))
3021 if (mapping && mapping->a_ops->releasepage)
3022 return mapping->a_ops->releasepage(page, gfp_mask);
3023 return try_to_free_buffers(page);
3026 EXPORT_SYMBOL(try_to_release_page);