1 // SPDX-License-Identifier: GPL-2.0-only
3 * mm/truncate.c - code for taking down pages from address_spaces
5 * Copyright (C) 2002, Linus Torvalds
7 * 10Sep2002 Andrew Morton
11 #include <linux/kernel.h>
12 #include <linux/backing-dev.h>
13 #include <linux/dax.h>
14 #include <linux/gfp.h>
16 #include <linux/swap.h>
17 #include <linux/export.h>
18 #include <linux/pagemap.h>
19 #include <linux/highmem.h>
20 #include <linux/pagevec.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/buffer_head.h> /* grr. try_to_release_page,
24 #include <linux/shmem_fs.h>
25 #include <linux/cleancache.h>
26 #include <linux/rmap.h>
30 * Regular page slots are stabilized by the page lock even without the tree
31 * itself locked. These unlocked entries need verification under the tree
34 static inline void __clear_shadow_entry(struct address_space *mapping,
35 pgoff_t index, void *entry)
37 XA_STATE(xas, &mapping->i_pages, index);
39 xas_set_update(&xas, workingset_update_node);
40 if (xas_load(&xas) != entry)
42 xas_store(&xas, NULL);
43 mapping->nrexceptional--;
46 static void clear_shadow_entry(struct address_space *mapping, pgoff_t index,
49 xa_lock_irq(&mapping->i_pages);
50 __clear_shadow_entry(mapping, index, entry);
51 xa_unlock_irq(&mapping->i_pages);
55 * Unconditionally remove exceptional entries. Usually called from truncate
56 * path. Note that the pagevec may be altered by this function by removing
57 * exceptional entries similar to what pagevec_remove_exceptionals does.
59 static void truncate_exceptional_pvec_entries(struct address_space *mapping,
60 struct pagevec *pvec, pgoff_t *indices)
65 /* Handled by shmem itself */
66 if (shmem_mapping(mapping))
69 for (j = 0; j < pagevec_count(pvec); j++)
70 if (xa_is_value(pvec->pages[j]))
73 if (j == pagevec_count(pvec))
76 dax = dax_mapping(mapping);
78 xa_lock_irq(&mapping->i_pages);
80 for (i = j; i < pagevec_count(pvec); i++) {
81 struct page *page = pvec->pages[i];
82 pgoff_t index = indices[i];
84 if (!xa_is_value(page)) {
85 pvec->pages[j++] = page;
90 dax_delete_mapping_entry(mapping, index);
94 __clear_shadow_entry(mapping, index, page);
98 xa_unlock_irq(&mapping->i_pages);
103 * Invalidate exceptional entry if easily possible. This handles exceptional
104 * entries for invalidate_inode_pages().
106 static int invalidate_exceptional_entry(struct address_space *mapping,
107 pgoff_t index, void *entry)
109 /* Handled by shmem itself, or for DAX we do nothing. */
110 if (shmem_mapping(mapping) || dax_mapping(mapping))
112 clear_shadow_entry(mapping, index, entry);
117 * Invalidate exceptional entry if clean. This handles exceptional entries for
118 * invalidate_inode_pages2() so for DAX it evicts only clean entries.
120 static int invalidate_exceptional_entry2(struct address_space *mapping,
121 pgoff_t index, void *entry)
123 /* Handled by shmem itself */
124 if (shmem_mapping(mapping))
126 if (dax_mapping(mapping))
127 return dax_invalidate_mapping_entry_sync(mapping, index);
128 clear_shadow_entry(mapping, index, entry);
133 * do_invalidatepage - invalidate part or all of a page
134 * @page: the page which is affected
135 * @offset: start of the range to invalidate
136 * @length: length of the range to invalidate
138 * do_invalidatepage() is called when all or part of the page has become
139 * invalidated by a truncate operation.
141 * do_invalidatepage() does not have to release all buffers, but it must
142 * ensure that no dirty buffer is left outside @offset and that no I/O
143 * is underway against any of the blocks which are outside the truncation
144 * point. Because the caller is about to free (and possibly reuse) those
147 void do_invalidatepage(struct page *page, unsigned int offset,
150 void (*invalidatepage)(struct page *, unsigned int, unsigned int);
152 invalidatepage = page->mapping->a_ops->invalidatepage;
155 invalidatepage = block_invalidatepage;
158 (*invalidatepage)(page, offset, length);
162 * If truncate cannot remove the fs-private metadata from the page, the page
163 * becomes orphaned. It will be left on the LRU and may even be mapped into
164 * user pagetables if we're racing with filemap_fault().
166 * We need to bail out if page->mapping is no longer equal to the original
167 * mapping. This happens a) when the VM reclaimed the page while we waited on
168 * its lock, b) when a concurrent invalidate_mapping_pages got there first and
169 * c) when tmpfs swizzles a page between a tmpfs inode and swapper_space.
172 truncate_cleanup_page(struct address_space *mapping, struct page *page)
174 if (page_mapped(page)) {
175 unsigned int nr = thp_nr_pages(page);
176 unmap_mapping_pages(mapping, page->index, nr, false);
179 if (page_has_private(page))
180 do_invalidatepage(page, 0, thp_size(page));
183 * Some filesystems seem to re-dirty the page even after
184 * the VM has canceled the dirty bit (eg ext3 journaling).
185 * Hence dirty accounting check is placed after invalidation.
187 cancel_dirty_page(page);
188 ClearPageMappedToDisk(page);
192 * This is for invalidate_mapping_pages(). That function can be called at
193 * any time, and is not supposed to throw away dirty pages. But pages can
194 * be marked dirty at any time too, so use remove_mapping which safely
195 * discards clean, unused pages.
197 * Returns non-zero if the page was successfully invalidated.
200 invalidate_complete_page(struct address_space *mapping, struct page *page)
204 if (page->mapping != mapping)
207 if (page_has_private(page) && !try_to_release_page(page, 0))
210 ret = remove_mapping(mapping, page);
215 int truncate_inode_page(struct address_space *mapping, struct page *page)
217 VM_BUG_ON_PAGE(PageTail(page), page);
219 if (page->mapping != mapping)
222 truncate_cleanup_page(mapping, page);
223 delete_from_page_cache(page);
228 * Used to get rid of pages on hardware memory corruption.
230 int generic_error_remove_page(struct address_space *mapping, struct page *page)
235 * Only punch for normal data pages for now.
236 * Handling other types like directories would need more auditing.
238 if (!S_ISREG(mapping->host->i_mode))
240 return truncate_inode_page(mapping, page);
242 EXPORT_SYMBOL(generic_error_remove_page);
245 * Safely invalidate one page from its pagecache mapping.
246 * It only drops clean, unused pages. The page must be locked.
248 * Returns 1 if the page is successfully invalidated, otherwise 0.
250 int invalidate_inode_page(struct page *page)
252 struct address_space *mapping = page_mapping(page);
255 if (PageDirty(page) || PageWriteback(page))
257 if (page_mapped(page))
259 return invalidate_complete_page(mapping, page);
263 * truncate_inode_pages_range - truncate range of pages specified by start & end byte offsets
264 * @mapping: mapping to truncate
265 * @lstart: offset from which to truncate
266 * @lend: offset to which to truncate (inclusive)
268 * Truncate the page cache, removing the pages that are between
269 * specified offsets (and zeroing out partial pages
270 * if lstart or lend + 1 is not page aligned).
272 * Truncate takes two passes - the first pass is nonblocking. It will not
273 * block on page locks and it will not block on writeback. The second pass
274 * will wait. This is to prevent as much IO as possible in the affected region.
275 * The first pass will remove most pages, so the search cost of the second pass
278 * We pass down the cache-hot hint to the page freeing code. Even if the
279 * mapping is large, it is probably the case that the final pages are the most
280 * recently touched, and freeing happens in ascending file offset order.
282 * Note that since ->invalidatepage() accepts range to invalidate
283 * truncate_inode_pages_range is able to handle cases where lend + 1 is not
284 * page aligned properly.
286 void truncate_inode_pages_range(struct address_space *mapping,
287 loff_t lstart, loff_t lend)
289 pgoff_t start; /* inclusive */
290 pgoff_t end; /* exclusive */
291 unsigned int partial_start; /* inclusive */
292 unsigned int partial_end; /* exclusive */
294 pgoff_t indices[PAGEVEC_SIZE];
298 if (mapping->nrpages == 0 && mapping->nrexceptional == 0)
301 /* Offsets within partial pages */
302 partial_start = lstart & (PAGE_SIZE - 1);
303 partial_end = (lend + 1) & (PAGE_SIZE - 1);
306 * 'start' and 'end' always covers the range of pages to be fully
307 * truncated. Partial pages are covered with 'partial_start' at the
308 * start of the range and 'partial_end' at the end of the range.
309 * Note that 'end' is exclusive while 'lend' is inclusive.
311 start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
314 * lend == -1 indicates end-of-file so we have to set 'end'
315 * to the highest possible pgoff_t and since the type is
316 * unsigned we're using -1.
320 end = (lend + 1) >> PAGE_SHIFT;
324 while (index < end && find_lock_entries(mapping, index, end - 1,
326 index = indices[pagevec_count(&pvec) - 1] + 1;
327 truncate_exceptional_pvec_entries(mapping, &pvec, indices);
328 for (i = 0; i < pagevec_count(&pvec); i++)
329 truncate_cleanup_page(mapping, pvec.pages[i]);
330 delete_from_page_cache_batch(mapping, &pvec);
331 for (i = 0; i < pagevec_count(&pvec); i++)
332 unlock_page(pvec.pages[i]);
333 pagevec_release(&pvec);
338 struct page *page = find_lock_page(mapping, start - 1);
340 unsigned int top = PAGE_SIZE;
342 /* Truncation within a single page */
346 wait_on_page_writeback(page);
347 zero_user_segment(page, partial_start, top);
348 cleancache_invalidate_page(mapping, page);
349 if (page_has_private(page))
350 do_invalidatepage(page, partial_start,
351 top - partial_start);
357 struct page *page = find_lock_page(mapping, end);
359 wait_on_page_writeback(page);
360 zero_user_segment(page, 0, partial_end);
361 cleancache_invalidate_page(mapping, page);
362 if (page_has_private(page))
363 do_invalidatepage(page, 0,
370 * If the truncation happened within a single page no pages
371 * will be released, just zeroed, so we can bail out now.
379 if (!find_get_entries(mapping, index, end - 1, &pvec,
381 /* If all gone from start onwards, we're done */
384 /* Otherwise restart to make sure all gone */
389 for (i = 0; i < pagevec_count(&pvec); i++) {
390 struct page *page = pvec.pages[i];
392 /* We rely upon deletion not changing page->index */
395 if (xa_is_value(page))
399 WARN_ON(page_to_index(page) != index);
400 wait_on_page_writeback(page);
401 truncate_inode_page(mapping, page);
404 truncate_exceptional_pvec_entries(mapping, &pvec, indices);
405 pagevec_release(&pvec);
410 cleancache_invalidate_inode(mapping);
412 EXPORT_SYMBOL(truncate_inode_pages_range);
415 * truncate_inode_pages - truncate *all* the pages from an offset
416 * @mapping: mapping to truncate
417 * @lstart: offset from which to truncate
419 * Called under (and serialised by) inode->i_mutex.
421 * Note: When this function returns, there can be a page in the process of
422 * deletion (inside __delete_from_page_cache()) in the specified range. Thus
423 * mapping->nrpages can be non-zero when this function returns even after
424 * truncation of the whole mapping.
426 void truncate_inode_pages(struct address_space *mapping, loff_t lstart)
428 truncate_inode_pages_range(mapping, lstart, (loff_t)-1);
430 EXPORT_SYMBOL(truncate_inode_pages);
433 * truncate_inode_pages_final - truncate *all* pages before inode dies
434 * @mapping: mapping to truncate
436 * Called under (and serialized by) inode->i_mutex.
438 * Filesystems have to use this in the .evict_inode path to inform the
439 * VM that this is the final truncate and the inode is going away.
441 void truncate_inode_pages_final(struct address_space *mapping)
443 unsigned long nrexceptional;
444 unsigned long nrpages;
447 * Page reclaim can not participate in regular inode lifetime
448 * management (can't call iput()) and thus can race with the
449 * inode teardown. Tell it when the address space is exiting,
450 * so that it does not install eviction information after the
451 * final truncate has begun.
453 mapping_set_exiting(mapping);
456 * When reclaim installs eviction entries, it increases
457 * nrexceptional first, then decreases nrpages. Make sure we see
458 * this in the right order or we might miss an entry.
460 nrpages = mapping->nrpages;
462 nrexceptional = mapping->nrexceptional;
464 if (nrpages || nrexceptional) {
466 * As truncation uses a lockless tree lookup, cycle
467 * the tree lock to make sure any ongoing tree
468 * modification that does not see AS_EXITING is
469 * completed before starting the final truncate.
471 xa_lock_irq(&mapping->i_pages);
472 xa_unlock_irq(&mapping->i_pages);
476 * Cleancache needs notification even if there are no pages or shadow
479 truncate_inode_pages(mapping, 0);
481 EXPORT_SYMBOL(truncate_inode_pages_final);
483 static unsigned long __invalidate_mapping_pages(struct address_space *mapping,
484 pgoff_t start, pgoff_t end, unsigned long *nr_pagevec)
486 pgoff_t indices[PAGEVEC_SIZE];
488 pgoff_t index = start;
490 unsigned long count = 0;
494 while (find_lock_entries(mapping, index, end, &pvec, indices)) {
495 for (i = 0; i < pagevec_count(&pvec); i++) {
496 struct page *page = pvec.pages[i];
498 /* We rely upon deletion not changing page->index */
501 if (xa_is_value(page)) {
502 invalidate_exceptional_entry(mapping, index,
506 index += thp_nr_pages(page) - 1;
508 ret = invalidate_inode_page(page);
511 * Invalidation is a hint that the page is no longer
512 * of interest and try to speed up its reclaim.
515 deactivate_file_page(page);
516 /* It is likely on the pagevec of a remote CPU */
522 pagevec_remove_exceptionals(&pvec);
523 pagevec_release(&pvec);
531 * invalidate_mapping_pages - Invalidate all the unlocked pages of one inode
532 * @mapping: the address_space which holds the pages to invalidate
533 * @start: the offset 'from' which to invalidate
534 * @end: the offset 'to' which to invalidate (inclusive)
536 * This function only removes the unlocked pages, if you want to
537 * remove all the pages of one inode, you must call truncate_inode_pages.
539 * invalidate_mapping_pages() will not block on IO activity. It will not
540 * invalidate pages which are dirty, locked, under writeback or mapped into
543 * Return: the number of the pages that were invalidated
545 unsigned long invalidate_mapping_pages(struct address_space *mapping,
546 pgoff_t start, pgoff_t end)
548 return __invalidate_mapping_pages(mapping, start, end, NULL);
550 EXPORT_SYMBOL(invalidate_mapping_pages);
553 * invalidate_mapping_pagevec - Invalidate all the unlocked pages of one inode
554 * @mapping: the address_space which holds the pages to invalidate
555 * @start: the offset 'from' which to invalidate
556 * @end: the offset 'to' which to invalidate (inclusive)
557 * @nr_pagevec: invalidate failed page number for caller
559 * This helper is similar to invalidate_mapping_pages(), except that it accounts
560 * for pages that are likely on a pagevec and counts them in @nr_pagevec, which
561 * will be used by the caller.
563 void invalidate_mapping_pagevec(struct address_space *mapping,
564 pgoff_t start, pgoff_t end, unsigned long *nr_pagevec)
566 __invalidate_mapping_pages(mapping, start, end, nr_pagevec);
570 * This is like invalidate_complete_page(), except it ignores the page's
571 * refcount. We do this because invalidate_inode_pages2() needs stronger
572 * invalidation guarantees, and cannot afford to leave pages behind because
573 * shrink_page_list() has a temp ref on them, or because they're transiently
574 * sitting in the lru_cache_add() pagevecs.
577 invalidate_complete_page2(struct address_space *mapping, struct page *page)
581 if (page->mapping != mapping)
584 if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL))
587 xa_lock_irqsave(&mapping->i_pages, flags);
591 BUG_ON(page_has_private(page));
592 __delete_from_page_cache(page, NULL);
593 xa_unlock_irqrestore(&mapping->i_pages, flags);
595 if (mapping->a_ops->freepage)
596 mapping->a_ops->freepage(page);
598 put_page(page); /* pagecache ref */
601 xa_unlock_irqrestore(&mapping->i_pages, flags);
605 static int do_launder_page(struct address_space *mapping, struct page *page)
607 if (!PageDirty(page))
609 if (page->mapping != mapping || mapping->a_ops->launder_page == NULL)
611 return mapping->a_ops->launder_page(page);
615 * invalidate_inode_pages2_range - remove range of pages from an address_space
616 * @mapping: the address_space
617 * @start: the page offset 'from' which to invalidate
618 * @end: the page offset 'to' which to invalidate (inclusive)
620 * Any pages which are found to be mapped into pagetables are unmapped prior to
623 * Return: -EBUSY if any pages could not be invalidated.
625 int invalidate_inode_pages2_range(struct address_space *mapping,
626 pgoff_t start, pgoff_t end)
628 pgoff_t indices[PAGEVEC_SIZE];
634 int did_range_unmap = 0;
636 if (mapping->nrpages == 0 && mapping->nrexceptional == 0)
641 while (find_get_entries(mapping, index, end, &pvec, indices)) {
642 for (i = 0; i < pagevec_count(&pvec); i++) {
643 struct page *page = pvec.pages[i];
645 /* We rely upon deletion not changing page->index */
648 if (xa_is_value(page)) {
649 if (!invalidate_exceptional_entry2(mapping,
656 WARN_ON(page_to_index(page) != index);
657 if (page->mapping != mapping) {
661 wait_on_page_writeback(page);
662 if (page_mapped(page)) {
663 if (!did_range_unmap) {
665 * Zap the rest of the file in one hit.
667 unmap_mapping_pages(mapping, index,
668 (1 + end - index), false);
674 unmap_mapping_pages(mapping, index,
678 BUG_ON(page_mapped(page));
679 ret2 = do_launder_page(mapping, page);
681 if (!invalidate_complete_page2(mapping, page))
688 pagevec_remove_exceptionals(&pvec);
689 pagevec_release(&pvec);
694 * For DAX we invalidate page tables after invalidating page cache. We
695 * could invalidate page tables while invalidating each entry however
696 * that would be expensive. And doing range unmapping before doesn't
697 * work as we have no cheap way to find whether page cache entry didn't
698 * get remapped later.
700 if (dax_mapping(mapping)) {
701 unmap_mapping_pages(mapping, start, end - start + 1, false);
704 cleancache_invalidate_inode(mapping);
707 EXPORT_SYMBOL_GPL(invalidate_inode_pages2_range);
710 * invalidate_inode_pages2 - remove all pages from an address_space
711 * @mapping: the address_space
713 * Any pages which are found to be mapped into pagetables are unmapped prior to
716 * Return: -EBUSY if any pages could not be invalidated.
718 int invalidate_inode_pages2(struct address_space *mapping)
720 return invalidate_inode_pages2_range(mapping, 0, -1);
722 EXPORT_SYMBOL_GPL(invalidate_inode_pages2);
725 * truncate_pagecache - unmap and remove pagecache that has been truncated
727 * @newsize: new file size
729 * inode's new i_size must already be written before truncate_pagecache
732 * This function should typically be called before the filesystem
733 * releases resources associated with the freed range (eg. deallocates
734 * blocks). This way, pagecache will always stay logically coherent
735 * with on-disk format, and the filesystem would not have to deal with
736 * situations such as writepage being called for a page that has already
737 * had its underlying blocks deallocated.
739 void truncate_pagecache(struct inode *inode, loff_t newsize)
741 struct address_space *mapping = inode->i_mapping;
742 loff_t holebegin = round_up(newsize, PAGE_SIZE);
745 * unmap_mapping_range is called twice, first simply for
746 * efficiency so that truncate_inode_pages does fewer
747 * single-page unmaps. However after this first call, and
748 * before truncate_inode_pages finishes, it is possible for
749 * private pages to be COWed, which remain after
750 * truncate_inode_pages finishes, hence the second
751 * unmap_mapping_range call must be made for correctness.
753 unmap_mapping_range(mapping, holebegin, 0, 1);
754 truncate_inode_pages(mapping, newsize);
755 unmap_mapping_range(mapping, holebegin, 0, 1);
757 EXPORT_SYMBOL(truncate_pagecache);
760 * truncate_setsize - update inode and pagecache for a new file size
762 * @newsize: new file size
764 * truncate_setsize updates i_size and performs pagecache truncation (if
765 * necessary) to @newsize. It will be typically be called from the filesystem's
766 * setattr function when ATTR_SIZE is passed in.
768 * Must be called with a lock serializing truncates and writes (generally
769 * i_mutex but e.g. xfs uses a different lock) and before all filesystem
770 * specific block truncation has been performed.
772 void truncate_setsize(struct inode *inode, loff_t newsize)
774 loff_t oldsize = inode->i_size;
776 i_size_write(inode, newsize);
777 if (newsize > oldsize)
778 pagecache_isize_extended(inode, oldsize, newsize);
779 truncate_pagecache(inode, newsize);
781 EXPORT_SYMBOL(truncate_setsize);
784 * pagecache_isize_extended - update pagecache after extension of i_size
785 * @inode: inode for which i_size was extended
786 * @from: original inode size
787 * @to: new inode size
789 * Handle extension of inode size either caused by extending truncate or by
790 * write starting after current i_size. We mark the page straddling current
791 * i_size RO so that page_mkwrite() is called on the nearest write access to
792 * the page. This way filesystem can be sure that page_mkwrite() is called on
793 * the page before user writes to the page via mmap after the i_size has been
796 * The function must be called after i_size is updated so that page fault
797 * coming after we unlock the page will already see the new i_size.
798 * The function must be called while we still hold i_mutex - this not only
799 * makes sure i_size is stable but also that userspace cannot observe new
800 * i_size value before we are prepared to store mmap writes at new inode size.
802 void pagecache_isize_extended(struct inode *inode, loff_t from, loff_t to)
804 int bsize = i_blocksize(inode);
809 WARN_ON(to > inode->i_size);
811 if (from >= to || bsize == PAGE_SIZE)
813 /* Page straddling @from will not have any hole block created? */
814 rounded_from = round_up(from, bsize);
815 if (to <= rounded_from || !(rounded_from & (PAGE_SIZE - 1)))
818 index = from >> PAGE_SHIFT;
819 page = find_lock_page(inode->i_mapping, index);
820 /* Page not cached? Nothing to do */
824 * See clear_page_dirty_for_io() for details why set_page_dirty()
827 if (page_mkclean(page))
828 set_page_dirty(page);
832 EXPORT_SYMBOL(pagecache_isize_extended);
835 * truncate_pagecache_range - unmap and remove pagecache that is hole-punched
837 * @lstart: offset of beginning of hole
838 * @lend: offset of last byte of hole
840 * This function should typically be called before the filesystem
841 * releases resources associated with the freed range (eg. deallocates
842 * blocks). This way, pagecache will always stay logically coherent
843 * with on-disk format, and the filesystem would not have to deal with
844 * situations such as writepage being called for a page that has already
845 * had its underlying blocks deallocated.
847 void truncate_pagecache_range(struct inode *inode, loff_t lstart, loff_t lend)
849 struct address_space *mapping = inode->i_mapping;
850 loff_t unmap_start = round_up(lstart, PAGE_SIZE);
851 loff_t unmap_end = round_down(1 + lend, PAGE_SIZE) - 1;
853 * This rounding is currently just for example: unmap_mapping_range
854 * expands its hole outwards, whereas we want it to contract the hole
855 * inwards. However, existing callers of truncate_pagecache_range are
856 * doing their own page rounding first. Note that unmap_mapping_range
857 * allows holelen 0 for all, and we allow lend -1 for end of file.
861 * Unlike in truncate_pagecache, unmap_mapping_range is called only
862 * once (before truncating pagecache), and without "even_cows" flag:
863 * hole-punching should not remove private COWed pages from the hole.
865 if ((u64)unmap_end > (u64)unmap_start)
866 unmap_mapping_range(mapping, unmap_start,
867 1 + unmap_end - unmap_start, 0);
868 truncate_inode_pages_range(mapping, lstart, lend);
870 EXPORT_SYMBOL(truncate_pagecache_range);