Linux 4.4.252
[linux/fpc-iii.git] / mm / filemap.c
blob3d0a0e409cbf5a1a7a76dea5292c8b1a7d3dc4ea
1 /*
2 * linux/mm/filemap.c
4 * Copyright (C) 1994-1999 Linus Torvalds
5 */
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)
12 #include <linux/export.h>
13 #include <linux/compiler.h>
14 #include <linux/fs.h>
15 #include <linux/uaccess.h>
16 #include <linux/capability.h>
17 #include <linux/kernel_stat.h>
18 #include <linux/gfp.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/mman.h>
22 #include <linux/pagemap.h>
23 #include <linux/file.h>
24 #include <linux/uio.h>
25 #include <linux/hash.h>
26 #include <linux/writeback.h>
27 #include <linux/backing-dev.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/security.h>
31 #include <linux/cpuset.h>
32 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
33 #include <linux/hugetlb.h>
34 #include <linux/memcontrol.h>
35 #include <linux/cleancache.h>
36 #include <linux/rmap.h>
37 #include "internal.h"
39 #define CREATE_TRACE_POINTS
40 #include <trace/events/filemap.h>
43 * FIXME: remove all knowledge of the buffer layer from the core VM
45 #include <linux/buffer_head.h> /* for try_to_free_buffers */
47 #include <asm/mman.h>
50 * Shared mappings implemented 30.11.1994. It's not fully working yet,
51 * though.
53 * Shared mappings now work. 15.8.1995 Bruno.
55 * finished 'unifying' the page and buffer cache and SMP-threaded the
56 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
58 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
62 * Lock ordering:
64 * ->i_mmap_rwsem (truncate_pagecache)
65 * ->private_lock (__free_pte->__set_page_dirty_buffers)
66 * ->swap_lock (exclusive_swap_page, others)
67 * ->mapping->tree_lock
69 * ->i_mutex
70 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
72 * ->mmap_sem
73 * ->i_mmap_rwsem
74 * ->page_table_lock or pte_lock (various, mainly in memory.c)
75 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
77 * ->mmap_sem
78 * ->lock_page (access_process_vm)
80 * ->i_mutex (generic_perform_write)
81 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
83 * bdi->wb.list_lock
84 * sb_lock (fs/fs-writeback.c)
85 * ->mapping->tree_lock (__sync_single_inode)
87 * ->i_mmap_rwsem
88 * ->anon_vma.lock (vma_adjust)
90 * ->anon_vma.lock
91 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
93 * ->page_table_lock or pte_lock
94 * ->swap_lock (try_to_unmap_one)
95 * ->private_lock (try_to_unmap_one)
96 * ->tree_lock (try_to_unmap_one)
97 * ->zone.lru_lock (follow_page->mark_page_accessed)
98 * ->zone.lru_lock (check_pte_range->isolate_lru_page)
99 * ->private_lock (page_remove_rmap->set_page_dirty)
100 * ->tree_lock (page_remove_rmap->set_page_dirty)
101 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
102 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
103 * ->memcg->move_lock (page_remove_rmap->mem_cgroup_begin_page_stat)
104 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
105 * ->inode->i_lock (zap_pte_range->set_page_dirty)
106 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
108 * ->i_mmap_rwsem
109 * ->tasklist_lock (memory_failure, collect_procs_ao)
112 static int page_cache_tree_insert(struct address_space *mapping,
113 struct page *page, void **shadowp)
115 struct radix_tree_node *node;
116 void **slot;
117 int error;
119 error = __radix_tree_create(&mapping->page_tree, page->index,
120 &node, &slot);
121 if (error)
122 return error;
123 if (*slot) {
124 void *p;
126 p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
127 if (!radix_tree_exceptional_entry(p))
128 return -EEXIST;
129 if (shadowp)
130 *shadowp = p;
131 mapping->nrshadows--;
132 if (node)
133 workingset_node_shadows_dec(node);
135 radix_tree_replace_slot(slot, page);
136 mapping->nrpages++;
137 if (node) {
138 workingset_node_pages_inc(node);
140 * Don't track node that contains actual pages.
142 * Avoid acquiring the list_lru lock if already
143 * untracked. The list_empty() test is safe as
144 * node->private_list is protected by
145 * mapping->tree_lock.
147 if (!list_empty(&node->private_list))
148 list_lru_del(&workingset_shadow_nodes,
149 &node->private_list);
151 return 0;
154 static void page_cache_tree_delete(struct address_space *mapping,
155 struct page *page, void *shadow)
157 struct radix_tree_node *node;
158 unsigned long index;
159 unsigned int offset;
160 unsigned int tag;
161 void **slot;
163 VM_BUG_ON(!PageLocked(page));
165 __radix_tree_lookup(&mapping->page_tree, page->index, &node, &slot);
167 if (!node) {
169 * We need a node to properly account shadow
170 * entries. Don't plant any without. XXX
172 shadow = NULL;
175 if (shadow) {
176 mapping->nrshadows++;
178 * Make sure the nrshadows update is committed before
179 * the nrpages update so that final truncate racing
180 * with reclaim does not see both counters 0 at the
181 * same time and miss a shadow entry.
183 smp_wmb();
185 mapping->nrpages--;
187 if (!node) {
188 /* Clear direct pointer tags in root node */
189 mapping->page_tree.gfp_mask &= __GFP_BITS_MASK;
190 radix_tree_replace_slot(slot, shadow);
191 return;
194 /* Clear tree tags for the removed page */
195 index = page->index;
196 offset = index & RADIX_TREE_MAP_MASK;
197 for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
198 if (test_bit(offset, node->tags[tag]))
199 radix_tree_tag_clear(&mapping->page_tree, index, tag);
202 /* Delete page, swap shadow entry */
203 radix_tree_replace_slot(slot, shadow);
204 workingset_node_pages_dec(node);
205 if (shadow)
206 workingset_node_shadows_inc(node);
207 else
208 if (__radix_tree_delete_node(&mapping->page_tree, node))
209 return;
212 * Track node that only contains shadow entries.
214 * Avoid acquiring the list_lru lock if already tracked. The
215 * list_empty() test is safe as node->private_list is
216 * protected by mapping->tree_lock.
218 if (!workingset_node_pages(node) &&
219 list_empty(&node->private_list)) {
220 node->private_data = mapping;
221 list_lru_add(&workingset_shadow_nodes, &node->private_list);
226 * Delete a page from the page cache and free it. Caller has to make
227 * sure the page is locked and that nobody else uses it - or that usage
228 * is safe. The caller must hold the mapping's tree_lock and
229 * mem_cgroup_begin_page_stat().
231 void __delete_from_page_cache(struct page *page, void *shadow,
232 struct mem_cgroup *memcg)
234 struct address_space *mapping = page->mapping;
236 trace_mm_filemap_delete_from_page_cache(page);
238 * if we're uptodate, flush out into the cleancache, otherwise
239 * invalidate any existing cleancache entries. We can't leave
240 * stale data around in the cleancache once our page is gone
242 if (PageUptodate(page) && PageMappedToDisk(page))
243 cleancache_put_page(page);
244 else
245 cleancache_invalidate_page(mapping, page);
247 page_cache_tree_delete(mapping, page, shadow);
249 page->mapping = NULL;
250 /* Leave page->index set: truncation lookup relies upon it */
252 /* hugetlb pages do not participate in page cache accounting. */
253 if (!PageHuge(page))
254 __dec_zone_page_state(page, NR_FILE_PAGES);
255 if (PageSwapBacked(page))
256 __dec_zone_page_state(page, NR_SHMEM);
257 BUG_ON(page_mapped(page));
260 * At this point page must be either written or cleaned by truncate.
261 * Dirty page here signals a bug and loss of unwritten data.
263 * This fixes dirty accounting after removing the page entirely but
264 * leaves PageDirty set: it has no effect for truncated page and
265 * anyway will be cleared before returning page into buddy allocator.
267 if (WARN_ON_ONCE(PageDirty(page)))
268 account_page_cleaned(page, mapping, memcg,
269 inode_to_wb(mapping->host));
273 * delete_from_page_cache - delete page from page cache
274 * @page: the page which the kernel is trying to remove from page cache
276 * This must be called only on pages that have been verified to be in the page
277 * cache and locked. It will never put the page into the free list, the caller
278 * has a reference on the page.
280 void delete_from_page_cache(struct page *page)
282 struct address_space *mapping = page->mapping;
283 struct mem_cgroup *memcg;
284 unsigned long flags;
286 void (*freepage)(struct page *);
288 BUG_ON(!PageLocked(page));
290 freepage = mapping->a_ops->freepage;
292 memcg = mem_cgroup_begin_page_stat(page);
293 spin_lock_irqsave(&mapping->tree_lock, flags);
294 __delete_from_page_cache(page, NULL, memcg);
295 spin_unlock_irqrestore(&mapping->tree_lock, flags);
296 mem_cgroup_end_page_stat(memcg);
298 if (freepage)
299 freepage(page);
300 page_cache_release(page);
302 EXPORT_SYMBOL(delete_from_page_cache);
304 static int filemap_check_errors(struct address_space *mapping)
306 int ret = 0;
307 /* Check for outstanding write errors */
308 if (test_bit(AS_ENOSPC, &mapping->flags) &&
309 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
310 ret = -ENOSPC;
311 if (test_bit(AS_EIO, &mapping->flags) &&
312 test_and_clear_bit(AS_EIO, &mapping->flags))
313 ret = -EIO;
314 return ret;
318 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
319 * @mapping: address space structure to write
320 * @start: offset in bytes where the range starts
321 * @end: offset in bytes where the range ends (inclusive)
322 * @sync_mode: enable synchronous operation
324 * Start writeback against all of a mapping's dirty pages that lie
325 * within the byte offsets <start, end> inclusive.
327 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
328 * opposed to a regular memory cleansing writeback. The difference between
329 * these two operations is that if a dirty page/buffer is encountered, it must
330 * be waited upon, and not just skipped over.
332 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
333 loff_t end, int sync_mode)
335 int ret;
336 struct writeback_control wbc = {
337 .sync_mode = sync_mode,
338 .nr_to_write = LONG_MAX,
339 .range_start = start,
340 .range_end = end,
343 if (!mapping_cap_writeback_dirty(mapping) ||
344 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
345 return 0;
347 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
348 ret = do_writepages(mapping, &wbc);
349 wbc_detach_inode(&wbc);
350 return ret;
353 static inline int __filemap_fdatawrite(struct address_space *mapping,
354 int sync_mode)
356 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
359 int filemap_fdatawrite(struct address_space *mapping)
361 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
363 EXPORT_SYMBOL(filemap_fdatawrite);
365 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
366 loff_t end)
368 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
370 EXPORT_SYMBOL(filemap_fdatawrite_range);
373 * filemap_flush - mostly a non-blocking flush
374 * @mapping: target address_space
376 * This is a mostly non-blocking flush. Not suitable for data-integrity
377 * purposes - I/O may not be started against all dirty pages.
379 int filemap_flush(struct address_space *mapping)
381 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
383 EXPORT_SYMBOL(filemap_flush);
385 static int __filemap_fdatawait_range(struct address_space *mapping,
386 loff_t start_byte, loff_t end_byte)
388 pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
389 pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
390 struct pagevec pvec;
391 int nr_pages;
392 int ret = 0;
394 if (end_byte < start_byte)
395 goto out;
397 pagevec_init(&pvec, 0);
398 while ((index <= end) &&
399 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
400 PAGECACHE_TAG_WRITEBACK,
401 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
402 unsigned i;
404 for (i = 0; i < nr_pages; i++) {
405 struct page *page = pvec.pages[i];
407 /* until radix tree lookup accepts end_index */
408 if (page->index > end)
409 continue;
411 wait_on_page_writeback(page);
412 if (TestClearPageError(page))
413 ret = -EIO;
415 pagevec_release(&pvec);
416 cond_resched();
418 out:
419 return ret;
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,
437 loff_t end_byte)
439 int ret, ret2;
441 ret = __filemap_fdatawait_range(mapping, start_byte, end_byte);
442 ret2 = filemap_check_errors(mapping);
443 if (!ret)
444 ret = ret2;
446 return ret;
448 EXPORT_SYMBOL(filemap_fdatawait_range);
451 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
452 * @mapping: address space structure to wait for
454 * Walk the list of under-writeback pages of the given address space
455 * and wait for all of them. Unlike filemap_fdatawait(), this function
456 * does not clear error status of the address space.
458 * Use this function if callers don't handle errors themselves. Expected
459 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
460 * fsfreeze(8)
462 void filemap_fdatawait_keep_errors(struct address_space *mapping)
464 loff_t i_size = i_size_read(mapping->host);
466 if (i_size == 0)
467 return;
469 __filemap_fdatawait_range(mapping, 0, i_size - 1);
473 * filemap_fdatawait - wait for all under-writeback pages to complete
474 * @mapping: address space structure to wait for
476 * Walk the list of under-writeback pages of the given address space
477 * and wait for all of them. Check error status of the address space
478 * and return it.
480 * Since the error status of the address space is cleared by this function,
481 * callers are responsible for checking the return value and handling and/or
482 * reporting the error.
484 int filemap_fdatawait(struct address_space *mapping)
486 loff_t i_size = i_size_read(mapping->host);
488 if (i_size == 0)
489 return 0;
491 return filemap_fdatawait_range(mapping, 0, i_size - 1);
493 EXPORT_SYMBOL(filemap_fdatawait);
495 int filemap_write_and_wait(struct address_space *mapping)
497 int err = 0;
499 if (mapping->nrpages) {
500 err = filemap_fdatawrite(mapping);
502 * Even if the above returned error, the pages may be
503 * written partially (e.g. -ENOSPC), so we wait for it.
504 * But the -EIO is special case, it may indicate the worst
505 * thing (e.g. bug) happened, so we avoid waiting for it.
507 if (err != -EIO) {
508 int err2 = filemap_fdatawait(mapping);
509 if (!err)
510 err = err2;
512 } else {
513 err = filemap_check_errors(mapping);
515 return err;
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)
533 int err = 0;
535 if (mapping->nrpages) {
536 err = __filemap_fdatawrite_range(mapping, lstart, lend,
537 WB_SYNC_ALL);
538 /* See comment of filemap_write_and_wait() */
539 if (err != -EIO) {
540 int err2 = filemap_fdatawait_range(mapping,
541 lstart, lend);
542 if (!err)
543 err = err2;
545 } else {
546 err = filemap_check_errors(mapping);
548 return err;
550 EXPORT_SYMBOL(filemap_write_and_wait_range);
553 * replace_page_cache_page - replace a pagecache page with a new one
554 * @old: page to be replaced
555 * @new: page to replace with
556 * @gfp_mask: allocation mode
558 * This function replaces a page in the pagecache with a new one. On
559 * success it acquires the pagecache reference for the new page and
560 * drops it for the old page. Both the old and new pages must be
561 * locked. This function does not add the new page to the LRU, the
562 * caller must do that.
564 * The remove + add is atomic. The only way this function can fail is
565 * memory allocation failure.
567 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
569 int error;
571 VM_BUG_ON_PAGE(!PageLocked(old), old);
572 VM_BUG_ON_PAGE(!PageLocked(new), new);
573 VM_BUG_ON_PAGE(new->mapping, new);
575 error = radix_tree_preload(gfp_mask & GFP_RECLAIM_MASK);
576 if (!error) {
577 struct address_space *mapping = old->mapping;
578 void (*freepage)(struct page *);
579 struct mem_cgroup *memcg;
580 unsigned long flags;
582 pgoff_t offset = old->index;
583 freepage = mapping->a_ops->freepage;
585 page_cache_get(new);
586 new->mapping = mapping;
587 new->index = offset;
589 memcg = mem_cgroup_begin_page_stat(old);
590 spin_lock_irqsave(&mapping->tree_lock, flags);
591 __delete_from_page_cache(old, NULL, memcg);
592 error = page_cache_tree_insert(mapping, new, NULL);
593 BUG_ON(error);
596 * hugetlb pages do not participate in page cache accounting.
598 if (!PageHuge(new))
599 __inc_zone_page_state(new, NR_FILE_PAGES);
600 if (PageSwapBacked(new))
601 __inc_zone_page_state(new, NR_SHMEM);
602 spin_unlock_irqrestore(&mapping->tree_lock, flags);
603 mem_cgroup_end_page_stat(memcg);
604 mem_cgroup_replace_page(old, new);
605 radix_tree_preload_end();
606 if (freepage)
607 freepage(old);
608 page_cache_release(old);
611 return error;
613 EXPORT_SYMBOL_GPL(replace_page_cache_page);
615 static int __add_to_page_cache_locked(struct page *page,
616 struct address_space *mapping,
617 pgoff_t offset, gfp_t gfp_mask,
618 void **shadowp)
620 int huge = PageHuge(page);
621 struct mem_cgroup *memcg;
622 int error;
624 VM_BUG_ON_PAGE(!PageLocked(page), page);
625 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
627 if (!huge) {
628 error = mem_cgroup_try_charge(page, current->mm,
629 gfp_mask, &memcg);
630 if (error)
631 return error;
634 error = radix_tree_maybe_preload(gfp_mask & GFP_RECLAIM_MASK);
635 if (error) {
636 if (!huge)
637 mem_cgroup_cancel_charge(page, memcg);
638 return error;
641 page_cache_get(page);
642 page->mapping = mapping;
643 page->index = offset;
645 spin_lock_irq(&mapping->tree_lock);
646 error = page_cache_tree_insert(mapping, page, shadowp);
647 radix_tree_preload_end();
648 if (unlikely(error))
649 goto err_insert;
651 /* hugetlb pages do not participate in page cache accounting. */
652 if (!huge)
653 __inc_zone_page_state(page, NR_FILE_PAGES);
654 spin_unlock_irq(&mapping->tree_lock);
655 if (!huge)
656 mem_cgroup_commit_charge(page, memcg, false);
657 trace_mm_filemap_add_to_page_cache(page);
658 return 0;
659 err_insert:
660 page->mapping = NULL;
661 /* Leave page->index set: truncation relies upon it */
662 spin_unlock_irq(&mapping->tree_lock);
663 if (!huge)
664 mem_cgroup_cancel_charge(page, memcg);
665 page_cache_release(page);
666 return error;
670 * add_to_page_cache_locked - add a locked page to the pagecache
671 * @page: page to add
672 * @mapping: the page's address_space
673 * @offset: page index
674 * @gfp_mask: page allocation mode
676 * This function is used to add a page to the pagecache. It must be locked.
677 * This function does not add the page to the LRU. The caller must do that.
679 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
680 pgoff_t offset, gfp_t gfp_mask)
682 return __add_to_page_cache_locked(page, mapping, offset,
683 gfp_mask, NULL);
685 EXPORT_SYMBOL(add_to_page_cache_locked);
687 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
688 pgoff_t offset, gfp_t gfp_mask)
690 void *shadow = NULL;
691 int ret;
693 __set_page_locked(page);
694 ret = __add_to_page_cache_locked(page, mapping, offset,
695 gfp_mask, &shadow);
696 if (unlikely(ret))
697 __clear_page_locked(page);
698 else {
700 * The page might have been evicted from cache only
701 * recently, in which case it should be activated like
702 * any other repeatedly accessed page.
704 if (shadow && workingset_refault(shadow)) {
705 SetPageActive(page);
706 workingset_activation(page);
707 } else
708 ClearPageActive(page);
709 lru_cache_add(page);
711 return ret;
713 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
715 #ifdef CONFIG_NUMA
716 struct page *__page_cache_alloc(gfp_t gfp)
718 int n;
719 struct page *page;
721 if (cpuset_do_page_mem_spread()) {
722 unsigned int cpuset_mems_cookie;
723 do {
724 cpuset_mems_cookie = read_mems_allowed_begin();
725 n = cpuset_mem_spread_node();
726 page = __alloc_pages_node(n, gfp, 0);
727 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
729 return page;
731 return alloc_pages(gfp, 0);
733 EXPORT_SYMBOL(__page_cache_alloc);
734 #endif
737 * In order to wait for pages to become available there must be
738 * waitqueues associated with pages. By using a hash table of
739 * waitqueues where the bucket discipline is to maintain all
740 * waiters on the same queue and wake all when any of the pages
741 * become available, and for the woken contexts to check to be
742 * sure the appropriate page became available, this saves space
743 * at a cost of "thundering herd" phenomena during rare hash
744 * collisions.
746 wait_queue_head_t *page_waitqueue(struct page *page)
748 const struct zone *zone = page_zone(page);
750 return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
752 EXPORT_SYMBOL(page_waitqueue);
754 void wait_on_page_bit(struct page *page, int bit_nr)
756 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
758 if (test_bit(bit_nr, &page->flags))
759 __wait_on_bit(page_waitqueue(page), &wait, bit_wait_io,
760 TASK_UNINTERRUPTIBLE);
762 EXPORT_SYMBOL(wait_on_page_bit);
764 int wait_on_page_bit_killable(struct page *page, int bit_nr)
766 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
768 if (!test_bit(bit_nr, &page->flags))
769 return 0;
771 return __wait_on_bit(page_waitqueue(page), &wait,
772 bit_wait_io, TASK_KILLABLE);
775 int wait_on_page_bit_killable_timeout(struct page *page,
776 int bit_nr, unsigned long timeout)
778 DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
780 wait.key.timeout = jiffies + timeout;
781 if (!test_bit(bit_nr, &page->flags))
782 return 0;
783 return __wait_on_bit(page_waitqueue(page), &wait,
784 bit_wait_io_timeout, TASK_KILLABLE);
786 EXPORT_SYMBOL_GPL(wait_on_page_bit_killable_timeout);
789 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
790 * @page: Page defining the wait queue of interest
791 * @waiter: Waiter to add to the queue
793 * Add an arbitrary @waiter to the wait queue for the nominated @page.
795 void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
797 wait_queue_head_t *q = page_waitqueue(page);
798 unsigned long flags;
800 spin_lock_irqsave(&q->lock, flags);
801 __add_wait_queue(q, waiter);
802 spin_unlock_irqrestore(&q->lock, flags);
804 EXPORT_SYMBOL_GPL(add_page_wait_queue);
807 * unlock_page - unlock a locked page
808 * @page: the page
810 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
811 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
812 * mechanism between PageLocked pages and PageWriteback pages is shared.
813 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
815 * The mb is necessary to enforce ordering between the clear_bit and the read
816 * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
818 void unlock_page(struct page *page)
820 VM_BUG_ON_PAGE(!PageLocked(page), page);
821 clear_bit_unlock(PG_locked, &page->flags);
822 smp_mb__after_atomic();
823 wake_up_page(page, PG_locked);
825 EXPORT_SYMBOL(unlock_page);
828 * end_page_writeback - end writeback against a page
829 * @page: the page
831 void end_page_writeback(struct page *page)
834 * TestClearPageReclaim could be used here but it is an atomic
835 * operation and overkill in this particular case. Failing to
836 * shuffle a page marked for immediate reclaim is too mild to
837 * justify taking an atomic operation penalty at the end of
838 * ever page writeback.
840 if (PageReclaim(page)) {
841 ClearPageReclaim(page);
842 rotate_reclaimable_page(page);
845 if (!test_clear_page_writeback(page))
846 BUG();
848 smp_mb__after_atomic();
849 wake_up_page(page, PG_writeback);
851 EXPORT_SYMBOL(end_page_writeback);
854 * After completing I/O on a page, call this routine to update the page
855 * flags appropriately
857 void page_endio(struct page *page, int rw, int err)
859 if (rw == READ) {
860 if (!err) {
861 SetPageUptodate(page);
862 } else {
863 ClearPageUptodate(page);
864 SetPageError(page);
866 unlock_page(page);
867 } else { /* rw == WRITE */
868 if (err) {
869 struct address_space *mapping;
871 SetPageError(page);
872 mapping = page_mapping(page);
873 if (mapping)
874 mapping_set_error(mapping, err);
876 end_page_writeback(page);
879 EXPORT_SYMBOL_GPL(page_endio);
882 * __lock_page - get a lock on the page, assuming we need to sleep to get it
883 * @page: the page to lock
885 void __lock_page(struct page *page)
887 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
889 __wait_on_bit_lock(page_waitqueue(page), &wait, bit_wait_io,
890 TASK_UNINTERRUPTIBLE);
892 EXPORT_SYMBOL(__lock_page);
894 int __lock_page_killable(struct page *page)
896 DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
898 return __wait_on_bit_lock(page_waitqueue(page), &wait,
899 bit_wait_io, TASK_KILLABLE);
901 EXPORT_SYMBOL_GPL(__lock_page_killable);
904 * Return values:
905 * 1 - page is locked; mmap_sem is still held.
906 * 0 - page is not locked.
907 * mmap_sem has been released (up_read()), unless flags had both
908 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
909 * which case mmap_sem is still held.
911 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
912 * with the page locked and the mmap_sem unperturbed.
914 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
915 unsigned int flags)
917 if (flags & FAULT_FLAG_ALLOW_RETRY) {
919 * CAUTION! In this case, mmap_sem is not released
920 * even though return 0.
922 if (flags & FAULT_FLAG_RETRY_NOWAIT)
923 return 0;
925 up_read(&mm->mmap_sem);
926 if (flags & FAULT_FLAG_KILLABLE)
927 wait_on_page_locked_killable(page);
928 else
929 wait_on_page_locked(page);
930 return 0;
931 } else {
932 if (flags & FAULT_FLAG_KILLABLE) {
933 int ret;
935 ret = __lock_page_killable(page);
936 if (ret) {
937 up_read(&mm->mmap_sem);
938 return 0;
940 } else
941 __lock_page(page);
942 return 1;
947 * page_cache_next_hole - find the next hole (not-present entry)
948 * @mapping: mapping
949 * @index: index
950 * @max_scan: maximum range to search
952 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
953 * lowest indexed hole.
955 * Returns: the index of the hole if found, otherwise returns an index
956 * outside of the set specified (in which case 'return - index >=
957 * max_scan' will be true). In rare cases of index wrap-around, 0 will
958 * be returned.
960 * page_cache_next_hole may be called under rcu_read_lock. However,
961 * like radix_tree_gang_lookup, this will not atomically search a
962 * snapshot of the tree at a single point in time. For example, if a
963 * hole is created at index 5, then subsequently a hole is created at
964 * index 10, page_cache_next_hole covering both indexes may return 10
965 * if called under rcu_read_lock.
967 pgoff_t page_cache_next_hole(struct address_space *mapping,
968 pgoff_t index, unsigned long max_scan)
970 unsigned long i;
972 for (i = 0; i < max_scan; i++) {
973 struct page *page;
975 page = radix_tree_lookup(&mapping->page_tree, index);
976 if (!page || radix_tree_exceptional_entry(page))
977 break;
978 index++;
979 if (index == 0)
980 break;
983 return index;
985 EXPORT_SYMBOL(page_cache_next_hole);
988 * page_cache_prev_hole - find the prev hole (not-present entry)
989 * @mapping: mapping
990 * @index: index
991 * @max_scan: maximum range to search
993 * Search backwards in the range [max(index-max_scan+1, 0), index] for
994 * the first hole.
996 * Returns: the index of the hole if found, otherwise returns an index
997 * outside of the set specified (in which case 'index - return >=
998 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
999 * will be returned.
1001 * page_cache_prev_hole may be called under rcu_read_lock. However,
1002 * like radix_tree_gang_lookup, this will not atomically search a
1003 * snapshot of the tree at a single point in time. For example, if a
1004 * hole is created at index 10, then subsequently a hole is created at
1005 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1006 * called under rcu_read_lock.
1008 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1009 pgoff_t index, unsigned long max_scan)
1011 unsigned long i;
1013 for (i = 0; i < max_scan; i++) {
1014 struct page *page;
1016 page = radix_tree_lookup(&mapping->page_tree, index);
1017 if (!page || radix_tree_exceptional_entry(page))
1018 break;
1019 index--;
1020 if (index == ULONG_MAX)
1021 break;
1024 return index;
1026 EXPORT_SYMBOL(page_cache_prev_hole);
1029 * find_get_entry - find and get a page cache entry
1030 * @mapping: the address_space to search
1031 * @offset: the page cache index
1033 * Looks up the page cache slot at @mapping & @offset. If there is a
1034 * page cache page, it is returned with an increased refcount.
1036 * If the slot holds a shadow entry of a previously evicted page, or a
1037 * swap entry from shmem/tmpfs, it is returned.
1039 * Otherwise, %NULL is returned.
1041 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1043 void **pagep;
1044 struct page *page;
1046 rcu_read_lock();
1047 repeat:
1048 page = NULL;
1049 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1050 if (pagep) {
1051 page = radix_tree_deref_slot(pagep);
1052 if (unlikely(!page))
1053 goto out;
1054 if (radix_tree_exception(page)) {
1055 if (radix_tree_deref_retry(page))
1056 goto repeat;
1058 * A shadow entry of a recently evicted page,
1059 * or a swap entry from shmem/tmpfs. Return
1060 * it without attempting to raise page count.
1062 goto out;
1064 if (!page_cache_get_speculative(page))
1065 goto repeat;
1068 * Has the page moved?
1069 * This is part of the lockless pagecache protocol. See
1070 * include/linux/pagemap.h for details.
1072 if (unlikely(page != *pagep)) {
1073 page_cache_release(page);
1074 goto repeat;
1077 out:
1078 rcu_read_unlock();
1080 return page;
1082 EXPORT_SYMBOL(find_get_entry);
1085 * find_lock_entry - locate, pin and lock a page cache entry
1086 * @mapping: the address_space to search
1087 * @offset: the page cache index
1089 * Looks up the page cache slot at @mapping & @offset. If there is a
1090 * page cache page, it is returned locked and with an increased
1091 * refcount.
1093 * If the slot holds a shadow entry of a previously evicted page, or a
1094 * swap entry from shmem/tmpfs, it is returned.
1096 * Otherwise, %NULL is returned.
1098 * find_lock_entry() may sleep.
1100 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1102 struct page *page;
1104 repeat:
1105 page = find_get_entry(mapping, offset);
1106 if (page && !radix_tree_exception(page)) {
1107 lock_page(page);
1108 /* Has the page been truncated? */
1109 if (unlikely(page->mapping != mapping)) {
1110 unlock_page(page);
1111 page_cache_release(page);
1112 goto repeat;
1114 VM_BUG_ON_PAGE(page->index != offset, page);
1116 return page;
1118 EXPORT_SYMBOL(find_lock_entry);
1121 * pagecache_get_page - find and get a page reference
1122 * @mapping: the address_space to search
1123 * @offset: the page index
1124 * @fgp_flags: PCG flags
1125 * @gfp_mask: gfp mask to use for the page cache data page allocation
1127 * Looks up the page cache slot at @mapping & @offset.
1129 * PCG flags modify how the page is returned.
1131 * FGP_ACCESSED: the page will be marked accessed
1132 * FGP_LOCK: Page is return locked
1133 * FGP_CREAT: If page is not present then a new page is allocated using
1134 * @gfp_mask and added to the page cache and the VM's LRU
1135 * list. The page is returned locked and with an increased
1136 * refcount. Otherwise, %NULL is returned.
1138 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1139 * if the GFP flags specified for FGP_CREAT are atomic.
1141 * If there is a page cache page, it is returned with an increased refcount.
1143 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1144 int fgp_flags, gfp_t gfp_mask)
1146 struct page *page;
1148 repeat:
1149 page = find_get_entry(mapping, offset);
1150 if (radix_tree_exceptional_entry(page))
1151 page = NULL;
1152 if (!page)
1153 goto no_page;
1155 if (fgp_flags & FGP_LOCK) {
1156 if (fgp_flags & FGP_NOWAIT) {
1157 if (!trylock_page(page)) {
1158 page_cache_release(page);
1159 return NULL;
1161 } else {
1162 lock_page(page);
1165 /* Has the page been truncated? */
1166 if (unlikely(page->mapping != mapping)) {
1167 unlock_page(page);
1168 page_cache_release(page);
1169 goto repeat;
1171 VM_BUG_ON_PAGE(page->index != offset, page);
1174 if (page && (fgp_flags & FGP_ACCESSED))
1175 mark_page_accessed(page);
1177 no_page:
1178 if (!page && (fgp_flags & FGP_CREAT)) {
1179 int err;
1180 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1181 gfp_mask |= __GFP_WRITE;
1182 if (fgp_flags & FGP_NOFS)
1183 gfp_mask &= ~__GFP_FS;
1185 page = __page_cache_alloc(gfp_mask);
1186 if (!page)
1187 return NULL;
1189 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1190 fgp_flags |= FGP_LOCK;
1192 /* Init accessed so avoid atomic mark_page_accessed later */
1193 if (fgp_flags & FGP_ACCESSED)
1194 __SetPageReferenced(page);
1196 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1197 if (unlikely(err)) {
1198 page_cache_release(page);
1199 page = NULL;
1200 if (err == -EEXIST)
1201 goto repeat;
1205 return page;
1207 EXPORT_SYMBOL(pagecache_get_page);
1210 * find_get_entries - gang pagecache lookup
1211 * @mapping: The address_space to search
1212 * @start: The starting page cache index
1213 * @nr_entries: The maximum number of entries
1214 * @entries: Where the resulting entries are placed
1215 * @indices: The cache indices corresponding to the entries in @entries
1217 * find_get_entries() will search for and return a group of up to
1218 * @nr_entries entries in the mapping. The entries are placed at
1219 * @entries. find_get_entries() takes a reference against any actual
1220 * pages it returns.
1222 * The search returns a group of mapping-contiguous page cache entries
1223 * with ascending indexes. There may be holes in the indices due to
1224 * not-present pages.
1226 * Any shadow entries of evicted pages, or swap entries from
1227 * shmem/tmpfs, are included in the returned array.
1229 * find_get_entries() returns the number of pages and shadow entries
1230 * which were found.
1232 unsigned find_get_entries(struct address_space *mapping,
1233 pgoff_t start, unsigned int nr_entries,
1234 struct page **entries, pgoff_t *indices)
1236 void **slot;
1237 unsigned int ret = 0;
1238 struct radix_tree_iter iter;
1240 if (!nr_entries)
1241 return 0;
1243 rcu_read_lock();
1244 restart:
1245 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1246 struct page *page;
1247 repeat:
1248 page = radix_tree_deref_slot(slot);
1249 if (unlikely(!page))
1250 continue;
1251 if (radix_tree_exception(page)) {
1252 if (radix_tree_deref_retry(page))
1253 goto restart;
1255 * A shadow entry of a recently evicted page,
1256 * or a swap entry from shmem/tmpfs. Return
1257 * it without attempting to raise page count.
1259 goto export;
1261 if (!page_cache_get_speculative(page))
1262 goto repeat;
1264 /* Has the page moved? */
1265 if (unlikely(page != *slot)) {
1266 page_cache_release(page);
1267 goto repeat;
1269 export:
1270 indices[ret] = iter.index;
1271 entries[ret] = page;
1272 if (++ret == nr_entries)
1273 break;
1275 rcu_read_unlock();
1276 return ret;
1280 * find_get_pages - gang pagecache lookup
1281 * @mapping: The address_space to search
1282 * @start: The starting page index
1283 * @nr_pages: The maximum number of pages
1284 * @pages: Where the resulting pages are placed
1286 * find_get_pages() will search for and return a group of up to
1287 * @nr_pages pages in the mapping. The pages are placed at @pages.
1288 * find_get_pages() takes a reference against the returned pages.
1290 * The search returns a group of mapping-contiguous pages with ascending
1291 * indexes. There may be holes in the indices due to not-present pages.
1293 * find_get_pages() returns the number of pages which were found.
1295 unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
1296 unsigned int nr_pages, struct page **pages)
1298 struct radix_tree_iter iter;
1299 void **slot;
1300 unsigned ret = 0;
1302 if (unlikely(!nr_pages))
1303 return 0;
1305 rcu_read_lock();
1306 restart:
1307 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1308 struct page *page;
1309 repeat:
1310 page = radix_tree_deref_slot(slot);
1311 if (unlikely(!page))
1312 continue;
1314 if (radix_tree_exception(page)) {
1315 if (radix_tree_deref_retry(page)) {
1317 * Transient condition which can only trigger
1318 * when entry at index 0 moves out of or back
1319 * to root: none yet gotten, safe to restart.
1321 WARN_ON(iter.index);
1322 goto restart;
1325 * A shadow entry of a recently evicted page,
1326 * or a swap entry from shmem/tmpfs. Skip
1327 * over it.
1329 continue;
1332 if (!page_cache_get_speculative(page))
1333 goto repeat;
1335 /* Has the page moved? */
1336 if (unlikely(page != *slot)) {
1337 page_cache_release(page);
1338 goto repeat;
1341 pages[ret] = page;
1342 if (++ret == nr_pages)
1343 break;
1346 rcu_read_unlock();
1347 return ret;
1351 * find_get_pages_contig - gang contiguous pagecache lookup
1352 * @mapping: The address_space to search
1353 * @index: The starting page index
1354 * @nr_pages: The maximum number of pages
1355 * @pages: Where the resulting pages are placed
1357 * find_get_pages_contig() works exactly like find_get_pages(), except
1358 * that the returned number of pages are guaranteed to be contiguous.
1360 * find_get_pages_contig() returns the number of pages which were found.
1362 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1363 unsigned int nr_pages, struct page **pages)
1365 struct radix_tree_iter iter;
1366 void **slot;
1367 unsigned int ret = 0;
1369 if (unlikely(!nr_pages))
1370 return 0;
1372 rcu_read_lock();
1373 restart:
1374 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1375 struct page *page;
1376 repeat:
1377 page = radix_tree_deref_slot(slot);
1378 /* The hole, there no reason to continue */
1379 if (unlikely(!page))
1380 break;
1382 if (radix_tree_exception(page)) {
1383 if (radix_tree_deref_retry(page)) {
1385 * Transient condition which can only trigger
1386 * when entry at index 0 moves out of or back
1387 * to root: none yet gotten, safe to restart.
1389 goto restart;
1392 * A shadow entry of a recently evicted page,
1393 * or a swap entry from shmem/tmpfs. Stop
1394 * looking for contiguous pages.
1396 break;
1399 if (!page_cache_get_speculative(page))
1400 goto repeat;
1402 /* Has the page moved? */
1403 if (unlikely(page != *slot)) {
1404 page_cache_release(page);
1405 goto repeat;
1409 * must check mapping and index after taking the ref.
1410 * otherwise we can get both false positives and false
1411 * negatives, which is just confusing to the caller.
1413 if (page->mapping == NULL || page->index != iter.index) {
1414 page_cache_release(page);
1415 break;
1418 pages[ret] = page;
1419 if (++ret == nr_pages)
1420 break;
1422 rcu_read_unlock();
1423 return ret;
1425 EXPORT_SYMBOL(find_get_pages_contig);
1428 * find_get_pages_tag - find and return pages that match @tag
1429 * @mapping: the address_space to search
1430 * @index: the starting page index
1431 * @tag: the tag index
1432 * @nr_pages: the maximum number of pages
1433 * @pages: where the resulting pages are placed
1435 * Like find_get_pages, except we only return pages which are tagged with
1436 * @tag. We update @index to index the next page for the traversal.
1438 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1439 int tag, unsigned int nr_pages, struct page **pages)
1441 struct radix_tree_iter iter;
1442 void **slot;
1443 unsigned ret = 0;
1445 if (unlikely(!nr_pages))
1446 return 0;
1448 rcu_read_lock();
1449 restart:
1450 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1451 &iter, *index, tag) {
1452 struct page *page;
1453 repeat:
1454 page = radix_tree_deref_slot(slot);
1455 if (unlikely(!page))
1456 continue;
1458 if (radix_tree_exception(page)) {
1459 if (radix_tree_deref_retry(page)) {
1461 * Transient condition which can only trigger
1462 * when entry at index 0 moves out of or back
1463 * to root: none yet gotten, safe to restart.
1465 goto restart;
1468 * A shadow entry of a recently evicted page.
1470 * Those entries should never be tagged, but
1471 * this tree walk is lockless and the tags are
1472 * looked up in bulk, one radix tree node at a
1473 * time, so there is a sizable window for page
1474 * reclaim to evict a page we saw tagged.
1476 * Skip over it.
1478 continue;
1481 if (!page_cache_get_speculative(page))
1482 goto repeat;
1484 /* Has the page moved? */
1485 if (unlikely(page != *slot)) {
1486 page_cache_release(page);
1487 goto repeat;
1490 pages[ret] = page;
1491 if (++ret == nr_pages)
1492 break;
1495 rcu_read_unlock();
1497 if (ret)
1498 *index = pages[ret - 1]->index + 1;
1500 return ret;
1502 EXPORT_SYMBOL(find_get_pages_tag);
1505 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1506 * a _large_ part of the i/o request. Imagine the worst scenario:
1508 * ---R__________________________________________B__________
1509 * ^ reading here ^ bad block(assume 4k)
1511 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1512 * => failing the whole request => read(R) => read(R+1) =>
1513 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1514 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1515 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1517 * It is going insane. Fix it by quickly scaling down the readahead size.
1519 static void shrink_readahead_size_eio(struct file *filp,
1520 struct file_ra_state *ra)
1522 ra->ra_pages /= 4;
1526 * do_generic_file_read - generic file read routine
1527 * @filp: the file to read
1528 * @ppos: current file position
1529 * @iter: data destination
1530 * @written: already copied
1532 * This is a generic file read routine, and uses the
1533 * mapping->a_ops->readpage() function for the actual low-level stuff.
1535 * This is really ugly. But the goto's actually try to clarify some
1536 * of the logic when it comes to error handling etc.
1538 static ssize_t do_generic_file_read(struct file *filp, loff_t *ppos,
1539 struct iov_iter *iter, ssize_t written)
1541 struct address_space *mapping = filp->f_mapping;
1542 struct inode *inode = mapping->host;
1543 struct file_ra_state *ra = &filp->f_ra;
1544 pgoff_t index;
1545 pgoff_t last_index;
1546 pgoff_t prev_index;
1547 unsigned long offset; /* offset into pagecache page */
1548 unsigned int prev_offset;
1549 int error = 0;
1551 index = *ppos >> PAGE_CACHE_SHIFT;
1552 prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
1553 prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
1554 last_index = (*ppos + iter->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
1555 offset = *ppos & ~PAGE_CACHE_MASK;
1557 for (;;) {
1558 struct page *page;
1559 pgoff_t end_index;
1560 loff_t isize;
1561 unsigned long nr, ret;
1563 cond_resched();
1564 find_page:
1565 if (fatal_signal_pending(current)) {
1566 error = -EINTR;
1567 goto out;
1570 page = find_get_page(mapping, index);
1571 if (!page) {
1572 page_cache_sync_readahead(mapping,
1573 ra, filp,
1574 index, last_index - index);
1575 page = find_get_page(mapping, index);
1576 if (unlikely(page == NULL))
1577 goto no_cached_page;
1579 if (PageReadahead(page)) {
1580 page_cache_async_readahead(mapping,
1581 ra, filp, page,
1582 index, last_index - index);
1584 if (!PageUptodate(page)) {
1586 * See comment in do_read_cache_page on why
1587 * wait_on_page_locked is used to avoid unnecessarily
1588 * serialisations and why it's safe.
1590 wait_on_page_locked_killable(page);
1591 if (PageUptodate(page))
1592 goto page_ok;
1594 if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
1595 !mapping->a_ops->is_partially_uptodate)
1596 goto page_not_up_to_date;
1597 if (!trylock_page(page))
1598 goto page_not_up_to_date;
1599 /* Did it get truncated before we got the lock? */
1600 if (!page->mapping)
1601 goto page_not_up_to_date_locked;
1602 if (!mapping->a_ops->is_partially_uptodate(page,
1603 offset, iter->count))
1604 goto page_not_up_to_date_locked;
1605 unlock_page(page);
1607 page_ok:
1609 * i_size must be checked after we know the page is Uptodate.
1611 * Checking i_size after the check allows us to calculate
1612 * the correct value for "nr", which means the zero-filled
1613 * part of the page is not copied back to userspace (unless
1614 * another truncate extends the file - this is desired though).
1617 isize = i_size_read(inode);
1618 end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1619 if (unlikely(!isize || index > end_index)) {
1620 page_cache_release(page);
1621 goto out;
1624 /* nr is the maximum number of bytes to copy from this page */
1625 nr = PAGE_CACHE_SIZE;
1626 if (index == end_index) {
1627 nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
1628 if (nr <= offset) {
1629 page_cache_release(page);
1630 goto out;
1633 nr = nr - offset;
1635 /* If users can be writing to this page using arbitrary
1636 * virtual addresses, take care about potential aliasing
1637 * before reading the page on the kernel side.
1639 if (mapping_writably_mapped(mapping))
1640 flush_dcache_page(page);
1643 * When a sequential read accesses a page several times,
1644 * only mark it as accessed the first time.
1646 if (prev_index != index || offset != prev_offset)
1647 mark_page_accessed(page);
1648 prev_index = index;
1651 * Ok, we have the page, and it's up-to-date, so
1652 * now we can copy it to user space...
1655 ret = copy_page_to_iter(page, offset, nr, iter);
1656 offset += ret;
1657 index += offset >> PAGE_CACHE_SHIFT;
1658 offset &= ~PAGE_CACHE_MASK;
1659 prev_offset = offset;
1661 page_cache_release(page);
1662 written += ret;
1663 if (!iov_iter_count(iter))
1664 goto out;
1665 if (ret < nr) {
1666 error = -EFAULT;
1667 goto out;
1669 continue;
1671 page_not_up_to_date:
1672 /* Get exclusive access to the page ... */
1673 error = lock_page_killable(page);
1674 if (unlikely(error))
1675 goto readpage_error;
1677 page_not_up_to_date_locked:
1678 /* Did it get truncated before we got the lock? */
1679 if (!page->mapping) {
1680 unlock_page(page);
1681 page_cache_release(page);
1682 continue;
1685 /* Did somebody else fill it already? */
1686 if (PageUptodate(page)) {
1687 unlock_page(page);
1688 goto page_ok;
1691 readpage:
1693 * A previous I/O error may have been due to temporary
1694 * failures, eg. multipath errors.
1695 * PG_error will be set again if readpage fails.
1697 ClearPageError(page);
1698 /* Start the actual read. The read will unlock the page. */
1699 error = mapping->a_ops->readpage(filp, page);
1701 if (unlikely(error)) {
1702 if (error == AOP_TRUNCATED_PAGE) {
1703 page_cache_release(page);
1704 error = 0;
1705 goto find_page;
1707 goto readpage_error;
1710 if (!PageUptodate(page)) {
1711 error = lock_page_killable(page);
1712 if (unlikely(error))
1713 goto readpage_error;
1714 if (!PageUptodate(page)) {
1715 if (page->mapping == NULL) {
1717 * invalidate_mapping_pages got it
1719 unlock_page(page);
1720 page_cache_release(page);
1721 goto find_page;
1723 unlock_page(page);
1724 shrink_readahead_size_eio(filp, ra);
1725 error = -EIO;
1726 goto readpage_error;
1728 unlock_page(page);
1731 goto page_ok;
1733 readpage_error:
1734 /* UHHUH! A synchronous read error occurred. Report it */
1735 page_cache_release(page);
1736 goto out;
1738 no_cached_page:
1740 * Ok, it wasn't cached, so we need to create a new
1741 * page..
1743 page = page_cache_alloc_cold(mapping);
1744 if (!page) {
1745 error = -ENOMEM;
1746 goto out;
1748 error = add_to_page_cache_lru(page, mapping, index,
1749 mapping_gfp_constraint(mapping, GFP_KERNEL));
1750 if (error) {
1751 page_cache_release(page);
1752 if (error == -EEXIST) {
1753 error = 0;
1754 goto find_page;
1756 goto out;
1758 goto readpage;
1761 out:
1762 ra->prev_pos = prev_index;
1763 ra->prev_pos <<= PAGE_CACHE_SHIFT;
1764 ra->prev_pos |= prev_offset;
1766 *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
1767 file_accessed(filp);
1768 return written ? written : error;
1772 * generic_file_read_iter - generic filesystem read routine
1773 * @iocb: kernel I/O control block
1774 * @iter: destination for the data read
1776 * This is the "read_iter()" routine for all filesystems
1777 * that can use the page cache directly.
1779 ssize_t
1780 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
1782 struct file *file = iocb->ki_filp;
1783 ssize_t retval = 0;
1784 loff_t *ppos = &iocb->ki_pos;
1785 loff_t pos = *ppos;
1787 if (iocb->ki_flags & IOCB_DIRECT) {
1788 struct address_space *mapping = file->f_mapping;
1789 struct inode *inode = mapping->host;
1790 size_t count = iov_iter_count(iter);
1791 loff_t size;
1793 if (!count)
1794 goto out; /* skip atime */
1795 size = i_size_read(inode);
1796 retval = filemap_write_and_wait_range(mapping, pos,
1797 pos + count - 1);
1798 if (!retval) {
1799 struct iov_iter data = *iter;
1800 retval = mapping->a_ops->direct_IO(iocb, &data, pos);
1803 if (retval > 0) {
1804 *ppos = pos + retval;
1805 iov_iter_advance(iter, retval);
1809 * Btrfs can have a short DIO read if we encounter
1810 * compressed extents, so if there was an error, or if
1811 * we've already read everything we wanted to, or if
1812 * there was a short read because we hit EOF, go ahead
1813 * and return. Otherwise fallthrough to buffered io for
1814 * the rest of the read. Buffered reads will not work for
1815 * DAX files, so don't bother trying.
1817 if (retval < 0 || !iov_iter_count(iter) || *ppos >= size ||
1818 IS_DAX(inode)) {
1819 file_accessed(file);
1820 goto out;
1824 retval = do_generic_file_read(file, ppos, iter, retval);
1825 out:
1826 return retval;
1828 EXPORT_SYMBOL(generic_file_read_iter);
1830 #ifdef CONFIG_MMU
1832 * page_cache_read - adds requested page to the page cache if not already there
1833 * @file: file to read
1834 * @offset: page index
1836 * This adds the requested page to the page cache if it isn't already there,
1837 * and schedules an I/O to read in its contents from disk.
1839 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
1841 struct address_space *mapping = file->f_mapping;
1842 struct page *page;
1843 int ret;
1845 do {
1846 page = __page_cache_alloc(gfp_mask|__GFP_COLD);
1847 if (!page)
1848 return -ENOMEM;
1850 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1851 if (ret == 0)
1852 ret = mapping->a_ops->readpage(file, page);
1853 else if (ret == -EEXIST)
1854 ret = 0; /* losing race to add is OK */
1856 page_cache_release(page);
1858 } while (ret == AOP_TRUNCATED_PAGE);
1860 return ret;
1863 #define MMAP_LOTSAMISS (100)
1866 * Synchronous readahead happens when we don't even find
1867 * a page in the page cache at all.
1869 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
1870 struct file_ra_state *ra,
1871 struct file *file,
1872 pgoff_t offset)
1874 struct address_space *mapping = file->f_mapping;
1876 /* If we don't want any read-ahead, don't bother */
1877 if (vma->vm_flags & VM_RAND_READ)
1878 return;
1879 if (!ra->ra_pages)
1880 return;
1882 if (vma->vm_flags & VM_SEQ_READ) {
1883 page_cache_sync_readahead(mapping, ra, file, offset,
1884 ra->ra_pages);
1885 return;
1888 /* Avoid banging the cache line if not needed */
1889 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
1890 ra->mmap_miss++;
1893 * Do we miss much more than hit in this file? If so,
1894 * stop bothering with read-ahead. It will only hurt.
1896 if (ra->mmap_miss > MMAP_LOTSAMISS)
1897 return;
1900 * mmap read-around
1902 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
1903 ra->size = ra->ra_pages;
1904 ra->async_size = ra->ra_pages / 4;
1905 ra_submit(ra, mapping, file);
1909 * Asynchronous readahead happens when we find the page and PG_readahead,
1910 * so we want to possibly extend the readahead further..
1912 static void do_async_mmap_readahead(struct vm_area_struct *vma,
1913 struct file_ra_state *ra,
1914 struct file *file,
1915 struct page *page,
1916 pgoff_t offset)
1918 struct address_space *mapping = file->f_mapping;
1920 /* If we don't want any read-ahead, don't bother */
1921 if (vma->vm_flags & VM_RAND_READ)
1922 return;
1923 if (ra->mmap_miss > 0)
1924 ra->mmap_miss--;
1925 if (PageReadahead(page))
1926 page_cache_async_readahead(mapping, ra, file,
1927 page, offset, ra->ra_pages);
1931 * filemap_fault - read in file data for page fault handling
1932 * @vma: vma in which the fault was taken
1933 * @vmf: struct vm_fault containing details of the fault
1935 * filemap_fault() is invoked via the vma operations vector for a
1936 * mapped memory region to read in file data during a page fault.
1938 * The goto's are kind of ugly, but this streamlines the normal case of having
1939 * it in the page cache, and handles the special cases reasonably without
1940 * having a lot of duplicated code.
1942 * vma->vm_mm->mmap_sem must be held on entry.
1944 * If our return value has VM_FAULT_RETRY set, it's because
1945 * lock_page_or_retry() returned 0.
1946 * The mmap_sem has usually been released in this case.
1947 * See __lock_page_or_retry() for the exception.
1949 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
1950 * has not been released.
1952 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
1954 int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1956 int error;
1957 struct file *file = vma->vm_file;
1958 struct address_space *mapping = file->f_mapping;
1959 struct file_ra_state *ra = &file->f_ra;
1960 struct inode *inode = mapping->host;
1961 pgoff_t offset = vmf->pgoff;
1962 struct page *page;
1963 loff_t size;
1964 int ret = 0;
1966 size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
1967 if (offset >= size >> PAGE_CACHE_SHIFT)
1968 return VM_FAULT_SIGBUS;
1971 * Do we have something in the page cache already?
1973 page = find_get_page(mapping, offset);
1974 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
1976 * We found the page, so try async readahead before
1977 * waiting for the lock.
1979 do_async_mmap_readahead(vma, ra, file, page, offset);
1980 } else if (!page) {
1981 /* No page in the page cache at all */
1982 do_sync_mmap_readahead(vma, ra, file, offset);
1983 count_vm_event(PGMAJFAULT);
1984 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
1985 ret = VM_FAULT_MAJOR;
1986 retry_find:
1987 page = find_get_page(mapping, offset);
1988 if (!page)
1989 goto no_cached_page;
1992 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
1993 page_cache_release(page);
1994 return ret | VM_FAULT_RETRY;
1997 /* Did it get truncated? */
1998 if (unlikely(page->mapping != mapping)) {
1999 unlock_page(page);
2000 put_page(page);
2001 goto retry_find;
2003 VM_BUG_ON_PAGE(page->index != offset, page);
2006 * We have a locked page in the page cache, now we need to check
2007 * that it's up-to-date. If not, it is going to be due to an error.
2009 if (unlikely(!PageUptodate(page)))
2010 goto page_not_uptodate;
2013 * Found the page and have a reference on it.
2014 * We must recheck i_size under page lock.
2016 size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
2017 if (unlikely(offset >= size >> PAGE_CACHE_SHIFT)) {
2018 unlock_page(page);
2019 page_cache_release(page);
2020 return VM_FAULT_SIGBUS;
2023 vmf->page = page;
2024 return ret | VM_FAULT_LOCKED;
2026 no_cached_page:
2028 * We're only likely to ever get here if MADV_RANDOM is in
2029 * effect.
2031 error = page_cache_read(file, offset, vmf->gfp_mask);
2034 * The page we want has now been added to the page cache.
2035 * In the unlikely event that someone removed it in the
2036 * meantime, we'll just come back here and read it again.
2038 if (error >= 0)
2039 goto retry_find;
2042 * An error return from page_cache_read can result if the
2043 * system is low on memory, or a problem occurs while trying
2044 * to schedule I/O.
2046 if (error == -ENOMEM)
2047 return VM_FAULT_OOM;
2048 return VM_FAULT_SIGBUS;
2050 page_not_uptodate:
2052 * Umm, take care of errors if the page isn't up-to-date.
2053 * Try to re-read it _once_. We do this synchronously,
2054 * because there really aren't any performance issues here
2055 * and we need to check for errors.
2057 ClearPageError(page);
2058 error = mapping->a_ops->readpage(file, page);
2059 if (!error) {
2060 wait_on_page_locked(page);
2061 if (!PageUptodate(page))
2062 error = -EIO;
2064 page_cache_release(page);
2066 if (!error || error == AOP_TRUNCATED_PAGE)
2067 goto retry_find;
2069 /* Things didn't work out. Return zero to tell the mm layer so. */
2070 shrink_readahead_size_eio(file, ra);
2071 return VM_FAULT_SIGBUS;
2073 EXPORT_SYMBOL(filemap_fault);
2075 void filemap_map_pages(struct vm_area_struct *vma, struct vm_fault *vmf)
2077 struct radix_tree_iter iter;
2078 void **slot;
2079 struct file *file = vma->vm_file;
2080 struct address_space *mapping = file->f_mapping;
2081 loff_t size;
2082 struct page *page;
2083 unsigned long address = (unsigned long) vmf->virtual_address;
2084 unsigned long addr;
2085 pte_t *pte;
2087 rcu_read_lock();
2088 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, vmf->pgoff) {
2089 if (iter.index > vmf->max_pgoff)
2090 break;
2091 repeat:
2092 page = radix_tree_deref_slot(slot);
2093 if (unlikely(!page))
2094 goto next;
2095 if (radix_tree_exception(page)) {
2096 if (radix_tree_deref_retry(page))
2097 break;
2098 else
2099 goto next;
2102 if (!page_cache_get_speculative(page))
2103 goto repeat;
2105 /* Has the page moved? */
2106 if (unlikely(page != *slot)) {
2107 page_cache_release(page);
2108 goto repeat;
2111 if (!PageUptodate(page) ||
2112 PageReadahead(page) ||
2113 PageHWPoison(page))
2114 goto skip;
2115 if (!trylock_page(page))
2116 goto skip;
2118 if (page->mapping != mapping || !PageUptodate(page))
2119 goto unlock;
2121 size = round_up(i_size_read(mapping->host), PAGE_CACHE_SIZE);
2122 if (page->index >= size >> PAGE_CACHE_SHIFT)
2123 goto unlock;
2125 pte = vmf->pte + page->index - vmf->pgoff;
2126 if (!pte_none(*pte))
2127 goto unlock;
2129 if (file->f_ra.mmap_miss > 0)
2130 file->f_ra.mmap_miss--;
2131 addr = address + (page->index - vmf->pgoff) * PAGE_SIZE;
2132 do_set_pte(vma, addr, page, pte, false, false);
2133 unlock_page(page);
2134 goto next;
2135 unlock:
2136 unlock_page(page);
2137 skip:
2138 page_cache_release(page);
2139 next:
2140 if (iter.index == vmf->max_pgoff)
2141 break;
2143 rcu_read_unlock();
2145 EXPORT_SYMBOL(filemap_map_pages);
2147 int filemap_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
2149 struct page *page = vmf->page;
2150 struct inode *inode = file_inode(vma->vm_file);
2151 int ret = VM_FAULT_LOCKED;
2153 sb_start_pagefault(inode->i_sb);
2154 file_update_time(vma->vm_file);
2155 lock_page(page);
2156 if (page->mapping != inode->i_mapping) {
2157 unlock_page(page);
2158 ret = VM_FAULT_NOPAGE;
2159 goto out;
2162 * We mark the page dirty already here so that when freeze is in
2163 * progress, we are guaranteed that writeback during freezing will
2164 * see the dirty page and writeprotect it again.
2166 set_page_dirty(page);
2167 wait_for_stable_page(page);
2168 out:
2169 sb_end_pagefault(inode->i_sb);
2170 return ret;
2172 EXPORT_SYMBOL(filemap_page_mkwrite);
2174 const struct vm_operations_struct generic_file_vm_ops = {
2175 .fault = filemap_fault,
2176 .map_pages = filemap_map_pages,
2177 .page_mkwrite = filemap_page_mkwrite,
2180 /* This is used for a general mmap of a disk file */
2182 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2184 struct address_space *mapping = file->f_mapping;
2186 if (!mapping->a_ops->readpage)
2187 return -ENOEXEC;
2188 file_accessed(file);
2189 vma->vm_ops = &generic_file_vm_ops;
2190 return 0;
2194 * This is for filesystems which do not implement ->writepage.
2196 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2198 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2199 return -EINVAL;
2200 return generic_file_mmap(file, vma);
2202 #else
2203 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2205 return -ENOSYS;
2207 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2209 return -ENOSYS;
2211 #endif /* CONFIG_MMU */
2213 EXPORT_SYMBOL(generic_file_mmap);
2214 EXPORT_SYMBOL(generic_file_readonly_mmap);
2216 static struct page *wait_on_page_read(struct page *page)
2218 if (!IS_ERR(page)) {
2219 wait_on_page_locked(page);
2220 if (!PageUptodate(page)) {
2221 page_cache_release(page);
2222 page = ERR_PTR(-EIO);
2225 return page;
2228 static struct page *do_read_cache_page(struct address_space *mapping,
2229 pgoff_t index,
2230 int (*filler)(void *, struct page *),
2231 void *data,
2232 gfp_t gfp)
2234 struct page *page;
2235 int err;
2236 repeat:
2237 page = find_get_page(mapping, index);
2238 if (!page) {
2239 page = __page_cache_alloc(gfp | __GFP_COLD);
2240 if (!page)
2241 return ERR_PTR(-ENOMEM);
2242 err = add_to_page_cache_lru(page, mapping, index, gfp);
2243 if (unlikely(err)) {
2244 page_cache_release(page);
2245 if (err == -EEXIST)
2246 goto repeat;
2247 /* Presumably ENOMEM for radix tree node */
2248 return ERR_PTR(err);
2251 filler:
2252 err = filler(data, page);
2253 if (err < 0) {
2254 page_cache_release(page);
2255 return ERR_PTR(err);
2258 page = wait_on_page_read(page);
2259 if (IS_ERR(page))
2260 return page;
2261 goto out;
2263 if (PageUptodate(page))
2264 goto out;
2267 * Page is not up to date and may be locked due one of the following
2268 * case a: Page is being filled and the page lock is held
2269 * case b: Read/write error clearing the page uptodate status
2270 * case c: Truncation in progress (page locked)
2271 * case d: Reclaim in progress
2273 * Case a, the page will be up to date when the page is unlocked.
2274 * There is no need to serialise on the page lock here as the page
2275 * is pinned so the lock gives no additional protection. Even if the
2276 * the page is truncated, the data is still valid if PageUptodate as
2277 * it's a race vs truncate race.
2278 * Case b, the page will not be up to date
2279 * Case c, the page may be truncated but in itself, the data may still
2280 * be valid after IO completes as it's a read vs truncate race. The
2281 * operation must restart if the page is not uptodate on unlock but
2282 * otherwise serialising on page lock to stabilise the mapping gives
2283 * no additional guarantees to the caller as the page lock is
2284 * released before return.
2285 * Case d, similar to truncation. If reclaim holds the page lock, it
2286 * will be a race with remove_mapping that determines if the mapping
2287 * is valid on unlock but otherwise the data is valid and there is
2288 * no need to serialise with page lock.
2290 * As the page lock gives no additional guarantee, we optimistically
2291 * wait on the page to be unlocked and check if it's up to date and
2292 * use the page if it is. Otherwise, the page lock is required to
2293 * distinguish between the different cases. The motivation is that we
2294 * avoid spurious serialisations and wakeups when multiple processes
2295 * wait on the same page for IO to complete.
2297 wait_on_page_locked(page);
2298 if (PageUptodate(page))
2299 goto out;
2301 /* Distinguish between all the cases under the safety of the lock */
2302 lock_page(page);
2304 /* Case c or d, restart the operation */
2305 if (!page->mapping) {
2306 unlock_page(page);
2307 page_cache_release(page);
2308 goto repeat;
2311 /* Someone else locked and filled the page in a very small window */
2312 if (PageUptodate(page)) {
2313 unlock_page(page);
2314 goto out;
2318 * A previous I/O error may have been due to temporary
2319 * failures.
2320 * Clear page error before actual read, PG_error will be
2321 * set again if read page fails.
2323 ClearPageError(page);
2324 goto filler;
2326 out:
2327 mark_page_accessed(page);
2328 return page;
2332 * read_cache_page - read into page cache, fill it if needed
2333 * @mapping: the page's address_space
2334 * @index: the page index
2335 * @filler: function to perform the read
2336 * @data: first arg to filler(data, page) function, often left as NULL
2338 * Read into the page cache. If a page already exists, and PageUptodate() is
2339 * not set, try to fill the page and wait for it to become unlocked.
2341 * If the page does not get brought uptodate, return -EIO.
2343 struct page *read_cache_page(struct address_space *mapping,
2344 pgoff_t index,
2345 int (*filler)(void *, struct page *),
2346 void *data)
2348 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2350 EXPORT_SYMBOL(read_cache_page);
2353 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2354 * @mapping: the page's address_space
2355 * @index: the page index
2356 * @gfp: the page allocator flags to use if allocating
2358 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2359 * any new page allocations done using the specified allocation flags.
2361 * If the page does not get brought uptodate, return -EIO.
2363 struct page *read_cache_page_gfp(struct address_space *mapping,
2364 pgoff_t index,
2365 gfp_t gfp)
2367 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2369 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2371 EXPORT_SYMBOL(read_cache_page_gfp);
2374 * Performs necessary checks before doing a write
2376 * Can adjust writing position or amount of bytes to write.
2377 * Returns appropriate error code that caller should return or
2378 * zero in case that write should be allowed.
2380 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2382 struct file *file = iocb->ki_filp;
2383 struct inode *inode = file->f_mapping->host;
2384 unsigned long limit = rlimit(RLIMIT_FSIZE);
2385 loff_t pos;
2387 if (!iov_iter_count(from))
2388 return 0;
2390 /* FIXME: this is for backwards compatibility with 2.4 */
2391 if (iocb->ki_flags & IOCB_APPEND)
2392 iocb->ki_pos = i_size_read(inode);
2394 pos = iocb->ki_pos;
2396 if (limit != RLIM_INFINITY) {
2397 if (iocb->ki_pos >= limit) {
2398 send_sig(SIGXFSZ, current, 0);
2399 return -EFBIG;
2401 iov_iter_truncate(from, limit - (unsigned long)pos);
2405 * LFS rule
2407 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2408 !(file->f_flags & O_LARGEFILE))) {
2409 if (pos >= MAX_NON_LFS)
2410 return -EFBIG;
2411 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2415 * Are we about to exceed the fs block limit ?
2417 * If we have written data it becomes a short write. If we have
2418 * exceeded without writing data we send a signal and return EFBIG.
2419 * Linus frestrict idea will clean these up nicely..
2421 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2422 return -EFBIG;
2424 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2425 return iov_iter_count(from);
2427 EXPORT_SYMBOL(generic_write_checks);
2429 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2430 loff_t pos, unsigned len, unsigned flags,
2431 struct page **pagep, void **fsdata)
2433 const struct address_space_operations *aops = mapping->a_ops;
2435 return aops->write_begin(file, mapping, pos, len, flags,
2436 pagep, fsdata);
2438 EXPORT_SYMBOL(pagecache_write_begin);
2440 int pagecache_write_end(struct file *file, struct address_space *mapping,
2441 loff_t pos, unsigned len, unsigned copied,
2442 struct page *page, void *fsdata)
2444 const struct address_space_operations *aops = mapping->a_ops;
2446 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2448 EXPORT_SYMBOL(pagecache_write_end);
2450 ssize_t
2451 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from, loff_t pos)
2453 struct file *file = iocb->ki_filp;
2454 struct address_space *mapping = file->f_mapping;
2455 struct inode *inode = mapping->host;
2456 ssize_t written;
2457 size_t write_len;
2458 pgoff_t end;
2459 struct iov_iter data;
2461 write_len = iov_iter_count(from);
2462 end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
2464 written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
2465 if (written)
2466 goto out;
2469 * After a write we want buffered reads to be sure to go to disk to get
2470 * the new data. We invalidate clean cached page from the region we're
2471 * about to write. We do this *before* the write so that we can return
2472 * without clobbering -EIOCBQUEUED from ->direct_IO().
2474 if (mapping->nrpages) {
2475 written = invalidate_inode_pages2_range(mapping,
2476 pos >> PAGE_CACHE_SHIFT, end);
2478 * If a page can not be invalidated, return 0 to fall back
2479 * to buffered write.
2481 if (written) {
2482 if (written == -EBUSY)
2483 return 0;
2484 goto out;
2488 data = *from;
2489 written = mapping->a_ops->direct_IO(iocb, &data, pos);
2492 * Finally, try again to invalidate clean pages which might have been
2493 * cached by non-direct readahead, or faulted in by get_user_pages()
2494 * if the source of the write was an mmap'ed region of the file
2495 * we're writing. Either one is a pretty crazy thing to do,
2496 * so we don't support it 100%. If this invalidation
2497 * fails, tough, the write still worked...
2499 if (mapping->nrpages) {
2500 invalidate_inode_pages2_range(mapping,
2501 pos >> PAGE_CACHE_SHIFT, end);
2504 if (written > 0) {
2505 pos += written;
2506 iov_iter_advance(from, written);
2507 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2508 i_size_write(inode, pos);
2509 mark_inode_dirty(inode);
2511 iocb->ki_pos = pos;
2513 out:
2514 return written;
2516 EXPORT_SYMBOL(generic_file_direct_write);
2519 * Find or create a page at the given pagecache position. Return the locked
2520 * page. This function is specifically for buffered writes.
2522 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2523 pgoff_t index, unsigned flags)
2525 struct page *page;
2526 int fgp_flags = FGP_LOCK|FGP_ACCESSED|FGP_WRITE|FGP_CREAT;
2528 if (flags & AOP_FLAG_NOFS)
2529 fgp_flags |= FGP_NOFS;
2531 page = pagecache_get_page(mapping, index, fgp_flags,
2532 mapping_gfp_mask(mapping));
2533 if (page)
2534 wait_for_stable_page(page);
2536 return page;
2538 EXPORT_SYMBOL(grab_cache_page_write_begin);
2540 ssize_t generic_perform_write(struct file *file,
2541 struct iov_iter *i, loff_t pos)
2543 struct address_space *mapping = file->f_mapping;
2544 const struct address_space_operations *a_ops = mapping->a_ops;
2545 long status = 0;
2546 ssize_t written = 0;
2547 unsigned int flags = 0;
2550 * Copies from kernel address space cannot fail (NFSD is a big user).
2552 if (!iter_is_iovec(i))
2553 flags |= AOP_FLAG_UNINTERRUPTIBLE;
2555 do {
2556 struct page *page;
2557 unsigned long offset; /* Offset into pagecache page */
2558 unsigned long bytes; /* Bytes to write to page */
2559 size_t copied; /* Bytes copied from user */
2560 void *fsdata;
2562 offset = (pos & (PAGE_CACHE_SIZE - 1));
2563 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2564 iov_iter_count(i));
2566 again:
2568 * Bring in the user page that we will copy from _first_.
2569 * Otherwise there's a nasty deadlock on copying from the
2570 * same page as we're writing to, without it being marked
2571 * up-to-date.
2573 * Not only is this an optimisation, but it is also required
2574 * to check that the address is actually valid, when atomic
2575 * usercopies are used, below.
2577 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
2578 status = -EFAULT;
2579 break;
2582 if (fatal_signal_pending(current)) {
2583 status = -EINTR;
2584 break;
2587 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
2588 &page, &fsdata);
2589 if (unlikely(status < 0))
2590 break;
2592 if (mapping_writably_mapped(mapping))
2593 flush_dcache_page(page);
2595 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
2596 flush_dcache_page(page);
2598 status = a_ops->write_end(file, mapping, pos, bytes, copied,
2599 page, fsdata);
2600 if (unlikely(status < 0))
2601 break;
2602 copied = status;
2604 cond_resched();
2606 iov_iter_advance(i, copied);
2607 if (unlikely(copied == 0)) {
2609 * If we were unable to copy any data at all, we must
2610 * fall back to a single segment length write.
2612 * If we didn't fallback here, we could livelock
2613 * because not all segments in the iov can be copied at
2614 * once without a pagefault.
2616 bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
2617 iov_iter_single_seg_count(i));
2618 goto again;
2620 pos += copied;
2621 written += copied;
2623 balance_dirty_pages_ratelimited(mapping);
2624 } while (iov_iter_count(i));
2626 return written ? written : status;
2628 EXPORT_SYMBOL(generic_perform_write);
2631 * __generic_file_write_iter - write data to a file
2632 * @iocb: IO state structure (file, offset, etc.)
2633 * @from: iov_iter with data to write
2635 * This function does all the work needed for actually writing data to a
2636 * file. It does all basic checks, removes SUID from the file, updates
2637 * modification times and calls proper subroutines depending on whether we
2638 * do direct IO or a standard buffered write.
2640 * It expects i_mutex to be grabbed unless we work on a block device or similar
2641 * object which does not need locking at all.
2643 * This function does *not* take care of syncing data in case of O_SYNC write.
2644 * A caller has to handle it. This is mainly due to the fact that we want to
2645 * avoid syncing under i_mutex.
2647 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2649 struct file *file = iocb->ki_filp;
2650 struct address_space * mapping = file->f_mapping;
2651 struct inode *inode = mapping->host;
2652 ssize_t written = 0;
2653 ssize_t err;
2654 ssize_t status;
2656 /* We can write back this queue in page reclaim */
2657 current->backing_dev_info = inode_to_bdi(inode);
2658 err = file_remove_privs(file);
2659 if (err)
2660 goto out;
2662 err = file_update_time(file);
2663 if (err)
2664 goto out;
2666 if (iocb->ki_flags & IOCB_DIRECT) {
2667 loff_t pos, endbyte;
2669 written = generic_file_direct_write(iocb, from, iocb->ki_pos);
2671 * If the write stopped short of completing, fall back to
2672 * buffered writes. Some filesystems do this for writes to
2673 * holes, for example. For DAX files, a buffered write will
2674 * not succeed (even if it did, DAX does not handle dirty
2675 * page-cache pages correctly).
2677 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
2678 goto out;
2680 status = generic_perform_write(file, from, pos = iocb->ki_pos);
2682 * If generic_perform_write() returned a synchronous error
2683 * then we want to return the number of bytes which were
2684 * direct-written, or the error code if that was zero. Note
2685 * that this differs from normal direct-io semantics, which
2686 * will return -EFOO even if some bytes were written.
2688 if (unlikely(status < 0)) {
2689 err = status;
2690 goto out;
2693 * We need to ensure that the page cache pages are written to
2694 * disk and invalidated to preserve the expected O_DIRECT
2695 * semantics.
2697 endbyte = pos + status - 1;
2698 err = filemap_write_and_wait_range(mapping, pos, endbyte);
2699 if (err == 0) {
2700 iocb->ki_pos = endbyte + 1;
2701 written += status;
2702 invalidate_mapping_pages(mapping,
2703 pos >> PAGE_CACHE_SHIFT,
2704 endbyte >> PAGE_CACHE_SHIFT);
2705 } else {
2707 * We don't know how much we wrote, so just return
2708 * the number of bytes which were direct-written
2711 } else {
2712 written = generic_perform_write(file, from, iocb->ki_pos);
2713 if (likely(written > 0))
2714 iocb->ki_pos += written;
2716 out:
2717 current->backing_dev_info = NULL;
2718 return written ? written : err;
2720 EXPORT_SYMBOL(__generic_file_write_iter);
2723 * generic_file_write_iter - write data to a file
2724 * @iocb: IO state structure
2725 * @from: iov_iter with data to write
2727 * This is a wrapper around __generic_file_write_iter() to be used by most
2728 * filesystems. It takes care of syncing the file in case of O_SYNC file
2729 * and acquires i_mutex as needed.
2731 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2733 struct file *file = iocb->ki_filp;
2734 struct inode *inode = file->f_mapping->host;
2735 ssize_t ret;
2737 mutex_lock(&inode->i_mutex);
2738 ret = generic_write_checks(iocb, from);
2739 if (ret > 0)
2740 ret = __generic_file_write_iter(iocb, from);
2741 mutex_unlock(&inode->i_mutex);
2743 if (ret > 0) {
2744 ssize_t err;
2746 err = generic_write_sync(file, iocb->ki_pos - ret, ret);
2747 if (err < 0)
2748 ret = err;
2750 return ret;
2752 EXPORT_SYMBOL(generic_file_write_iter);
2755 * try_to_release_page() - release old fs-specific metadata on a page
2757 * @page: the page which the kernel is trying to free
2758 * @gfp_mask: memory allocation flags (and I/O mode)
2760 * The address_space is to try to release any data against the page
2761 * (presumably at page->private). If the release was successful, return `1'.
2762 * Otherwise return zero.
2764 * This may also be called if PG_fscache is set on a page, indicating that the
2765 * page is known to the local caching routines.
2767 * The @gfp_mask argument specifies whether I/O may be performed to release
2768 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
2771 int try_to_release_page(struct page *page, gfp_t gfp_mask)
2773 struct address_space * const mapping = page->mapping;
2775 BUG_ON(!PageLocked(page));
2776 if (PageWriteback(page))
2777 return 0;
2779 if (mapping && mapping->a_ops->releasepage)
2780 return mapping->a_ops->releasepage(page, gfp_mask);
2781 return try_to_free_buffers(page);
2784 EXPORT_SYMBOL(try_to_release_page);