Linux 4.14.136
[linux-stable.git] / mm / filemap.c
blob938365ad7e99aab2b12c5447a96984a4abcb1f2c
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/dax.h>
15 #include <linux/fs.h>
16 #include <linux/sched/signal.h>
17 #include <linux/uaccess.h>
18 #include <linux/capability.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/gfp.h>
21 #include <linux/mm.h>
22 #include <linux/swap.h>
23 #include <linux/mman.h>
24 #include <linux/pagemap.h>
25 #include <linux/file.h>
26 #include <linux/uio.h>
27 #include <linux/hash.h>
28 #include <linux/writeback.h>
29 #include <linux/backing-dev.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/security.h>
33 #include <linux/cpuset.h>
34 #include <linux/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>
39 #include "internal.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 */
49 #include <asm/mman.h>
52 * Shared mappings implemented 30.11.1994. It's not fully working yet,
53 * though.
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>
64 * Lock ordering:
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
71 * ->i_mutex
72 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
74 * ->mmap_sem
75 * ->i_mmap_rwsem
76 * ->page_table_lock or pte_lock (various, mainly in memory.c)
77 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
79 * ->mmap_sem
80 * ->lock_page (access_process_vm)
82 * ->i_mutex (generic_perform_write)
83 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
85 * bdi->wb.list_lock
86 * sb_lock (fs/fs-writeback.c)
87 * ->mapping->tree_lock (__sync_single_inode)
89 * ->i_mmap_rwsem
90 * ->anon_vma.lock (vma_adjust)
92 * ->anon_vma.lock
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)
110 * ->i_mmap_rwsem
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;
118 void **slot;
119 int error;
121 error = __radix_tree_create(&mapping->page_tree, page->index, 0,
122 &node, &slot);
123 if (error)
124 return error;
125 if (*slot) {
126 void *p;
128 p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
129 if (!radix_tree_exceptional_entry(p))
130 return -EEXIST;
132 mapping->nrexceptional--;
133 if (shadowp)
134 *shadowp = p;
136 __radix_tree_replace(&mapping->page_tree, node, slot, page,
137 workingset_update_node, mapping);
138 mapping->nrpages++;
139 return 0;
142 static void page_cache_tree_delete(struct address_space *mapping,
143 struct page *page, void *shadow)
145 int i, nr;
147 /* hugetlb pages are represented by one entry in the radix tree */
148 nr = PageHuge(page) ? 1 : hpage_nr_pages(page);
150 VM_BUG_ON_PAGE(!PageLocked(page), page);
151 VM_BUG_ON_PAGE(PageTail(page), page);
152 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
154 for (i = 0; i < nr; i++) {
155 struct radix_tree_node *node;
156 void **slot;
158 __radix_tree_lookup(&mapping->page_tree, page->index + i,
159 &node, &slot);
161 VM_BUG_ON_PAGE(!node && nr != 1, page);
163 radix_tree_clear_tags(&mapping->page_tree, node, slot);
164 __radix_tree_replace(&mapping->page_tree, node, slot, shadow,
165 workingset_update_node, mapping);
168 if (shadow) {
169 mapping->nrexceptional += nr;
171 * Make sure the nrexceptional update is committed before
172 * the nrpages update so that final truncate racing
173 * with reclaim does not see both counters 0 at the
174 * same time and miss a shadow entry.
176 smp_wmb();
178 mapping->nrpages -= nr;
182 * Delete a page from the page cache and free it. Caller has to make
183 * sure the page is locked and that nobody else uses it - or that usage
184 * is safe. The caller must hold the mapping's tree_lock.
186 void __delete_from_page_cache(struct page *page, void *shadow)
188 struct address_space *mapping = page->mapping;
189 int nr = hpage_nr_pages(page);
191 trace_mm_filemap_delete_from_page_cache(page);
193 * if we're uptodate, flush out into the cleancache, otherwise
194 * invalidate any existing cleancache entries. We can't leave
195 * stale data around in the cleancache once our page is gone
197 if (PageUptodate(page) && PageMappedToDisk(page))
198 cleancache_put_page(page);
199 else
200 cleancache_invalidate_page(mapping, page);
202 VM_BUG_ON_PAGE(PageTail(page), page);
203 VM_BUG_ON_PAGE(page_mapped(page), page);
204 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
205 int mapcount;
207 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
208 current->comm, page_to_pfn(page));
209 dump_page(page, "still mapped when deleted");
210 dump_stack();
211 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
213 mapcount = page_mapcount(page);
214 if (mapping_exiting(mapping) &&
215 page_count(page) >= mapcount + 2) {
217 * All vmas have already been torn down, so it's
218 * a good bet that actually the page is unmapped,
219 * and we'd prefer not to leak it: if we're wrong,
220 * some other bad page check should catch it later.
222 page_mapcount_reset(page);
223 page_ref_sub(page, mapcount);
227 page_cache_tree_delete(mapping, page, shadow);
229 page->mapping = NULL;
230 /* Leave page->index set: truncation lookup relies upon it */
232 /* hugetlb pages do not participate in page cache accounting. */
233 if (PageHuge(page))
234 return;
236 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
237 if (PageSwapBacked(page)) {
238 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
239 if (PageTransHuge(page))
240 __dec_node_page_state(page, NR_SHMEM_THPS);
241 } else {
242 VM_BUG_ON_PAGE(PageTransHuge(page), page);
246 * At this point page must be either written or cleaned by truncate.
247 * Dirty page here signals a bug and loss of unwritten data.
249 * This fixes dirty accounting after removing the page entirely but
250 * leaves PageDirty set: it has no effect for truncated page and
251 * anyway will be cleared before returning page into buddy allocator.
253 if (WARN_ON_ONCE(PageDirty(page)))
254 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
258 * delete_from_page_cache - delete page from page cache
259 * @page: the page which the kernel is trying to remove from page cache
261 * This must be called only on pages that have been verified to be in the page
262 * cache and locked. It will never put the page into the free list, the caller
263 * has a reference on the page.
265 void delete_from_page_cache(struct page *page)
267 struct address_space *mapping = page_mapping(page);
268 unsigned long flags;
269 void (*freepage)(struct page *);
271 BUG_ON(!PageLocked(page));
273 freepage = mapping->a_ops->freepage;
275 spin_lock_irqsave(&mapping->tree_lock, flags);
276 __delete_from_page_cache(page, NULL);
277 spin_unlock_irqrestore(&mapping->tree_lock, flags);
279 if (freepage)
280 freepage(page);
282 if (PageTransHuge(page) && !PageHuge(page)) {
283 page_ref_sub(page, HPAGE_PMD_NR);
284 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
285 } else {
286 put_page(page);
289 EXPORT_SYMBOL(delete_from_page_cache);
291 int filemap_check_errors(struct address_space *mapping)
293 int ret = 0;
294 /* Check for outstanding write errors */
295 if (test_bit(AS_ENOSPC, &mapping->flags) &&
296 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
297 ret = -ENOSPC;
298 if (test_bit(AS_EIO, &mapping->flags) &&
299 test_and_clear_bit(AS_EIO, &mapping->flags))
300 ret = -EIO;
301 return ret;
303 EXPORT_SYMBOL(filemap_check_errors);
305 static int filemap_check_and_keep_errors(struct address_space *mapping)
307 /* Check for outstanding write errors */
308 if (test_bit(AS_EIO, &mapping->flags))
309 return -EIO;
310 if (test_bit(AS_ENOSPC, &mapping->flags))
311 return -ENOSPC;
312 return 0;
316 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
317 * @mapping: address space structure to write
318 * @start: offset in bytes where the range starts
319 * @end: offset in bytes where the range ends (inclusive)
320 * @sync_mode: enable synchronous operation
322 * Start writeback against all of a mapping's dirty pages that lie
323 * within the byte offsets <start, end> inclusive.
325 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
326 * opposed to a regular memory cleansing writeback. The difference between
327 * these two operations is that if a dirty page/buffer is encountered, it must
328 * be waited upon, and not just skipped over.
330 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
331 loff_t end, int sync_mode)
333 int ret;
334 struct writeback_control wbc = {
335 .sync_mode = sync_mode,
336 .nr_to_write = LONG_MAX,
337 .range_start = start,
338 .range_end = end,
341 if (!mapping_cap_writeback_dirty(mapping))
342 return 0;
344 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
345 ret = do_writepages(mapping, &wbc);
346 wbc_detach_inode(&wbc);
347 return ret;
350 static inline int __filemap_fdatawrite(struct address_space *mapping,
351 int sync_mode)
353 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
356 int filemap_fdatawrite(struct address_space *mapping)
358 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
360 EXPORT_SYMBOL(filemap_fdatawrite);
362 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
363 loff_t end)
365 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
367 EXPORT_SYMBOL(filemap_fdatawrite_range);
370 * filemap_flush - mostly a non-blocking flush
371 * @mapping: target address_space
373 * This is a mostly non-blocking flush. Not suitable for data-integrity
374 * purposes - I/O may not be started against all dirty pages.
376 int filemap_flush(struct address_space *mapping)
378 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
380 EXPORT_SYMBOL(filemap_flush);
383 * filemap_range_has_page - check if a page exists in range.
384 * @mapping: address space within which to check
385 * @start_byte: offset in bytes where the range starts
386 * @end_byte: offset in bytes where the range ends (inclusive)
388 * Find at least one page in the range supplied, usually used to check if
389 * direct writing in this range will trigger a writeback.
391 bool filemap_range_has_page(struct address_space *mapping,
392 loff_t start_byte, loff_t end_byte)
394 pgoff_t index = start_byte >> PAGE_SHIFT;
395 pgoff_t end = end_byte >> PAGE_SHIFT;
396 struct page *page;
398 if (end_byte < start_byte)
399 return false;
401 if (mapping->nrpages == 0)
402 return false;
404 if (!find_get_pages_range(mapping, &index, end, 1, &page))
405 return false;
406 put_page(page);
407 return true;
409 EXPORT_SYMBOL(filemap_range_has_page);
411 static void __filemap_fdatawait_range(struct address_space *mapping,
412 loff_t start_byte, loff_t end_byte)
414 pgoff_t index = start_byte >> PAGE_SHIFT;
415 pgoff_t end = end_byte >> PAGE_SHIFT;
416 struct pagevec pvec;
417 int nr_pages;
419 if (end_byte < start_byte)
420 return;
422 pagevec_init(&pvec, 0);
423 while ((index <= end) &&
424 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
425 PAGECACHE_TAG_WRITEBACK,
426 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
427 unsigned i;
429 for (i = 0; i < nr_pages; i++) {
430 struct page *page = pvec.pages[i];
432 /* until radix tree lookup accepts end_index */
433 if (page->index > end)
434 continue;
436 wait_on_page_writeback(page);
437 ClearPageError(page);
439 pagevec_release(&pvec);
440 cond_resched();
445 * filemap_fdatawait_range - wait for writeback to complete
446 * @mapping: address space structure to wait for
447 * @start_byte: offset in bytes where the range starts
448 * @end_byte: offset in bytes where the range ends (inclusive)
450 * Walk the list of under-writeback pages of the given address space
451 * in the given range and wait for all of them. Check error status of
452 * the address space and return it.
454 * Since the error status of the address space is cleared by this function,
455 * callers are responsible for checking the return value and handling and/or
456 * reporting the error.
458 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
459 loff_t end_byte)
461 __filemap_fdatawait_range(mapping, start_byte, end_byte);
462 return filemap_check_errors(mapping);
464 EXPORT_SYMBOL(filemap_fdatawait_range);
467 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
468 * @mapping: address space structure to wait for
469 * @start_byte: offset in bytes where the range starts
470 * @end_byte: offset in bytes where the range ends (inclusive)
472 * Walk the list of under-writeback pages of the given address space in the
473 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
474 * this function does not clear error status of the address space.
476 * Use this function if callers don't handle errors themselves. Expected
477 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
478 * fsfreeze(8)
480 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
481 loff_t start_byte, loff_t end_byte)
483 __filemap_fdatawait_range(mapping, start_byte, end_byte);
484 return filemap_check_and_keep_errors(mapping);
486 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
489 * file_fdatawait_range - wait for writeback to complete
490 * @file: file pointing to address space structure to wait for
491 * @start_byte: offset in bytes where the range starts
492 * @end_byte: offset in bytes where the range ends (inclusive)
494 * Walk the list of under-writeback pages of the address space that file
495 * refers to, in the given range and wait for all of them. Check error
496 * status of the address space vs. the file->f_wb_err cursor and return it.
498 * Since the error status of the file is advanced by this function,
499 * callers are responsible for checking the return value and handling and/or
500 * reporting the error.
502 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
504 struct address_space *mapping = file->f_mapping;
506 __filemap_fdatawait_range(mapping, start_byte, end_byte);
507 return file_check_and_advance_wb_err(file);
509 EXPORT_SYMBOL(file_fdatawait_range);
512 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
513 * @mapping: address space structure to wait for
515 * Walk the list of under-writeback pages of the given address space
516 * and wait for all of them. Unlike filemap_fdatawait(), this function
517 * does not clear error status of the address space.
519 * Use this function if callers don't handle errors themselves. Expected
520 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
521 * fsfreeze(8)
523 int filemap_fdatawait_keep_errors(struct address_space *mapping)
525 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
526 return filemap_check_and_keep_errors(mapping);
528 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
530 static bool mapping_needs_writeback(struct address_space *mapping)
532 return (!dax_mapping(mapping) && mapping->nrpages) ||
533 (dax_mapping(mapping) && mapping->nrexceptional);
536 int filemap_write_and_wait(struct address_space *mapping)
538 int err = 0;
540 if (mapping_needs_writeback(mapping)) {
541 err = filemap_fdatawrite(mapping);
543 * Even if the above returned error, the pages may be
544 * written partially (e.g. -ENOSPC), so we wait for it.
545 * But the -EIO is special case, it may indicate the worst
546 * thing (e.g. bug) happened, so we avoid waiting for it.
548 if (err != -EIO) {
549 int err2 = filemap_fdatawait(mapping);
550 if (!err)
551 err = err2;
552 } else {
553 /* Clear any previously stored errors */
554 filemap_check_errors(mapping);
556 } else {
557 err = filemap_check_errors(mapping);
559 return err;
561 EXPORT_SYMBOL(filemap_write_and_wait);
564 * filemap_write_and_wait_range - write out & wait on a file range
565 * @mapping: the address_space for the pages
566 * @lstart: offset in bytes where the range starts
567 * @lend: offset in bytes where the range ends (inclusive)
569 * Write out and wait upon file offsets lstart->lend, inclusive.
571 * Note that @lend is inclusive (describes the last byte to be written) so
572 * that this function can be used to write to the very end-of-file (end = -1).
574 int filemap_write_and_wait_range(struct address_space *mapping,
575 loff_t lstart, loff_t lend)
577 int err = 0;
579 if (mapping_needs_writeback(mapping)) {
580 err = __filemap_fdatawrite_range(mapping, lstart, lend,
581 WB_SYNC_ALL);
582 /* See comment of filemap_write_and_wait() */
583 if (err != -EIO) {
584 int err2 = filemap_fdatawait_range(mapping,
585 lstart, lend);
586 if (!err)
587 err = err2;
588 } else {
589 /* Clear any previously stored errors */
590 filemap_check_errors(mapping);
592 } else {
593 err = filemap_check_errors(mapping);
595 return err;
597 EXPORT_SYMBOL(filemap_write_and_wait_range);
599 void __filemap_set_wb_err(struct address_space *mapping, int err)
601 errseq_t eseq = errseq_set(&mapping->wb_err, err);
603 trace_filemap_set_wb_err(mapping, eseq);
605 EXPORT_SYMBOL(__filemap_set_wb_err);
608 * file_check_and_advance_wb_err - report wb error (if any) that was previously
609 * and advance wb_err to current one
610 * @file: struct file on which the error is being reported
612 * When userland calls fsync (or something like nfsd does the equivalent), we
613 * want to report any writeback errors that occurred since the last fsync (or
614 * since the file was opened if there haven't been any).
616 * Grab the wb_err from the mapping. If it matches what we have in the file,
617 * then just quickly return 0. The file is all caught up.
619 * If it doesn't match, then take the mapping value, set the "seen" flag in
620 * it and try to swap it into place. If it works, or another task beat us
621 * to it with the new value, then update the f_wb_err and return the error
622 * portion. The error at this point must be reported via proper channels
623 * (a'la fsync, or NFS COMMIT operation, etc.).
625 * While we handle mapping->wb_err with atomic operations, the f_wb_err
626 * value is protected by the f_lock since we must ensure that it reflects
627 * the latest value swapped in for this file descriptor.
629 int file_check_and_advance_wb_err(struct file *file)
631 int err = 0;
632 errseq_t old = READ_ONCE(file->f_wb_err);
633 struct address_space *mapping = file->f_mapping;
635 /* Locklessly handle the common case where nothing has changed */
636 if (errseq_check(&mapping->wb_err, old)) {
637 /* Something changed, must use slow path */
638 spin_lock(&file->f_lock);
639 old = file->f_wb_err;
640 err = errseq_check_and_advance(&mapping->wb_err,
641 &file->f_wb_err);
642 trace_file_check_and_advance_wb_err(file, old);
643 spin_unlock(&file->f_lock);
647 * We're mostly using this function as a drop in replacement for
648 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
649 * that the legacy code would have had on these flags.
651 clear_bit(AS_EIO, &mapping->flags);
652 clear_bit(AS_ENOSPC, &mapping->flags);
653 return err;
655 EXPORT_SYMBOL(file_check_and_advance_wb_err);
658 * file_write_and_wait_range - write out & wait on a file range
659 * @file: file pointing to address_space with pages
660 * @lstart: offset in bytes where the range starts
661 * @lend: offset in bytes where the range ends (inclusive)
663 * Write out and wait upon file offsets lstart->lend, inclusive.
665 * Note that @lend is inclusive (describes the last byte to be written) so
666 * that this function can be used to write to the very end-of-file (end = -1).
668 * After writing out and waiting on the data, we check and advance the
669 * f_wb_err cursor to the latest value, and return any errors detected there.
671 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
673 int err = 0, err2;
674 struct address_space *mapping = file->f_mapping;
676 if (mapping_needs_writeback(mapping)) {
677 err = __filemap_fdatawrite_range(mapping, lstart, lend,
678 WB_SYNC_ALL);
679 /* See comment of filemap_write_and_wait() */
680 if (err != -EIO)
681 __filemap_fdatawait_range(mapping, lstart, lend);
683 err2 = file_check_and_advance_wb_err(file);
684 if (!err)
685 err = err2;
686 return err;
688 EXPORT_SYMBOL(file_write_and_wait_range);
691 * replace_page_cache_page - replace a pagecache page with a new one
692 * @old: page to be replaced
693 * @new: page to replace with
694 * @gfp_mask: allocation mode
696 * This function replaces a page in the pagecache with a new one. On
697 * success it acquires the pagecache reference for the new page and
698 * drops it for the old page. Both the old and new pages must be
699 * locked. This function does not add the new page to the LRU, the
700 * caller must do that.
702 * The remove + add is atomic. The only way this function can fail is
703 * memory allocation failure.
705 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
707 int error;
709 VM_BUG_ON_PAGE(!PageLocked(old), old);
710 VM_BUG_ON_PAGE(!PageLocked(new), new);
711 VM_BUG_ON_PAGE(new->mapping, new);
713 error = radix_tree_preload(gfp_mask & GFP_RECLAIM_MASK);
714 if (!error) {
715 struct address_space *mapping = old->mapping;
716 void (*freepage)(struct page *);
717 unsigned long flags;
719 pgoff_t offset = old->index;
720 freepage = mapping->a_ops->freepage;
722 get_page(new);
723 new->mapping = mapping;
724 new->index = offset;
726 spin_lock_irqsave(&mapping->tree_lock, flags);
727 __delete_from_page_cache(old, NULL);
728 error = page_cache_tree_insert(mapping, new, NULL);
729 BUG_ON(error);
732 * hugetlb pages do not participate in page cache accounting.
734 if (!PageHuge(new))
735 __inc_node_page_state(new, NR_FILE_PAGES);
736 if (PageSwapBacked(new))
737 __inc_node_page_state(new, NR_SHMEM);
738 spin_unlock_irqrestore(&mapping->tree_lock, flags);
739 mem_cgroup_migrate(old, new);
740 radix_tree_preload_end();
741 if (freepage)
742 freepage(old);
743 put_page(old);
746 return error;
748 EXPORT_SYMBOL_GPL(replace_page_cache_page);
750 static int __add_to_page_cache_locked(struct page *page,
751 struct address_space *mapping,
752 pgoff_t offset, gfp_t gfp_mask,
753 void **shadowp)
755 int huge = PageHuge(page);
756 struct mem_cgroup *memcg;
757 int error;
759 VM_BUG_ON_PAGE(!PageLocked(page), page);
760 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
762 if (!huge) {
763 error = mem_cgroup_try_charge(page, current->mm,
764 gfp_mask, &memcg, false);
765 if (error)
766 return error;
769 error = radix_tree_maybe_preload(gfp_mask & GFP_RECLAIM_MASK);
770 if (error) {
771 if (!huge)
772 mem_cgroup_cancel_charge(page, memcg, false);
773 return error;
776 get_page(page);
777 page->mapping = mapping;
778 page->index = offset;
780 spin_lock_irq(&mapping->tree_lock);
781 error = page_cache_tree_insert(mapping, page, shadowp);
782 radix_tree_preload_end();
783 if (unlikely(error))
784 goto err_insert;
786 /* hugetlb pages do not participate in page cache accounting. */
787 if (!huge)
788 __inc_node_page_state(page, NR_FILE_PAGES);
789 spin_unlock_irq(&mapping->tree_lock);
790 if (!huge)
791 mem_cgroup_commit_charge(page, memcg, false, false);
792 trace_mm_filemap_add_to_page_cache(page);
793 return 0;
794 err_insert:
795 page->mapping = NULL;
796 /* Leave page->index set: truncation relies upon it */
797 spin_unlock_irq(&mapping->tree_lock);
798 if (!huge)
799 mem_cgroup_cancel_charge(page, memcg, false);
800 put_page(page);
801 return error;
805 * add_to_page_cache_locked - add a locked page to the pagecache
806 * @page: page to add
807 * @mapping: the page's address_space
808 * @offset: page index
809 * @gfp_mask: page allocation mode
811 * This function is used to add a page to the pagecache. It must be locked.
812 * This function does not add the page to the LRU. The caller must do that.
814 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
815 pgoff_t offset, gfp_t gfp_mask)
817 return __add_to_page_cache_locked(page, mapping, offset,
818 gfp_mask, NULL);
820 EXPORT_SYMBOL(add_to_page_cache_locked);
822 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
823 pgoff_t offset, gfp_t gfp_mask)
825 void *shadow = NULL;
826 int ret;
828 __SetPageLocked(page);
829 ret = __add_to_page_cache_locked(page, mapping, offset,
830 gfp_mask, &shadow);
831 if (unlikely(ret))
832 __ClearPageLocked(page);
833 else {
835 * The page might have been evicted from cache only
836 * recently, in which case it should be activated like
837 * any other repeatedly accessed page.
838 * The exception is pages getting rewritten; evicting other
839 * data from the working set, only to cache data that will
840 * get overwritten with something else, is a waste of memory.
842 if (!(gfp_mask & __GFP_WRITE) &&
843 shadow && workingset_refault(shadow)) {
844 SetPageActive(page);
845 workingset_activation(page);
846 } else
847 ClearPageActive(page);
848 lru_cache_add(page);
850 return ret;
852 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
854 #ifdef CONFIG_NUMA
855 struct page *__page_cache_alloc(gfp_t gfp)
857 int n;
858 struct page *page;
860 if (cpuset_do_page_mem_spread()) {
861 unsigned int cpuset_mems_cookie;
862 do {
863 cpuset_mems_cookie = read_mems_allowed_begin();
864 n = cpuset_mem_spread_node();
865 page = __alloc_pages_node(n, gfp, 0);
866 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
868 return page;
870 return alloc_pages(gfp, 0);
872 EXPORT_SYMBOL(__page_cache_alloc);
873 #endif
876 * In order to wait for pages to become available there must be
877 * waitqueues associated with pages. By using a hash table of
878 * waitqueues where the bucket discipline is to maintain all
879 * waiters on the same queue and wake all when any of the pages
880 * become available, and for the woken contexts to check to be
881 * sure the appropriate page became available, this saves space
882 * at a cost of "thundering herd" phenomena during rare hash
883 * collisions.
885 #define PAGE_WAIT_TABLE_BITS 8
886 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
887 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
889 static wait_queue_head_t *page_waitqueue(struct page *page)
891 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
894 void __init pagecache_init(void)
896 int i;
898 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
899 init_waitqueue_head(&page_wait_table[i]);
901 page_writeback_init();
904 /* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
905 struct wait_page_key {
906 struct page *page;
907 int bit_nr;
908 int page_match;
911 struct wait_page_queue {
912 struct page *page;
913 int bit_nr;
914 wait_queue_entry_t wait;
917 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
919 struct wait_page_key *key = arg;
920 struct wait_page_queue *wait_page
921 = container_of(wait, struct wait_page_queue, wait);
923 if (wait_page->page != key->page)
924 return 0;
925 key->page_match = 1;
927 if (wait_page->bit_nr != key->bit_nr)
928 return 0;
930 /* Stop walking if it's locked */
931 if (test_bit(key->bit_nr, &key->page->flags))
932 return -1;
934 return autoremove_wake_function(wait, mode, sync, key);
937 static void wake_up_page_bit(struct page *page, int bit_nr)
939 wait_queue_head_t *q = page_waitqueue(page);
940 struct wait_page_key key;
941 unsigned long flags;
942 wait_queue_entry_t bookmark;
944 key.page = page;
945 key.bit_nr = bit_nr;
946 key.page_match = 0;
948 bookmark.flags = 0;
949 bookmark.private = NULL;
950 bookmark.func = NULL;
951 INIT_LIST_HEAD(&bookmark.entry);
953 spin_lock_irqsave(&q->lock, flags);
954 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
956 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
958 * Take a breather from holding the lock,
959 * allow pages that finish wake up asynchronously
960 * to acquire the lock and remove themselves
961 * from wait queue
963 spin_unlock_irqrestore(&q->lock, flags);
964 cpu_relax();
965 spin_lock_irqsave(&q->lock, flags);
966 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
970 * It is possible for other pages to have collided on the waitqueue
971 * hash, so in that case check for a page match. That prevents a long-
972 * term waiter
974 * It is still possible to miss a case here, when we woke page waiters
975 * and removed them from the waitqueue, but there are still other
976 * page waiters.
978 if (!waitqueue_active(q) || !key.page_match) {
979 ClearPageWaiters(page);
981 * It's possible to miss clearing Waiters here, when we woke
982 * our page waiters, but the hashed waitqueue has waiters for
983 * other pages on it.
985 * That's okay, it's a rare case. The next waker will clear it.
988 spin_unlock_irqrestore(&q->lock, flags);
991 static void wake_up_page(struct page *page, int bit)
993 if (!PageWaiters(page))
994 return;
995 wake_up_page_bit(page, bit);
998 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
999 struct page *page, int bit_nr, int state, bool lock)
1001 struct wait_page_queue wait_page;
1002 wait_queue_entry_t *wait = &wait_page.wait;
1003 int ret = 0;
1005 init_wait(wait);
1006 wait->flags = lock ? WQ_FLAG_EXCLUSIVE : 0;
1007 wait->func = wake_page_function;
1008 wait_page.page = page;
1009 wait_page.bit_nr = bit_nr;
1011 for (;;) {
1012 spin_lock_irq(&q->lock);
1014 if (likely(list_empty(&wait->entry))) {
1015 __add_wait_queue_entry_tail(q, wait);
1016 SetPageWaiters(page);
1019 set_current_state(state);
1021 spin_unlock_irq(&q->lock);
1023 if (likely(test_bit(bit_nr, &page->flags))) {
1024 io_schedule();
1027 if (lock) {
1028 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1029 break;
1030 } else {
1031 if (!test_bit(bit_nr, &page->flags))
1032 break;
1035 if (unlikely(signal_pending_state(state, current))) {
1036 ret = -EINTR;
1037 break;
1041 finish_wait(q, wait);
1044 * A signal could leave PageWaiters set. Clearing it here if
1045 * !waitqueue_active would be possible (by open-coding finish_wait),
1046 * but still fail to catch it in the case of wait hash collision. We
1047 * already can fail to clear wait hash collision cases, so don't
1048 * bother with signals either.
1051 return ret;
1054 void wait_on_page_bit(struct page *page, int bit_nr)
1056 wait_queue_head_t *q = page_waitqueue(page);
1057 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, false);
1059 EXPORT_SYMBOL(wait_on_page_bit);
1061 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1063 wait_queue_head_t *q = page_waitqueue(page);
1064 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, false);
1068 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1069 * @page: Page defining the wait queue of interest
1070 * @waiter: Waiter to add to the queue
1072 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1074 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1076 wait_queue_head_t *q = page_waitqueue(page);
1077 unsigned long flags;
1079 spin_lock_irqsave(&q->lock, flags);
1080 __add_wait_queue_entry_tail(q, waiter);
1081 SetPageWaiters(page);
1082 spin_unlock_irqrestore(&q->lock, flags);
1084 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1086 #ifndef clear_bit_unlock_is_negative_byte
1089 * PG_waiters is the high bit in the same byte as PG_lock.
1091 * On x86 (and on many other architectures), we can clear PG_lock and
1092 * test the sign bit at the same time. But if the architecture does
1093 * not support that special operation, we just do this all by hand
1094 * instead.
1096 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1097 * being cleared, but a memory barrier should be unneccssary since it is
1098 * in the same byte as PG_locked.
1100 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1102 clear_bit_unlock(nr, mem);
1103 /* smp_mb__after_atomic(); */
1104 return test_bit(PG_waiters, mem);
1107 #endif
1110 * unlock_page - unlock a locked page
1111 * @page: the page
1113 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1114 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1115 * mechanism between PageLocked pages and PageWriteback pages is shared.
1116 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1118 * Note that this depends on PG_waiters being the sign bit in the byte
1119 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1120 * clear the PG_locked bit and test PG_waiters at the same time fairly
1121 * portably (architectures that do LL/SC can test any bit, while x86 can
1122 * test the sign bit).
1124 void unlock_page(struct page *page)
1126 BUILD_BUG_ON(PG_waiters != 7);
1127 page = compound_head(page);
1128 VM_BUG_ON_PAGE(!PageLocked(page), page);
1129 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1130 wake_up_page_bit(page, PG_locked);
1132 EXPORT_SYMBOL(unlock_page);
1135 * end_page_writeback - end writeback against a page
1136 * @page: the page
1138 void end_page_writeback(struct page *page)
1141 * TestClearPageReclaim could be used here but it is an atomic
1142 * operation and overkill in this particular case. Failing to
1143 * shuffle a page marked for immediate reclaim is too mild to
1144 * justify taking an atomic operation penalty at the end of
1145 * ever page writeback.
1147 if (PageReclaim(page)) {
1148 ClearPageReclaim(page);
1149 rotate_reclaimable_page(page);
1152 if (!test_clear_page_writeback(page))
1153 BUG();
1155 smp_mb__after_atomic();
1156 wake_up_page(page, PG_writeback);
1158 EXPORT_SYMBOL(end_page_writeback);
1161 * After completing I/O on a page, call this routine to update the page
1162 * flags appropriately
1164 void page_endio(struct page *page, bool is_write, int err)
1166 if (!is_write) {
1167 if (!err) {
1168 SetPageUptodate(page);
1169 } else {
1170 ClearPageUptodate(page);
1171 SetPageError(page);
1173 unlock_page(page);
1174 } else {
1175 if (err) {
1176 struct address_space *mapping;
1178 SetPageError(page);
1179 mapping = page_mapping(page);
1180 if (mapping)
1181 mapping_set_error(mapping, err);
1183 end_page_writeback(page);
1186 EXPORT_SYMBOL_GPL(page_endio);
1189 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1190 * @__page: the page to lock
1192 void __lock_page(struct page *__page)
1194 struct page *page = compound_head(__page);
1195 wait_queue_head_t *q = page_waitqueue(page);
1196 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, true);
1198 EXPORT_SYMBOL(__lock_page);
1200 int __lock_page_killable(struct page *__page)
1202 struct page *page = compound_head(__page);
1203 wait_queue_head_t *q = page_waitqueue(page);
1204 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE, true);
1206 EXPORT_SYMBOL_GPL(__lock_page_killable);
1209 * Return values:
1210 * 1 - page is locked; mmap_sem is still held.
1211 * 0 - page is not locked.
1212 * mmap_sem has been released (up_read()), unless flags had both
1213 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1214 * which case mmap_sem is still held.
1216 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1217 * with the page locked and the mmap_sem unperturbed.
1219 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1220 unsigned int flags)
1222 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1224 * CAUTION! In this case, mmap_sem is not released
1225 * even though return 0.
1227 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1228 return 0;
1230 up_read(&mm->mmap_sem);
1231 if (flags & FAULT_FLAG_KILLABLE)
1232 wait_on_page_locked_killable(page);
1233 else
1234 wait_on_page_locked(page);
1235 return 0;
1236 } else {
1237 if (flags & FAULT_FLAG_KILLABLE) {
1238 int ret;
1240 ret = __lock_page_killable(page);
1241 if (ret) {
1242 up_read(&mm->mmap_sem);
1243 return 0;
1245 } else
1246 __lock_page(page);
1247 return 1;
1252 * page_cache_next_hole - find the next hole (not-present entry)
1253 * @mapping: mapping
1254 * @index: index
1255 * @max_scan: maximum range to search
1257 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1258 * lowest indexed hole.
1260 * Returns: the index of the hole if found, otherwise returns an index
1261 * outside of the set specified (in which case 'return - index >=
1262 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1263 * be returned.
1265 * page_cache_next_hole may be called under rcu_read_lock. However,
1266 * like radix_tree_gang_lookup, this will not atomically search a
1267 * snapshot of the tree at a single point in time. For example, if a
1268 * hole is created at index 5, then subsequently a hole is created at
1269 * index 10, page_cache_next_hole covering both indexes may return 10
1270 * if called under rcu_read_lock.
1272 pgoff_t page_cache_next_hole(struct address_space *mapping,
1273 pgoff_t index, unsigned long max_scan)
1275 unsigned long i;
1277 for (i = 0; i < max_scan; i++) {
1278 struct page *page;
1280 page = radix_tree_lookup(&mapping->page_tree, index);
1281 if (!page || radix_tree_exceptional_entry(page))
1282 break;
1283 index++;
1284 if (index == 0)
1285 break;
1288 return index;
1290 EXPORT_SYMBOL(page_cache_next_hole);
1293 * page_cache_prev_hole - find the prev hole (not-present entry)
1294 * @mapping: mapping
1295 * @index: index
1296 * @max_scan: maximum range to search
1298 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1299 * the first hole.
1301 * Returns: the index of the hole if found, otherwise returns an index
1302 * outside of the set specified (in which case 'index - return >=
1303 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1304 * will be returned.
1306 * page_cache_prev_hole may be called under rcu_read_lock. However,
1307 * like radix_tree_gang_lookup, this will not atomically search a
1308 * snapshot of the tree at a single point in time. For example, if a
1309 * hole is created at index 10, then subsequently a hole is created at
1310 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1311 * called under rcu_read_lock.
1313 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1314 pgoff_t index, unsigned long max_scan)
1316 unsigned long i;
1318 for (i = 0; i < max_scan; i++) {
1319 struct page *page;
1321 page = radix_tree_lookup(&mapping->page_tree, index);
1322 if (!page || radix_tree_exceptional_entry(page))
1323 break;
1324 index--;
1325 if (index == ULONG_MAX)
1326 break;
1329 return index;
1331 EXPORT_SYMBOL(page_cache_prev_hole);
1334 * find_get_entry - find and get a page cache entry
1335 * @mapping: the address_space to search
1336 * @offset: the page cache index
1338 * Looks up the page cache slot at @mapping & @offset. If there is a
1339 * page cache page, it is returned with an increased refcount.
1341 * If the slot holds a shadow entry of a previously evicted page, or a
1342 * swap entry from shmem/tmpfs, it is returned.
1344 * Otherwise, %NULL is returned.
1346 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1348 void **pagep;
1349 struct page *head, *page;
1351 rcu_read_lock();
1352 repeat:
1353 page = NULL;
1354 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1355 if (pagep) {
1356 page = radix_tree_deref_slot(pagep);
1357 if (unlikely(!page))
1358 goto out;
1359 if (radix_tree_exception(page)) {
1360 if (radix_tree_deref_retry(page))
1361 goto repeat;
1363 * A shadow entry of a recently evicted page,
1364 * or a swap entry from shmem/tmpfs. Return
1365 * it without attempting to raise page count.
1367 goto out;
1370 head = compound_head(page);
1371 if (!page_cache_get_speculative(head))
1372 goto repeat;
1374 /* The page was split under us? */
1375 if (compound_head(page) != head) {
1376 put_page(head);
1377 goto repeat;
1381 * Has the page moved?
1382 * This is part of the lockless pagecache protocol. See
1383 * include/linux/pagemap.h for details.
1385 if (unlikely(page != *pagep)) {
1386 put_page(head);
1387 goto repeat;
1390 out:
1391 rcu_read_unlock();
1393 return page;
1395 EXPORT_SYMBOL(find_get_entry);
1398 * find_lock_entry - locate, pin and lock a page cache entry
1399 * @mapping: the address_space to search
1400 * @offset: the page cache index
1402 * Looks up the page cache slot at @mapping & @offset. If there is a
1403 * page cache page, it is returned locked and with an increased
1404 * refcount.
1406 * If the slot holds a shadow entry of a previously evicted page, or a
1407 * swap entry from shmem/tmpfs, it is returned.
1409 * Otherwise, %NULL is returned.
1411 * find_lock_entry() may sleep.
1413 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1415 struct page *page;
1417 repeat:
1418 page = find_get_entry(mapping, offset);
1419 if (page && !radix_tree_exception(page)) {
1420 lock_page(page);
1421 /* Has the page been truncated? */
1422 if (unlikely(page_mapping(page) != mapping)) {
1423 unlock_page(page);
1424 put_page(page);
1425 goto repeat;
1427 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1429 return page;
1431 EXPORT_SYMBOL(find_lock_entry);
1434 * pagecache_get_page - find and get a page reference
1435 * @mapping: the address_space to search
1436 * @offset: the page index
1437 * @fgp_flags: PCG flags
1438 * @gfp_mask: gfp mask to use for the page cache data page allocation
1440 * Looks up the page cache slot at @mapping & @offset.
1442 * PCG flags modify how the page is returned.
1444 * @fgp_flags can be:
1446 * - FGP_ACCESSED: the page will be marked accessed
1447 * - FGP_LOCK: Page is return locked
1448 * - FGP_CREAT: If page is not present then a new page is allocated using
1449 * @gfp_mask and added to the page cache and the VM's LRU
1450 * list. The page is returned locked and with an increased
1451 * refcount. Otherwise, NULL is returned.
1453 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1454 * if the GFP flags specified for FGP_CREAT are atomic.
1456 * If there is a page cache page, it is returned with an increased refcount.
1458 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1459 int fgp_flags, gfp_t gfp_mask)
1461 struct page *page;
1463 repeat:
1464 page = find_get_entry(mapping, offset);
1465 if (radix_tree_exceptional_entry(page))
1466 page = NULL;
1467 if (!page)
1468 goto no_page;
1470 if (fgp_flags & FGP_LOCK) {
1471 if (fgp_flags & FGP_NOWAIT) {
1472 if (!trylock_page(page)) {
1473 put_page(page);
1474 return NULL;
1476 } else {
1477 lock_page(page);
1480 /* Has the page been truncated? */
1481 if (unlikely(page->mapping != mapping)) {
1482 unlock_page(page);
1483 put_page(page);
1484 goto repeat;
1486 VM_BUG_ON_PAGE(page->index != offset, page);
1489 if (page && (fgp_flags & FGP_ACCESSED))
1490 mark_page_accessed(page);
1492 no_page:
1493 if (!page && (fgp_flags & FGP_CREAT)) {
1494 int err;
1495 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1496 gfp_mask |= __GFP_WRITE;
1497 if (fgp_flags & FGP_NOFS)
1498 gfp_mask &= ~__GFP_FS;
1500 page = __page_cache_alloc(gfp_mask);
1501 if (!page)
1502 return NULL;
1504 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1505 fgp_flags |= FGP_LOCK;
1507 /* Init accessed so avoid atomic mark_page_accessed later */
1508 if (fgp_flags & FGP_ACCESSED)
1509 __SetPageReferenced(page);
1511 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1512 if (unlikely(err)) {
1513 put_page(page);
1514 page = NULL;
1515 if (err == -EEXIST)
1516 goto repeat;
1520 return page;
1522 EXPORT_SYMBOL(pagecache_get_page);
1525 * find_get_entries - gang pagecache lookup
1526 * @mapping: The address_space to search
1527 * @start: The starting page cache index
1528 * @nr_entries: The maximum number of entries
1529 * @entries: Where the resulting entries are placed
1530 * @indices: The cache indices corresponding to the entries in @entries
1532 * find_get_entries() will search for and return a group of up to
1533 * @nr_entries entries in the mapping. The entries are placed at
1534 * @entries. find_get_entries() takes a reference against any actual
1535 * pages it returns.
1537 * The search returns a group of mapping-contiguous page cache entries
1538 * with ascending indexes. There may be holes in the indices due to
1539 * not-present pages.
1541 * Any shadow entries of evicted pages, or swap entries from
1542 * shmem/tmpfs, are included in the returned array.
1544 * find_get_entries() returns the number of pages and shadow entries
1545 * which were found.
1547 unsigned find_get_entries(struct address_space *mapping,
1548 pgoff_t start, unsigned int nr_entries,
1549 struct page **entries, pgoff_t *indices)
1551 void **slot;
1552 unsigned int ret = 0;
1553 struct radix_tree_iter iter;
1555 if (!nr_entries)
1556 return 0;
1558 rcu_read_lock();
1559 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1560 struct page *head, *page;
1561 repeat:
1562 page = radix_tree_deref_slot(slot);
1563 if (unlikely(!page))
1564 continue;
1565 if (radix_tree_exception(page)) {
1566 if (radix_tree_deref_retry(page)) {
1567 slot = radix_tree_iter_retry(&iter);
1568 continue;
1571 * A shadow entry of a recently evicted page, a swap
1572 * entry from shmem/tmpfs or a DAX entry. Return it
1573 * without attempting to raise page count.
1575 goto export;
1578 head = compound_head(page);
1579 if (!page_cache_get_speculative(head))
1580 goto repeat;
1582 /* The page was split under us? */
1583 if (compound_head(page) != head) {
1584 put_page(head);
1585 goto repeat;
1588 /* Has the page moved? */
1589 if (unlikely(page != *slot)) {
1590 put_page(head);
1591 goto repeat;
1593 export:
1594 indices[ret] = iter.index;
1595 entries[ret] = page;
1596 if (++ret == nr_entries)
1597 break;
1599 rcu_read_unlock();
1600 return ret;
1604 * find_get_pages_range - gang pagecache lookup
1605 * @mapping: The address_space to search
1606 * @start: The starting page index
1607 * @end: The final page index (inclusive)
1608 * @nr_pages: The maximum number of pages
1609 * @pages: Where the resulting pages are placed
1611 * find_get_pages_range() will search for and return a group of up to @nr_pages
1612 * pages in the mapping starting at index @start and up to index @end
1613 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1614 * a reference against the returned pages.
1616 * The search returns a group of mapping-contiguous pages with ascending
1617 * indexes. There may be holes in the indices due to not-present pages.
1618 * We also update @start to index the next page for the traversal.
1620 * find_get_pages_range() returns the number of pages which were found. If this
1621 * number is smaller than @nr_pages, the end of specified range has been
1622 * reached.
1624 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1625 pgoff_t end, unsigned int nr_pages,
1626 struct page **pages)
1628 struct radix_tree_iter iter;
1629 void **slot;
1630 unsigned ret = 0;
1632 if (unlikely(!nr_pages))
1633 return 0;
1635 rcu_read_lock();
1636 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, *start) {
1637 struct page *head, *page;
1639 if (iter.index > end)
1640 break;
1641 repeat:
1642 page = radix_tree_deref_slot(slot);
1643 if (unlikely(!page))
1644 continue;
1646 if (radix_tree_exception(page)) {
1647 if (radix_tree_deref_retry(page)) {
1648 slot = radix_tree_iter_retry(&iter);
1649 continue;
1652 * A shadow entry of a recently evicted page,
1653 * or a swap entry from shmem/tmpfs. Skip
1654 * over it.
1656 continue;
1659 head = compound_head(page);
1660 if (!page_cache_get_speculative(head))
1661 goto repeat;
1663 /* The page was split under us? */
1664 if (compound_head(page) != head) {
1665 put_page(head);
1666 goto repeat;
1669 /* Has the page moved? */
1670 if (unlikely(page != *slot)) {
1671 put_page(head);
1672 goto repeat;
1675 pages[ret] = page;
1676 if (++ret == nr_pages) {
1677 *start = pages[ret - 1]->index + 1;
1678 goto out;
1683 * We come here when there is no page beyond @end. We take care to not
1684 * overflow the index @start as it confuses some of the callers. This
1685 * breaks the iteration when there is page at index -1 but that is
1686 * already broken anyway.
1688 if (end == (pgoff_t)-1)
1689 *start = (pgoff_t)-1;
1690 else
1691 *start = end + 1;
1692 out:
1693 rcu_read_unlock();
1695 return ret;
1699 * find_get_pages_contig - gang contiguous pagecache lookup
1700 * @mapping: The address_space to search
1701 * @index: The starting page index
1702 * @nr_pages: The maximum number of pages
1703 * @pages: Where the resulting pages are placed
1705 * find_get_pages_contig() works exactly like find_get_pages(), except
1706 * that the returned number of pages are guaranteed to be contiguous.
1708 * find_get_pages_contig() returns the number of pages which were found.
1710 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1711 unsigned int nr_pages, struct page **pages)
1713 struct radix_tree_iter iter;
1714 void **slot;
1715 unsigned int ret = 0;
1717 if (unlikely(!nr_pages))
1718 return 0;
1720 rcu_read_lock();
1721 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1722 struct page *head, *page;
1723 repeat:
1724 page = radix_tree_deref_slot(slot);
1725 /* The hole, there no reason to continue */
1726 if (unlikely(!page))
1727 break;
1729 if (radix_tree_exception(page)) {
1730 if (radix_tree_deref_retry(page)) {
1731 slot = radix_tree_iter_retry(&iter);
1732 continue;
1735 * A shadow entry of a recently evicted page,
1736 * or a swap entry from shmem/tmpfs. Stop
1737 * looking for contiguous pages.
1739 break;
1742 head = compound_head(page);
1743 if (!page_cache_get_speculative(head))
1744 goto repeat;
1746 /* The page was split under us? */
1747 if (compound_head(page) != head) {
1748 put_page(head);
1749 goto repeat;
1752 /* Has the page moved? */
1753 if (unlikely(page != *slot)) {
1754 put_page(head);
1755 goto repeat;
1759 * must check mapping and index after taking the ref.
1760 * otherwise we can get both false positives and false
1761 * negatives, which is just confusing to the caller.
1763 if (page->mapping == NULL || page_to_pgoff(page) != iter.index) {
1764 put_page(page);
1765 break;
1768 pages[ret] = page;
1769 if (++ret == nr_pages)
1770 break;
1772 rcu_read_unlock();
1773 return ret;
1775 EXPORT_SYMBOL(find_get_pages_contig);
1778 * find_get_pages_tag - find and return pages that match @tag
1779 * @mapping: the address_space to search
1780 * @index: the starting page index
1781 * @tag: the tag index
1782 * @nr_pages: the maximum number of pages
1783 * @pages: where the resulting pages are placed
1785 * Like find_get_pages, except we only return pages which are tagged with
1786 * @tag. We update @index to index the next page for the traversal.
1788 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1789 int tag, unsigned int nr_pages, struct page **pages)
1791 struct radix_tree_iter iter;
1792 void **slot;
1793 unsigned ret = 0;
1795 if (unlikely(!nr_pages))
1796 return 0;
1798 rcu_read_lock();
1799 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1800 &iter, *index, tag) {
1801 struct page *head, *page;
1802 repeat:
1803 page = radix_tree_deref_slot(slot);
1804 if (unlikely(!page))
1805 continue;
1807 if (radix_tree_exception(page)) {
1808 if (radix_tree_deref_retry(page)) {
1809 slot = radix_tree_iter_retry(&iter);
1810 continue;
1813 * A shadow entry of a recently evicted page.
1815 * Those entries should never be tagged, but
1816 * this tree walk is lockless and the tags are
1817 * looked up in bulk, one radix tree node at a
1818 * time, so there is a sizable window for page
1819 * reclaim to evict a page we saw tagged.
1821 * Skip over it.
1823 continue;
1826 head = compound_head(page);
1827 if (!page_cache_get_speculative(head))
1828 goto repeat;
1830 /* The page was split under us? */
1831 if (compound_head(page) != head) {
1832 put_page(head);
1833 goto repeat;
1836 /* Has the page moved? */
1837 if (unlikely(page != *slot)) {
1838 put_page(head);
1839 goto repeat;
1842 pages[ret] = page;
1843 if (++ret == nr_pages)
1844 break;
1847 rcu_read_unlock();
1849 if (ret)
1850 *index = pages[ret - 1]->index + 1;
1852 return ret;
1854 EXPORT_SYMBOL(find_get_pages_tag);
1857 * find_get_entries_tag - find and return entries that match @tag
1858 * @mapping: the address_space to search
1859 * @start: the starting page cache index
1860 * @tag: the tag index
1861 * @nr_entries: the maximum number of entries
1862 * @entries: where the resulting entries are placed
1863 * @indices: the cache indices corresponding to the entries in @entries
1865 * Like find_get_entries, except we only return entries which are tagged with
1866 * @tag.
1868 unsigned find_get_entries_tag(struct address_space *mapping, pgoff_t start,
1869 int tag, unsigned int nr_entries,
1870 struct page **entries, pgoff_t *indices)
1872 void **slot;
1873 unsigned int ret = 0;
1874 struct radix_tree_iter iter;
1876 if (!nr_entries)
1877 return 0;
1879 rcu_read_lock();
1880 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1881 &iter, start, tag) {
1882 struct page *head, *page;
1883 repeat:
1884 page = radix_tree_deref_slot(slot);
1885 if (unlikely(!page))
1886 continue;
1887 if (radix_tree_exception(page)) {
1888 if (radix_tree_deref_retry(page)) {
1889 slot = radix_tree_iter_retry(&iter);
1890 continue;
1894 * A shadow entry of a recently evicted page, a swap
1895 * entry from shmem/tmpfs or a DAX entry. Return it
1896 * without attempting to raise page count.
1898 goto export;
1901 head = compound_head(page);
1902 if (!page_cache_get_speculative(head))
1903 goto repeat;
1905 /* The page was split under us? */
1906 if (compound_head(page) != head) {
1907 put_page(head);
1908 goto repeat;
1911 /* Has the page moved? */
1912 if (unlikely(page != *slot)) {
1913 put_page(head);
1914 goto repeat;
1916 export:
1917 indices[ret] = iter.index;
1918 entries[ret] = page;
1919 if (++ret == nr_entries)
1920 break;
1922 rcu_read_unlock();
1923 return ret;
1925 EXPORT_SYMBOL(find_get_entries_tag);
1928 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1929 * a _large_ part of the i/o request. Imagine the worst scenario:
1931 * ---R__________________________________________B__________
1932 * ^ reading here ^ bad block(assume 4k)
1934 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1935 * => failing the whole request => read(R) => read(R+1) =>
1936 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1937 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1938 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1940 * It is going insane. Fix it by quickly scaling down the readahead size.
1942 static void shrink_readahead_size_eio(struct file *filp,
1943 struct file_ra_state *ra)
1945 ra->ra_pages /= 4;
1949 * generic_file_buffered_read - generic file read routine
1950 * @iocb: the iocb to read
1951 * @iter: data destination
1952 * @written: already copied
1954 * This is a generic file read routine, and uses the
1955 * mapping->a_ops->readpage() function for the actual low-level stuff.
1957 * This is really ugly. But the goto's actually try to clarify some
1958 * of the logic when it comes to error handling etc.
1960 static ssize_t generic_file_buffered_read(struct kiocb *iocb,
1961 struct iov_iter *iter, ssize_t written)
1963 struct file *filp = iocb->ki_filp;
1964 struct address_space *mapping = filp->f_mapping;
1965 struct inode *inode = mapping->host;
1966 struct file_ra_state *ra = &filp->f_ra;
1967 loff_t *ppos = &iocb->ki_pos;
1968 pgoff_t index;
1969 pgoff_t last_index;
1970 pgoff_t prev_index;
1971 unsigned long offset; /* offset into pagecache page */
1972 unsigned int prev_offset;
1973 int error = 0;
1975 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
1976 return 0;
1977 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
1979 index = *ppos >> PAGE_SHIFT;
1980 prev_index = ra->prev_pos >> PAGE_SHIFT;
1981 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
1982 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
1983 offset = *ppos & ~PAGE_MASK;
1985 for (;;) {
1986 struct page *page;
1987 pgoff_t end_index;
1988 loff_t isize;
1989 unsigned long nr, ret;
1991 cond_resched();
1992 find_page:
1993 if (fatal_signal_pending(current)) {
1994 error = -EINTR;
1995 goto out;
1998 page = find_get_page(mapping, index);
1999 if (!page) {
2000 if (iocb->ki_flags & IOCB_NOWAIT)
2001 goto would_block;
2002 page_cache_sync_readahead(mapping,
2003 ra, filp,
2004 index, last_index - index);
2005 page = find_get_page(mapping, index);
2006 if (unlikely(page == NULL))
2007 goto no_cached_page;
2009 if (PageReadahead(page)) {
2010 page_cache_async_readahead(mapping,
2011 ra, filp, page,
2012 index, last_index - index);
2014 if (!PageUptodate(page)) {
2015 if (iocb->ki_flags & IOCB_NOWAIT) {
2016 put_page(page);
2017 goto would_block;
2021 * See comment in do_read_cache_page on why
2022 * wait_on_page_locked is used to avoid unnecessarily
2023 * serialisations and why it's safe.
2025 error = wait_on_page_locked_killable(page);
2026 if (unlikely(error))
2027 goto readpage_error;
2028 if (PageUptodate(page))
2029 goto page_ok;
2031 if (inode->i_blkbits == PAGE_SHIFT ||
2032 !mapping->a_ops->is_partially_uptodate)
2033 goto page_not_up_to_date;
2034 /* pipes can't handle partially uptodate pages */
2035 if (unlikely(iter->type & ITER_PIPE))
2036 goto page_not_up_to_date;
2037 if (!trylock_page(page))
2038 goto page_not_up_to_date;
2039 /* Did it get truncated before we got the lock? */
2040 if (!page->mapping)
2041 goto page_not_up_to_date_locked;
2042 if (!mapping->a_ops->is_partially_uptodate(page,
2043 offset, iter->count))
2044 goto page_not_up_to_date_locked;
2045 unlock_page(page);
2047 page_ok:
2049 * i_size must be checked after we know the page is Uptodate.
2051 * Checking i_size after the check allows us to calculate
2052 * the correct value for "nr", which means the zero-filled
2053 * part of the page is not copied back to userspace (unless
2054 * another truncate extends the file - this is desired though).
2057 isize = i_size_read(inode);
2058 end_index = (isize - 1) >> PAGE_SHIFT;
2059 if (unlikely(!isize || index > end_index)) {
2060 put_page(page);
2061 goto out;
2064 /* nr is the maximum number of bytes to copy from this page */
2065 nr = PAGE_SIZE;
2066 if (index == end_index) {
2067 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2068 if (nr <= offset) {
2069 put_page(page);
2070 goto out;
2073 nr = nr - offset;
2075 /* If users can be writing to this page using arbitrary
2076 * virtual addresses, take care about potential aliasing
2077 * before reading the page on the kernel side.
2079 if (mapping_writably_mapped(mapping))
2080 flush_dcache_page(page);
2083 * When a sequential read accesses a page several times,
2084 * only mark it as accessed the first time.
2086 if (prev_index != index || offset != prev_offset)
2087 mark_page_accessed(page);
2088 prev_index = index;
2091 * Ok, we have the page, and it's up-to-date, so
2092 * now we can copy it to user space...
2095 ret = copy_page_to_iter(page, offset, nr, iter);
2096 offset += ret;
2097 index += offset >> PAGE_SHIFT;
2098 offset &= ~PAGE_MASK;
2099 prev_offset = offset;
2101 put_page(page);
2102 written += ret;
2103 if (!iov_iter_count(iter))
2104 goto out;
2105 if (ret < nr) {
2106 error = -EFAULT;
2107 goto out;
2109 continue;
2111 page_not_up_to_date:
2112 /* Get exclusive access to the page ... */
2113 error = lock_page_killable(page);
2114 if (unlikely(error))
2115 goto readpage_error;
2117 page_not_up_to_date_locked:
2118 /* Did it get truncated before we got the lock? */
2119 if (!page->mapping) {
2120 unlock_page(page);
2121 put_page(page);
2122 continue;
2125 /* Did somebody else fill it already? */
2126 if (PageUptodate(page)) {
2127 unlock_page(page);
2128 goto page_ok;
2131 readpage:
2133 * A previous I/O error may have been due to temporary
2134 * failures, eg. multipath errors.
2135 * PG_error will be set again if readpage fails.
2137 ClearPageError(page);
2138 /* Start the actual read. The read will unlock the page. */
2139 error = mapping->a_ops->readpage(filp, page);
2141 if (unlikely(error)) {
2142 if (error == AOP_TRUNCATED_PAGE) {
2143 put_page(page);
2144 error = 0;
2145 goto find_page;
2147 goto readpage_error;
2150 if (!PageUptodate(page)) {
2151 error = lock_page_killable(page);
2152 if (unlikely(error))
2153 goto readpage_error;
2154 if (!PageUptodate(page)) {
2155 if (page->mapping == NULL) {
2157 * invalidate_mapping_pages got it
2159 unlock_page(page);
2160 put_page(page);
2161 goto find_page;
2163 unlock_page(page);
2164 shrink_readahead_size_eio(filp, ra);
2165 error = -EIO;
2166 goto readpage_error;
2168 unlock_page(page);
2171 goto page_ok;
2173 readpage_error:
2174 /* UHHUH! A synchronous read error occurred. Report it */
2175 put_page(page);
2176 goto out;
2178 no_cached_page:
2180 * Ok, it wasn't cached, so we need to create a new
2181 * page..
2183 page = page_cache_alloc_cold(mapping);
2184 if (!page) {
2185 error = -ENOMEM;
2186 goto out;
2188 error = add_to_page_cache_lru(page, mapping, index,
2189 mapping_gfp_constraint(mapping, GFP_KERNEL));
2190 if (error) {
2191 put_page(page);
2192 if (error == -EEXIST) {
2193 error = 0;
2194 goto find_page;
2196 goto out;
2198 goto readpage;
2201 would_block:
2202 error = -EAGAIN;
2203 out:
2204 ra->prev_pos = prev_index;
2205 ra->prev_pos <<= PAGE_SHIFT;
2206 ra->prev_pos |= prev_offset;
2208 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2209 file_accessed(filp);
2210 return written ? written : error;
2214 * generic_file_read_iter - generic filesystem read routine
2215 * @iocb: kernel I/O control block
2216 * @iter: destination for the data read
2218 * This is the "read_iter()" routine for all filesystems
2219 * that can use the page cache directly.
2221 ssize_t
2222 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2224 size_t count = iov_iter_count(iter);
2225 ssize_t retval = 0;
2227 if (!count)
2228 goto out; /* skip atime */
2230 if (iocb->ki_flags & IOCB_DIRECT) {
2231 struct file *file = iocb->ki_filp;
2232 struct address_space *mapping = file->f_mapping;
2233 struct inode *inode = mapping->host;
2234 loff_t size;
2236 size = i_size_read(inode);
2237 if (iocb->ki_flags & IOCB_NOWAIT) {
2238 if (filemap_range_has_page(mapping, iocb->ki_pos,
2239 iocb->ki_pos + count - 1))
2240 return -EAGAIN;
2241 } else {
2242 retval = filemap_write_and_wait_range(mapping,
2243 iocb->ki_pos,
2244 iocb->ki_pos + count - 1);
2245 if (retval < 0)
2246 goto out;
2249 file_accessed(file);
2251 retval = mapping->a_ops->direct_IO(iocb, iter);
2252 if (retval >= 0) {
2253 iocb->ki_pos += retval;
2254 count -= retval;
2256 iov_iter_revert(iter, count - iov_iter_count(iter));
2259 * Btrfs can have a short DIO read if we encounter
2260 * compressed extents, so if there was an error, or if
2261 * we've already read everything we wanted to, or if
2262 * there was a short read because we hit EOF, go ahead
2263 * and return. Otherwise fallthrough to buffered io for
2264 * the rest of the read. Buffered reads will not work for
2265 * DAX files, so don't bother trying.
2267 if (retval < 0 || !count || iocb->ki_pos >= size ||
2268 IS_DAX(inode))
2269 goto out;
2272 retval = generic_file_buffered_read(iocb, iter, retval);
2273 out:
2274 return retval;
2276 EXPORT_SYMBOL(generic_file_read_iter);
2278 #ifdef CONFIG_MMU
2280 * page_cache_read - adds requested page to the page cache if not already there
2281 * @file: file to read
2282 * @offset: page index
2283 * @gfp_mask: memory allocation flags
2285 * This adds the requested page to the page cache if it isn't already there,
2286 * and schedules an I/O to read in its contents from disk.
2288 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
2290 struct address_space *mapping = file->f_mapping;
2291 struct page *page;
2292 int ret;
2294 do {
2295 page = __page_cache_alloc(gfp_mask|__GFP_COLD);
2296 if (!page)
2297 return -ENOMEM;
2299 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
2300 if (ret == 0)
2301 ret = mapping->a_ops->readpage(file, page);
2302 else if (ret == -EEXIST)
2303 ret = 0; /* losing race to add is OK */
2305 put_page(page);
2307 } while (ret == AOP_TRUNCATED_PAGE);
2309 return ret;
2312 #define MMAP_LOTSAMISS (100)
2315 * Synchronous readahead happens when we don't even find
2316 * a page in the page cache at all.
2318 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
2319 struct file_ra_state *ra,
2320 struct file *file,
2321 pgoff_t offset)
2323 struct address_space *mapping = file->f_mapping;
2325 /* If we don't want any read-ahead, don't bother */
2326 if (vma->vm_flags & VM_RAND_READ)
2327 return;
2328 if (!ra->ra_pages)
2329 return;
2331 if (vma->vm_flags & VM_SEQ_READ) {
2332 page_cache_sync_readahead(mapping, ra, file, offset,
2333 ra->ra_pages);
2334 return;
2337 /* Avoid banging the cache line if not needed */
2338 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2339 ra->mmap_miss++;
2342 * Do we miss much more than hit in this file? If so,
2343 * stop bothering with read-ahead. It will only hurt.
2345 if (ra->mmap_miss > MMAP_LOTSAMISS)
2346 return;
2349 * mmap read-around
2351 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2352 ra->size = ra->ra_pages;
2353 ra->async_size = ra->ra_pages / 4;
2354 ra_submit(ra, mapping, file);
2358 * Asynchronous readahead happens when we find the page and PG_readahead,
2359 * so we want to possibly extend the readahead further..
2361 static void do_async_mmap_readahead(struct vm_area_struct *vma,
2362 struct file_ra_state *ra,
2363 struct file *file,
2364 struct page *page,
2365 pgoff_t offset)
2367 struct address_space *mapping = file->f_mapping;
2369 /* If we don't want any read-ahead, don't bother */
2370 if (vma->vm_flags & VM_RAND_READ)
2371 return;
2372 if (ra->mmap_miss > 0)
2373 ra->mmap_miss--;
2374 if (PageReadahead(page))
2375 page_cache_async_readahead(mapping, ra, file,
2376 page, offset, ra->ra_pages);
2380 * filemap_fault - read in file data for page fault handling
2381 * @vmf: struct vm_fault containing details of the fault
2383 * filemap_fault() is invoked via the vma operations vector for a
2384 * mapped memory region to read in file data during a page fault.
2386 * The goto's are kind of ugly, but this streamlines the normal case of having
2387 * it in the page cache, and handles the special cases reasonably without
2388 * having a lot of duplicated code.
2390 * vma->vm_mm->mmap_sem must be held on entry.
2392 * If our return value has VM_FAULT_RETRY set, it's because
2393 * lock_page_or_retry() returned 0.
2394 * The mmap_sem has usually been released in this case.
2395 * See __lock_page_or_retry() for the exception.
2397 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2398 * has not been released.
2400 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2402 int filemap_fault(struct vm_fault *vmf)
2404 int error;
2405 struct file *file = vmf->vma->vm_file;
2406 struct address_space *mapping = file->f_mapping;
2407 struct file_ra_state *ra = &file->f_ra;
2408 struct inode *inode = mapping->host;
2409 pgoff_t offset = vmf->pgoff;
2410 pgoff_t max_off;
2411 struct page *page;
2412 int ret = 0;
2414 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2415 if (unlikely(offset >= max_off))
2416 return VM_FAULT_SIGBUS;
2419 * Do we have something in the page cache already?
2421 page = find_get_page(mapping, offset);
2422 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2424 * We found the page, so try async readahead before
2425 * waiting for the lock.
2427 do_async_mmap_readahead(vmf->vma, ra, file, page, offset);
2428 } else if (!page) {
2429 /* No page in the page cache at all */
2430 do_sync_mmap_readahead(vmf->vma, ra, file, offset);
2431 count_vm_event(PGMAJFAULT);
2432 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2433 ret = VM_FAULT_MAJOR;
2434 retry_find:
2435 page = find_get_page(mapping, offset);
2436 if (!page)
2437 goto no_cached_page;
2440 if (!lock_page_or_retry(page, vmf->vma->vm_mm, vmf->flags)) {
2441 put_page(page);
2442 return ret | VM_FAULT_RETRY;
2445 /* Did it get truncated? */
2446 if (unlikely(page->mapping != mapping)) {
2447 unlock_page(page);
2448 put_page(page);
2449 goto retry_find;
2451 VM_BUG_ON_PAGE(page->index != offset, page);
2454 * We have a locked page in the page cache, now we need to check
2455 * that it's up-to-date. If not, it is going to be due to an error.
2457 if (unlikely(!PageUptodate(page)))
2458 goto page_not_uptodate;
2461 * Found the page and have a reference on it.
2462 * We must recheck i_size under page lock.
2464 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2465 if (unlikely(offset >= max_off)) {
2466 unlock_page(page);
2467 put_page(page);
2468 return VM_FAULT_SIGBUS;
2471 vmf->page = page;
2472 return ret | VM_FAULT_LOCKED;
2474 no_cached_page:
2476 * We're only likely to ever get here if MADV_RANDOM is in
2477 * effect.
2479 error = page_cache_read(file, offset, vmf->gfp_mask);
2482 * The page we want has now been added to the page cache.
2483 * In the unlikely event that someone removed it in the
2484 * meantime, we'll just come back here and read it again.
2486 if (error >= 0)
2487 goto retry_find;
2490 * An error return from page_cache_read can result if the
2491 * system is low on memory, or a problem occurs while trying
2492 * to schedule I/O.
2494 if (error == -ENOMEM)
2495 return VM_FAULT_OOM;
2496 return VM_FAULT_SIGBUS;
2498 page_not_uptodate:
2500 * Umm, take care of errors if the page isn't up-to-date.
2501 * Try to re-read it _once_. We do this synchronously,
2502 * because there really aren't any performance issues here
2503 * and we need to check for errors.
2505 ClearPageError(page);
2506 error = mapping->a_ops->readpage(file, page);
2507 if (!error) {
2508 wait_on_page_locked(page);
2509 if (!PageUptodate(page))
2510 error = -EIO;
2512 put_page(page);
2514 if (!error || error == AOP_TRUNCATED_PAGE)
2515 goto retry_find;
2517 /* Things didn't work out. Return zero to tell the mm layer so. */
2518 shrink_readahead_size_eio(file, ra);
2519 return VM_FAULT_SIGBUS;
2521 EXPORT_SYMBOL(filemap_fault);
2523 void filemap_map_pages(struct vm_fault *vmf,
2524 pgoff_t start_pgoff, pgoff_t end_pgoff)
2526 struct radix_tree_iter iter;
2527 void **slot;
2528 struct file *file = vmf->vma->vm_file;
2529 struct address_space *mapping = file->f_mapping;
2530 pgoff_t last_pgoff = start_pgoff;
2531 unsigned long max_idx;
2532 struct page *head, *page;
2534 rcu_read_lock();
2535 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter,
2536 start_pgoff) {
2537 if (iter.index > end_pgoff)
2538 break;
2539 repeat:
2540 page = radix_tree_deref_slot(slot);
2541 if (unlikely(!page))
2542 goto next;
2543 if (radix_tree_exception(page)) {
2544 if (radix_tree_deref_retry(page)) {
2545 slot = radix_tree_iter_retry(&iter);
2546 continue;
2548 goto next;
2551 head = compound_head(page);
2552 if (!page_cache_get_speculative(head))
2553 goto repeat;
2555 /* The page was split under us? */
2556 if (compound_head(page) != head) {
2557 put_page(head);
2558 goto repeat;
2561 /* Has the page moved? */
2562 if (unlikely(page != *slot)) {
2563 put_page(head);
2564 goto repeat;
2567 if (!PageUptodate(page) ||
2568 PageReadahead(page) ||
2569 PageHWPoison(page))
2570 goto skip;
2571 if (!trylock_page(page))
2572 goto skip;
2574 if (page->mapping != mapping || !PageUptodate(page))
2575 goto unlock;
2577 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2578 if (page->index >= max_idx)
2579 goto unlock;
2581 if (file->f_ra.mmap_miss > 0)
2582 file->f_ra.mmap_miss--;
2584 vmf->address += (iter.index - last_pgoff) << PAGE_SHIFT;
2585 if (vmf->pte)
2586 vmf->pte += iter.index - last_pgoff;
2587 last_pgoff = iter.index;
2588 if (alloc_set_pte(vmf, NULL, page))
2589 goto unlock;
2590 unlock_page(page);
2591 goto next;
2592 unlock:
2593 unlock_page(page);
2594 skip:
2595 put_page(page);
2596 next:
2597 /* Huge page is mapped? No need to proceed. */
2598 if (pmd_trans_huge(*vmf->pmd))
2599 break;
2600 if (iter.index == end_pgoff)
2601 break;
2603 rcu_read_unlock();
2605 EXPORT_SYMBOL(filemap_map_pages);
2607 int filemap_page_mkwrite(struct vm_fault *vmf)
2609 struct page *page = vmf->page;
2610 struct inode *inode = file_inode(vmf->vma->vm_file);
2611 int ret = VM_FAULT_LOCKED;
2613 sb_start_pagefault(inode->i_sb);
2614 file_update_time(vmf->vma->vm_file);
2615 lock_page(page);
2616 if (page->mapping != inode->i_mapping) {
2617 unlock_page(page);
2618 ret = VM_FAULT_NOPAGE;
2619 goto out;
2622 * We mark the page dirty already here so that when freeze is in
2623 * progress, we are guaranteed that writeback during freezing will
2624 * see the dirty page and writeprotect it again.
2626 set_page_dirty(page);
2627 wait_for_stable_page(page);
2628 out:
2629 sb_end_pagefault(inode->i_sb);
2630 return ret;
2632 EXPORT_SYMBOL(filemap_page_mkwrite);
2634 const struct vm_operations_struct generic_file_vm_ops = {
2635 .fault = filemap_fault,
2636 .map_pages = filemap_map_pages,
2637 .page_mkwrite = filemap_page_mkwrite,
2640 /* This is used for a general mmap of a disk file */
2642 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2644 struct address_space *mapping = file->f_mapping;
2646 if (!mapping->a_ops->readpage)
2647 return -ENOEXEC;
2648 file_accessed(file);
2649 vma->vm_ops = &generic_file_vm_ops;
2650 return 0;
2654 * This is for filesystems which do not implement ->writepage.
2656 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2658 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2659 return -EINVAL;
2660 return generic_file_mmap(file, vma);
2662 #else
2663 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2665 return -ENOSYS;
2667 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2669 return -ENOSYS;
2671 #endif /* CONFIG_MMU */
2673 EXPORT_SYMBOL(generic_file_mmap);
2674 EXPORT_SYMBOL(generic_file_readonly_mmap);
2676 static struct page *wait_on_page_read(struct page *page)
2678 if (!IS_ERR(page)) {
2679 wait_on_page_locked(page);
2680 if (!PageUptodate(page)) {
2681 put_page(page);
2682 page = ERR_PTR(-EIO);
2685 return page;
2688 static struct page *do_read_cache_page(struct address_space *mapping,
2689 pgoff_t index,
2690 int (*filler)(void *, struct page *),
2691 void *data,
2692 gfp_t gfp)
2694 struct page *page;
2695 int err;
2696 repeat:
2697 page = find_get_page(mapping, index);
2698 if (!page) {
2699 page = __page_cache_alloc(gfp | __GFP_COLD);
2700 if (!page)
2701 return ERR_PTR(-ENOMEM);
2702 err = add_to_page_cache_lru(page, mapping, index, gfp);
2703 if (unlikely(err)) {
2704 put_page(page);
2705 if (err == -EEXIST)
2706 goto repeat;
2707 /* Presumably ENOMEM for radix tree node */
2708 return ERR_PTR(err);
2711 filler:
2712 err = filler(data, page);
2713 if (err < 0) {
2714 put_page(page);
2715 return ERR_PTR(err);
2718 page = wait_on_page_read(page);
2719 if (IS_ERR(page))
2720 return page;
2721 goto out;
2723 if (PageUptodate(page))
2724 goto out;
2727 * Page is not up to date and may be locked due one of the following
2728 * case a: Page is being filled and the page lock is held
2729 * case b: Read/write error clearing the page uptodate status
2730 * case c: Truncation in progress (page locked)
2731 * case d: Reclaim in progress
2733 * Case a, the page will be up to date when the page is unlocked.
2734 * There is no need to serialise on the page lock here as the page
2735 * is pinned so the lock gives no additional protection. Even if the
2736 * the page is truncated, the data is still valid if PageUptodate as
2737 * it's a race vs truncate race.
2738 * Case b, the page will not be up to date
2739 * Case c, the page may be truncated but in itself, the data may still
2740 * be valid after IO completes as it's a read vs truncate race. The
2741 * operation must restart if the page is not uptodate on unlock but
2742 * otherwise serialising on page lock to stabilise the mapping gives
2743 * no additional guarantees to the caller as the page lock is
2744 * released before return.
2745 * Case d, similar to truncation. If reclaim holds the page lock, it
2746 * will be a race with remove_mapping that determines if the mapping
2747 * is valid on unlock but otherwise the data is valid and there is
2748 * no need to serialise with page lock.
2750 * As the page lock gives no additional guarantee, we optimistically
2751 * wait on the page to be unlocked and check if it's up to date and
2752 * use the page if it is. Otherwise, the page lock is required to
2753 * distinguish between the different cases. The motivation is that we
2754 * avoid spurious serialisations and wakeups when multiple processes
2755 * wait on the same page for IO to complete.
2757 wait_on_page_locked(page);
2758 if (PageUptodate(page))
2759 goto out;
2761 /* Distinguish between all the cases under the safety of the lock */
2762 lock_page(page);
2764 /* Case c or d, restart the operation */
2765 if (!page->mapping) {
2766 unlock_page(page);
2767 put_page(page);
2768 goto repeat;
2771 /* Someone else locked and filled the page in a very small window */
2772 if (PageUptodate(page)) {
2773 unlock_page(page);
2774 goto out;
2776 goto filler;
2778 out:
2779 mark_page_accessed(page);
2780 return page;
2784 * read_cache_page - read into page cache, fill it if needed
2785 * @mapping: the page's address_space
2786 * @index: the page index
2787 * @filler: function to perform the read
2788 * @data: first arg to filler(data, page) function, often left as NULL
2790 * Read into the page cache. If a page already exists, and PageUptodate() is
2791 * not set, try to fill the page and wait for it to become unlocked.
2793 * If the page does not get brought uptodate, return -EIO.
2795 struct page *read_cache_page(struct address_space *mapping,
2796 pgoff_t index,
2797 int (*filler)(void *, struct page *),
2798 void *data)
2800 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2802 EXPORT_SYMBOL(read_cache_page);
2805 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2806 * @mapping: the page's address_space
2807 * @index: the page index
2808 * @gfp: the page allocator flags to use if allocating
2810 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2811 * any new page allocations done using the specified allocation flags.
2813 * If the page does not get brought uptodate, return -EIO.
2815 struct page *read_cache_page_gfp(struct address_space *mapping,
2816 pgoff_t index,
2817 gfp_t gfp)
2819 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2821 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2823 EXPORT_SYMBOL(read_cache_page_gfp);
2826 * Performs necessary checks before doing a write
2828 * Can adjust writing position or amount of bytes to write.
2829 * Returns appropriate error code that caller should return or
2830 * zero in case that write should be allowed.
2832 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2834 struct file *file = iocb->ki_filp;
2835 struct inode *inode = file->f_mapping->host;
2836 unsigned long limit = rlimit(RLIMIT_FSIZE);
2837 loff_t pos;
2839 if (!iov_iter_count(from))
2840 return 0;
2842 /* FIXME: this is for backwards compatibility with 2.4 */
2843 if (iocb->ki_flags & IOCB_APPEND)
2844 iocb->ki_pos = i_size_read(inode);
2846 pos = iocb->ki_pos;
2848 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2849 return -EINVAL;
2851 if (limit != RLIM_INFINITY) {
2852 if (iocb->ki_pos >= limit) {
2853 send_sig(SIGXFSZ, current, 0);
2854 return -EFBIG;
2856 iov_iter_truncate(from, limit - (unsigned long)pos);
2860 * LFS rule
2862 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2863 !(file->f_flags & O_LARGEFILE))) {
2864 if (pos >= MAX_NON_LFS)
2865 return -EFBIG;
2866 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2870 * Are we about to exceed the fs block limit ?
2872 * If we have written data it becomes a short write. If we have
2873 * exceeded without writing data we send a signal and return EFBIG.
2874 * Linus frestrict idea will clean these up nicely..
2876 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2877 return -EFBIG;
2879 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2880 return iov_iter_count(from);
2882 EXPORT_SYMBOL(generic_write_checks);
2884 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2885 loff_t pos, unsigned len, unsigned flags,
2886 struct page **pagep, void **fsdata)
2888 const struct address_space_operations *aops = mapping->a_ops;
2890 return aops->write_begin(file, mapping, pos, len, flags,
2891 pagep, fsdata);
2893 EXPORT_SYMBOL(pagecache_write_begin);
2895 int pagecache_write_end(struct file *file, struct address_space *mapping,
2896 loff_t pos, unsigned len, unsigned copied,
2897 struct page *page, void *fsdata)
2899 const struct address_space_operations *aops = mapping->a_ops;
2901 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2903 EXPORT_SYMBOL(pagecache_write_end);
2905 ssize_t
2906 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
2908 struct file *file = iocb->ki_filp;
2909 struct address_space *mapping = file->f_mapping;
2910 struct inode *inode = mapping->host;
2911 loff_t pos = iocb->ki_pos;
2912 ssize_t written;
2913 size_t write_len;
2914 pgoff_t end;
2916 write_len = iov_iter_count(from);
2917 end = (pos + write_len - 1) >> PAGE_SHIFT;
2919 if (iocb->ki_flags & IOCB_NOWAIT) {
2920 /* If there are pages to writeback, return */
2921 if (filemap_range_has_page(inode->i_mapping, pos,
2922 pos + iov_iter_count(from)))
2923 return -EAGAIN;
2924 } else {
2925 written = filemap_write_and_wait_range(mapping, pos,
2926 pos + write_len - 1);
2927 if (written)
2928 goto out;
2932 * After a write we want buffered reads to be sure to go to disk to get
2933 * the new data. We invalidate clean cached page from the region we're
2934 * about to write. We do this *before* the write so that we can return
2935 * without clobbering -EIOCBQUEUED from ->direct_IO().
2937 written = invalidate_inode_pages2_range(mapping,
2938 pos >> PAGE_SHIFT, end);
2940 * If a page can not be invalidated, return 0 to fall back
2941 * to buffered write.
2943 if (written) {
2944 if (written == -EBUSY)
2945 return 0;
2946 goto out;
2949 written = mapping->a_ops->direct_IO(iocb, from);
2952 * Finally, try again to invalidate clean pages which might have been
2953 * cached by non-direct readahead, or faulted in by get_user_pages()
2954 * if the source of the write was an mmap'ed region of the file
2955 * we're writing. Either one is a pretty crazy thing to do,
2956 * so we don't support it 100%. If this invalidation
2957 * fails, tough, the write still worked...
2959 * Most of the time we do not need this since dio_complete() will do
2960 * the invalidation for us. However there are some file systems that
2961 * do not end up with dio_complete() being called, so let's not break
2962 * them by removing it completely
2964 if (mapping->nrpages)
2965 invalidate_inode_pages2_range(mapping,
2966 pos >> PAGE_SHIFT, end);
2968 if (written > 0) {
2969 pos += written;
2970 write_len -= written;
2971 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2972 i_size_write(inode, pos);
2973 mark_inode_dirty(inode);
2975 iocb->ki_pos = pos;
2977 iov_iter_revert(from, write_len - iov_iter_count(from));
2978 out:
2979 return written;
2981 EXPORT_SYMBOL(generic_file_direct_write);
2984 * Find or create a page at the given pagecache position. Return the locked
2985 * page. This function is specifically for buffered writes.
2987 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2988 pgoff_t index, unsigned flags)
2990 struct page *page;
2991 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
2993 if (flags & AOP_FLAG_NOFS)
2994 fgp_flags |= FGP_NOFS;
2996 page = pagecache_get_page(mapping, index, fgp_flags,
2997 mapping_gfp_mask(mapping));
2998 if (page)
2999 wait_for_stable_page(page);
3001 return page;
3003 EXPORT_SYMBOL(grab_cache_page_write_begin);
3005 ssize_t generic_perform_write(struct file *file,
3006 struct iov_iter *i, loff_t pos)
3008 struct address_space *mapping = file->f_mapping;
3009 const struct address_space_operations *a_ops = mapping->a_ops;
3010 long status = 0;
3011 ssize_t written = 0;
3012 unsigned int flags = 0;
3014 do {
3015 struct page *page;
3016 unsigned long offset; /* Offset into pagecache page */
3017 unsigned long bytes; /* Bytes to write to page */
3018 size_t copied; /* Bytes copied from user */
3019 void *fsdata;
3021 offset = (pos & (PAGE_SIZE - 1));
3022 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3023 iov_iter_count(i));
3025 again:
3027 * Bring in the user page that we will copy from _first_.
3028 * Otherwise there's a nasty deadlock on copying from the
3029 * same page as we're writing to, without it being marked
3030 * up-to-date.
3032 * Not only is this an optimisation, but it is also required
3033 * to check that the address is actually valid, when atomic
3034 * usercopies are used, below.
3036 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3037 status = -EFAULT;
3038 break;
3041 if (fatal_signal_pending(current)) {
3042 status = -EINTR;
3043 break;
3046 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3047 &page, &fsdata);
3048 if (unlikely(status < 0))
3049 break;
3051 if (mapping_writably_mapped(mapping))
3052 flush_dcache_page(page);
3054 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3055 flush_dcache_page(page);
3057 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3058 page, fsdata);
3059 if (unlikely(status < 0))
3060 break;
3061 copied = status;
3063 cond_resched();
3065 iov_iter_advance(i, copied);
3066 if (unlikely(copied == 0)) {
3068 * If we were unable to copy any data at all, we must
3069 * fall back to a single segment length write.
3071 * If we didn't fallback here, we could livelock
3072 * because not all segments in the iov can be copied at
3073 * once without a pagefault.
3075 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3076 iov_iter_single_seg_count(i));
3077 goto again;
3079 pos += copied;
3080 written += copied;
3082 balance_dirty_pages_ratelimited(mapping);
3083 } while (iov_iter_count(i));
3085 return written ? written : status;
3087 EXPORT_SYMBOL(generic_perform_write);
3090 * __generic_file_write_iter - write data to a file
3091 * @iocb: IO state structure (file, offset, etc.)
3092 * @from: iov_iter with data to write
3094 * This function does all the work needed for actually writing data to a
3095 * file. It does all basic checks, removes SUID from the file, updates
3096 * modification times and calls proper subroutines depending on whether we
3097 * do direct IO or a standard buffered write.
3099 * It expects i_mutex to be grabbed unless we work on a block device or similar
3100 * object which does not need locking at all.
3102 * This function does *not* take care of syncing data in case of O_SYNC write.
3103 * A caller has to handle it. This is mainly due to the fact that we want to
3104 * avoid syncing under i_mutex.
3106 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3108 struct file *file = iocb->ki_filp;
3109 struct address_space * mapping = file->f_mapping;
3110 struct inode *inode = mapping->host;
3111 ssize_t written = 0;
3112 ssize_t err;
3113 ssize_t status;
3115 /* We can write back this queue in page reclaim */
3116 current->backing_dev_info = inode_to_bdi(inode);
3117 err = file_remove_privs(file);
3118 if (err)
3119 goto out;
3121 err = file_update_time(file);
3122 if (err)
3123 goto out;
3125 if (iocb->ki_flags & IOCB_DIRECT) {
3126 loff_t pos, endbyte;
3128 written = generic_file_direct_write(iocb, from);
3130 * If the write stopped short of completing, fall back to
3131 * buffered writes. Some filesystems do this for writes to
3132 * holes, for example. For DAX files, a buffered write will
3133 * not succeed (even if it did, DAX does not handle dirty
3134 * page-cache pages correctly).
3136 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3137 goto out;
3139 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3141 * If generic_perform_write() returned a synchronous error
3142 * then we want to return the number of bytes which were
3143 * direct-written, or the error code if that was zero. Note
3144 * that this differs from normal direct-io semantics, which
3145 * will return -EFOO even if some bytes were written.
3147 if (unlikely(status < 0)) {
3148 err = status;
3149 goto out;
3152 * We need to ensure that the page cache pages are written to
3153 * disk and invalidated to preserve the expected O_DIRECT
3154 * semantics.
3156 endbyte = pos + status - 1;
3157 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3158 if (err == 0) {
3159 iocb->ki_pos = endbyte + 1;
3160 written += status;
3161 invalidate_mapping_pages(mapping,
3162 pos >> PAGE_SHIFT,
3163 endbyte >> PAGE_SHIFT);
3164 } else {
3166 * We don't know how much we wrote, so just return
3167 * the number of bytes which were direct-written
3170 } else {
3171 written = generic_perform_write(file, from, iocb->ki_pos);
3172 if (likely(written > 0))
3173 iocb->ki_pos += written;
3175 out:
3176 current->backing_dev_info = NULL;
3177 return written ? written : err;
3179 EXPORT_SYMBOL(__generic_file_write_iter);
3182 * generic_file_write_iter - write data to a file
3183 * @iocb: IO state structure
3184 * @from: iov_iter with data to write
3186 * This is a wrapper around __generic_file_write_iter() to be used by most
3187 * filesystems. It takes care of syncing the file in case of O_SYNC file
3188 * and acquires i_mutex as needed.
3190 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3192 struct file *file = iocb->ki_filp;
3193 struct inode *inode = file->f_mapping->host;
3194 ssize_t ret;
3196 inode_lock(inode);
3197 ret = generic_write_checks(iocb, from);
3198 if (ret > 0)
3199 ret = __generic_file_write_iter(iocb, from);
3200 inode_unlock(inode);
3202 if (ret > 0)
3203 ret = generic_write_sync(iocb, ret);
3204 return ret;
3206 EXPORT_SYMBOL(generic_file_write_iter);
3209 * try_to_release_page() - release old fs-specific metadata on a page
3211 * @page: the page which the kernel is trying to free
3212 * @gfp_mask: memory allocation flags (and I/O mode)
3214 * The address_space is to try to release any data against the page
3215 * (presumably at page->private). If the release was successful, return '1'.
3216 * Otherwise return zero.
3218 * This may also be called if PG_fscache is set on a page, indicating that the
3219 * page is known to the local caching routines.
3221 * The @gfp_mask argument specifies whether I/O may be performed to release
3222 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3225 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3227 struct address_space * const mapping = page->mapping;
3229 BUG_ON(!PageLocked(page));
3230 if (PageWriteback(page))
3231 return 0;
3233 if (mapping && mapping->a_ops->releasepage)
3234 return mapping->a_ops->releasepage(page, gfp_mask);
3235 return try_to_free_buffers(page);
3238 EXPORT_SYMBOL(try_to_release_page);