3603 lines · 99.7 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0-only/* *	linux/mm/filemap.c * * Copyright (C) 1994-1999  Linus Torvalds */ /* * This file handles the generic file mmap semantics used by * most "normal" filesystems (but you don't /have/ to use this: * the NFS filesystem used to do this differently, for example) */#include <linux/export.h>#include <linux/compiler.h>#include <linux/dax.h>#include <linux/fs.h>#include <linux/sched/signal.h>#include <linux/uaccess.h>#include <linux/capability.h>#include <linux/kernel_stat.h>#include <linux/gfp.h>#include <linux/mm.h>#include <linux/swap.h>#include <linux/mman.h>#include <linux/pagemap.h>#include <linux/file.h>#include <linux/uio.h>#include <linux/error-injection.h>#include <linux/hash.h>#include <linux/writeback.h>#include <linux/backing-dev.h>#include <linux/pagevec.h>#include <linux/blkdev.h>#include <linux/security.h>#include <linux/cpuset.h>#include <linux/hugetlb.h>#include <linux/memcontrol.h>#include <linux/cleancache.h>#include <linux/shmem_fs.h>#include <linux/rmap.h>#include <linux/delayacct.h>#include <linux/psi.h>#include <linux/ramfs.h>#include <linux/page_idle.h>#include "internal.h" #define CREATE_TRACE_POINTS#include <trace/events/filemap.h> /* * FIXME: remove all knowledge of the buffer layer from the core VM */#include <linux/buffer_head.h> /* for try_to_free_buffers */ #include <asm/mman.h> /* * Shared mappings implemented 30.11.1994. It's not fully working yet, * though. * * Shared mappings now work. 15.8.1995  Bruno. * * finished 'unifying' the page and buffer cache and SMP-threaded the * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com> * * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de> */ /* * Lock ordering: * *  ->i_mmap_rwsem		(truncate_pagecache) *    ->private_lock		(__free_pte->__set_page_dirty_buffers) *      ->swap_lock		(exclusive_swap_page, others) *        ->i_pages lock * *  ->i_mutex *    ->i_mmap_rwsem		(truncate->unmap_mapping_range) * *  ->mmap_lock *    ->i_mmap_rwsem *      ->page_table_lock or pte_lock	(various, mainly in memory.c) *        ->i_pages lock	(arch-dependent flush_dcache_mmap_lock) * *  ->mmap_lock *    ->lock_page		(access_process_vm) * *  ->i_mutex			(generic_perform_write) *    ->mmap_lock		(fault_in_pages_readable->do_page_fault) * *  bdi->wb.list_lock *    sb_lock			(fs/fs-writeback.c) *    ->i_pages lock		(__sync_single_inode) * *  ->i_mmap_rwsem *    ->anon_vma.lock		(vma_adjust) * *  ->anon_vma.lock *    ->page_table_lock or pte_lock	(anon_vma_prepare and various) * *  ->page_table_lock or pte_lock *    ->swap_lock		(try_to_unmap_one) *    ->private_lock		(try_to_unmap_one) *    ->i_pages lock		(try_to_unmap_one) *    ->pgdat->lru_lock		(follow_page->mark_page_accessed) *    ->pgdat->lru_lock		(check_pte_range->isolate_lru_page) *    ->private_lock		(page_remove_rmap->set_page_dirty) *    ->i_pages lock		(page_remove_rmap->set_page_dirty) *    bdi.wb->list_lock		(page_remove_rmap->set_page_dirty) *    ->inode->i_lock		(page_remove_rmap->set_page_dirty) *    ->memcg->move_lock	(page_remove_rmap->lock_page_memcg) *    bdi.wb->list_lock		(zap_pte_range->set_page_dirty) *    ->inode->i_lock		(zap_pte_range->set_page_dirty) *    ->private_lock		(zap_pte_range->__set_page_dirty_buffers) * * ->i_mmap_rwsem *   ->tasklist_lock            (memory_failure, collect_procs_ao) */ static void page_cache_delete(struct address_space *mapping,				   struct page *page, void *shadow){	XA_STATE(xas, &mapping->i_pages, page->index);	unsigned int nr = 1; 	mapping_set_update(&xas, mapping); 	/* hugetlb pages are represented by a single entry in the xarray */	if (!PageHuge(page)) {		xas_set_order(&xas, page->index, compound_order(page));		nr = compound_nr(page);	} 	VM_BUG_ON_PAGE(!PageLocked(page), page);	VM_BUG_ON_PAGE(PageTail(page), page);	VM_BUG_ON_PAGE(nr != 1 && shadow, page); 	xas_store(&xas, shadow);	xas_init_marks(&xas); 	page->mapping = NULL;	/* Leave page->index set: truncation lookup relies upon it */ 	if (shadow) {		mapping->nrexceptional += nr;		/*		 * Make sure the nrexceptional update is committed before		 * the nrpages update so that final truncate racing		 * with reclaim does not see both counters 0 at the		 * same time and miss a shadow entry.		 */		smp_wmb();	}	mapping->nrpages -= nr;} static void unaccount_page_cache_page(struct address_space *mapping,				      struct page *page){	int nr; 	/*	 * if we're uptodate, flush out into the cleancache, otherwise	 * invalidate any existing cleancache entries.  We can't leave	 * stale data around in the cleancache once our page is gone	 */	if (PageUptodate(page) && PageMappedToDisk(page))		cleancache_put_page(page);	else		cleancache_invalidate_page(mapping, page); 	VM_BUG_ON_PAGE(PageTail(page), page);	VM_BUG_ON_PAGE(page_mapped(page), page);	if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {		int mapcount; 		pr_alert("BUG: Bad page cache in process %s  pfn:%05lx\n",			 current->comm, page_to_pfn(page));		dump_page(page, "still mapped when deleted");		dump_stack();		add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 		mapcount = page_mapcount(page);		if (mapping_exiting(mapping) &&		    page_count(page) >= mapcount + 2) {			/*			 * All vmas have already been torn down, so it's			 * a good bet that actually the page is unmapped,			 * and we'd prefer not to leak it: if we're wrong,			 * some other bad page check should catch it later.			 */			page_mapcount_reset(page);			page_ref_sub(page, mapcount);		}	} 	/* hugetlb pages do not participate in page cache accounting. */	if (PageHuge(page))		return; 	nr = thp_nr_pages(page); 	__mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);	if (PageSwapBacked(page)) {		__mod_lruvec_page_state(page, NR_SHMEM, -nr);		if (PageTransHuge(page))			__dec_node_page_state(page, NR_SHMEM_THPS);	} else if (PageTransHuge(page)) {		__dec_node_page_state(page, NR_FILE_THPS);		filemap_nr_thps_dec(mapping);	} 	/*	 * At this point page must be either written or cleaned by	 * truncate.  Dirty page here signals a bug and loss of	 * unwritten data.	 *	 * This fixes dirty accounting after removing the page entirely	 * but leaves PageDirty set: it has no effect for truncated	 * page and anyway will be cleared before returning page into	 * buddy allocator.	 */	if (WARN_ON_ONCE(PageDirty(page)))		account_page_cleaned(page, mapping, inode_to_wb(mapping->host));} /* * Delete a page from the page cache and free it. Caller has to make * sure the page is locked and that nobody else uses it - or that usage * is safe.  The caller must hold the i_pages lock. */void __delete_from_page_cache(struct page *page, void *shadow){	struct address_space *mapping = page->mapping; 	trace_mm_filemap_delete_from_page_cache(page); 	unaccount_page_cache_page(mapping, page);	page_cache_delete(mapping, page, shadow);} static void page_cache_free_page(struct address_space *mapping,				struct page *page){	void (*freepage)(struct page *); 	freepage = mapping->a_ops->freepage;	if (freepage)		freepage(page); 	if (PageTransHuge(page) && !PageHuge(page)) {		page_ref_sub(page, HPAGE_PMD_NR);		VM_BUG_ON_PAGE(page_count(page) <= 0, page);	} else {		put_page(page);	}} /** * delete_from_page_cache - delete page from page cache * @page: the page which the kernel is trying to remove from page cache * * This must be called only on pages that have been verified to be in the page * cache and locked.  It will never put the page into the free list, the caller * has a reference on the page. */void delete_from_page_cache(struct page *page){	struct address_space *mapping = page_mapping(page);	unsigned long flags; 	BUG_ON(!PageLocked(page));	xa_lock_irqsave(&mapping->i_pages, flags);	__delete_from_page_cache(page, NULL);	xa_unlock_irqrestore(&mapping->i_pages, flags); 	page_cache_free_page(mapping, page);}EXPORT_SYMBOL(delete_from_page_cache); /* * page_cache_delete_batch - delete several pages from page cache * @mapping: the mapping to which pages belong * @pvec: pagevec with pages to delete * * The function walks over mapping->i_pages and removes pages passed in @pvec * from the mapping. The function expects @pvec to be sorted by page index * and is optimised for it to be dense. * It tolerates holes in @pvec (mapping entries at those indices are not * modified). The function expects only THP head pages to be present in the * @pvec. * * The function expects the i_pages lock to be held. */static void page_cache_delete_batch(struct address_space *mapping,			     struct pagevec *pvec){	XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);	int total_pages = 0;	int i = 0;	struct page *page; 	mapping_set_update(&xas, mapping);	xas_for_each(&xas, page, ULONG_MAX) {		if (i >= pagevec_count(pvec))			break; 		/* A swap/dax/shadow entry got inserted? Skip it. */		if (xa_is_value(page))			continue;		/*		 * A page got inserted in our range? Skip it. We have our		 * pages locked so they are protected from being removed.		 * If we see a page whose index is higher than ours, it		 * means our page has been removed, which shouldn't be		 * possible because we're holding the PageLock.		 */		if (page != pvec->pages[i]) {			VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,					page);			continue;		} 		WARN_ON_ONCE(!PageLocked(page)); 		if (page->index == xas.xa_index)			page->mapping = NULL;		/* Leave page->index set: truncation lookup relies on it */ 		/*		 * Move to the next page in the vector if this is a regular		 * page or the index is of the last sub-page of this compound		 * page.		 */		if (page->index + compound_nr(page) - 1 == xas.xa_index)			i++;		xas_store(&xas, NULL);		total_pages++;	}	mapping->nrpages -= total_pages;} void delete_from_page_cache_batch(struct address_space *mapping,				  struct pagevec *pvec){	int i;	unsigned long flags; 	if (!pagevec_count(pvec))		return; 	xa_lock_irqsave(&mapping->i_pages, flags);	for (i = 0; i < pagevec_count(pvec); i++) {		trace_mm_filemap_delete_from_page_cache(pvec->pages[i]); 		unaccount_page_cache_page(mapping, pvec->pages[i]);	}	page_cache_delete_batch(mapping, pvec);	xa_unlock_irqrestore(&mapping->i_pages, flags); 	for (i = 0; i < pagevec_count(pvec); i++)		page_cache_free_page(mapping, pvec->pages[i]);} int filemap_check_errors(struct address_space *mapping){	int ret = 0;	/* Check for outstanding write errors */	if (test_bit(AS_ENOSPC, &mapping->flags) &&	    test_and_clear_bit(AS_ENOSPC, &mapping->flags))		ret = -ENOSPC;	if (test_bit(AS_EIO, &mapping->flags) &&	    test_and_clear_bit(AS_EIO, &mapping->flags))		ret = -EIO;	return ret;}EXPORT_SYMBOL(filemap_check_errors); static int filemap_check_and_keep_errors(struct address_space *mapping){	/* Check for outstanding write errors */	if (test_bit(AS_EIO, &mapping->flags))		return -EIO;	if (test_bit(AS_ENOSPC, &mapping->flags))		return -ENOSPC;	return 0;} /** * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range * @mapping:	address space structure to write * @start:	offset in bytes where the range starts * @end:	offset in bytes where the range ends (inclusive) * @sync_mode:	enable synchronous operation * * Start writeback against all of a mapping's dirty pages that lie * within the byte offsets <start, end> inclusive. * * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as * opposed to a regular memory cleansing writeback.  The difference between * these two operations is that if a dirty page/buffer is encountered, it must * be waited upon, and not just skipped over. * * Return: %0 on success, negative error code otherwise. */int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,				loff_t end, int sync_mode){	int ret;	struct writeback_control wbc = {		.sync_mode = sync_mode,		.nr_to_write = LONG_MAX,		.range_start = start,		.range_end = end,	}; 	if (!mapping_cap_writeback_dirty(mapping) ||	    !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))		return 0; 	wbc_attach_fdatawrite_inode(&wbc, mapping->host);	ret = do_writepages(mapping, &wbc);	wbc_detach_inode(&wbc);	return ret;} static inline int __filemap_fdatawrite(struct address_space *mapping,	int sync_mode){	return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);} int filemap_fdatawrite(struct address_space *mapping){	return __filemap_fdatawrite(mapping, WB_SYNC_ALL);}EXPORT_SYMBOL(filemap_fdatawrite); int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,				loff_t end){	return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);}EXPORT_SYMBOL(filemap_fdatawrite_range); /** * filemap_flush - mostly a non-blocking flush * @mapping:	target address_space * * This is a mostly non-blocking flush.  Not suitable for data-integrity * purposes - I/O may not be started against all dirty pages. * * Return: %0 on success, negative error code otherwise. */int filemap_flush(struct address_space *mapping){	return __filemap_fdatawrite(mapping, WB_SYNC_NONE);}EXPORT_SYMBOL(filemap_flush); /** * filemap_range_has_page - check if a page exists in range. * @mapping:           address space within which to check * @start_byte:        offset in bytes where the range starts * @end_byte:          offset in bytes where the range ends (inclusive) * * Find at least one page in the range supplied, usually used to check if * direct writing in this range will trigger a writeback. * * Return: %true if at least one page exists in the specified range, * %false otherwise. */bool filemap_range_has_page(struct address_space *mapping,			   loff_t start_byte, loff_t end_byte){	struct page *page;	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);	pgoff_t max = end_byte >> PAGE_SHIFT; 	if (end_byte < start_byte)		return false; 	rcu_read_lock();	for (;;) {		page = xas_find(&xas, max);		if (xas_retry(&xas, page))			continue;		/* Shadow entries don't count */		if (xa_is_value(page))			continue;		/*		 * We don't need to try to pin this page; we're about to		 * release the RCU lock anyway.  It is enough to know that		 * there was a page here recently.		 */		break;	}	rcu_read_unlock(); 	return page != NULL;

Lines 1–500 of 3603.