xref: /linux/mm/page_isolation.c (revision f4e98954234b104c23902ee5bb4e59be6f9904a7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/mm/page_isolation.c
4  */
5 
6 #include <linux/mm.h>
7 #include <linux/page-isolation.h>
8 #include <linux/pageblock-flags.h>
9 #include <linux/memory.h>
10 #include <linux/hugetlb.h>
11 #include <linux/page_owner.h>
12 #include <linux/migrate.h>
13 #include "internal.h"
14 
15 #define CREATE_TRACE_POINTS
16 #include <trace/events/page_isolation.h>
17 
18 bool page_is_unmovable(struct zone *zone, struct page *page,
19 		enum pb_isolate_mode mode, unsigned long *step)
20 {
21 	/*
22 	 * Both, bootmem allocations and memory holes are marked
23 	 * PG_reserved and are unmovable. We can even have unmovable
24 	 * allocations inside ZONE_MOVABLE, for example when
25 	 * specifying "movablecore".
26 	 */
27 	if (PageReserved(page))
28 		return true;
29 
30 	/*
31 	 * If the zone is movable and we have ruled out all reserved
32 	 * pages then it should be reasonably safe to assume the rest
33 	 * is movable.
34 	 */
35 	if (zone_idx(zone) == ZONE_MOVABLE)
36 		return false;
37 
38 	/*
39 	 * Hugepages are not in LRU lists, but they're movable.
40 	 * THPs are on the LRU, but need to be counted as #small pages.
41 	 * We need not scan over tail pages because we don't
42 	 * handle each tail page individually in migration.
43 	 */
44 	if (PageHuge(page) || PageCompound(page)) {
45 		struct folio *folio = page_folio(page);
46 
47 		if (folio_test_hugetlb(folio)) {
48 			struct hstate *h;
49 
50 			if (!IS_ENABLED(CONFIG_ARCH_ENABLE_HUGEPAGE_MIGRATION))
51 				return true;
52 
53 			/*
54 			 * The huge page may be freed so can not
55 			 * use folio_hstate() directly.
56 			 */
57 			h = size_to_hstate(folio_size(folio));
58 			if (h && !hugepage_migration_supported(h))
59 				return true;
60 
61 		} else if (!folio_test_lru(folio)) {
62 			return true;
63 		}
64 
65 		*step = folio_nr_pages(folio) - folio_page_idx(folio, page);
66 		return false;
67 	}
68 
69 	/*
70 	 * We can't use page_count without pin a page
71 	 * because another CPU can free compound page.
72 	 * This check already skips compound tails of THP
73 	 * because their page->_refcount is zero at all time.
74 	 */
75 	if (!page_ref_count(page)) {
76 		if (PageBuddy(page))
77 			*step = (1 << buddy_order(page));
78 		return false;
79 	}
80 
81 	/*
82 	 * The HWPoisoned page may be not in buddy system, and
83 	 * page_count() is not 0.
84 	 */
85 	if ((mode == PB_ISOLATE_MODE_MEM_OFFLINE) && PageHWPoison(page))
86 		return false;
87 
88 	/*
89 	 * We treat all PageOffline() pages as movable when offlining
90 	 * to give drivers a chance to decrement their reference count
91 	 * in MEM_GOING_OFFLINE in order to indicate that these pages
92 	 * can be offlined as there are no direct references anymore.
93 	 * For actually unmovable PageOffline() where the driver does
94 	 * not support this, we will fail later when trying to actually
95 	 * move these pages that still have a reference count > 0.
96 	 * (false negatives in this function only)
97 	 */
98 	if ((mode == PB_ISOLATE_MODE_MEM_OFFLINE) && PageOffline(page))
99 		return false;
100 
101 	if (PageLRU(page) || page_has_movable_ops(page))
102 		return false;
103 
104 	/*
105 	 * If there are RECLAIMABLE pages, we need to check
106 	 * it.  But now, memory offline itself doesn't call
107 	 * shrink_node_slabs() and it still to be fixed.
108 	 */
109 	return true;
110 }
111 
112 /*
113  * This function checks whether the range [start_pfn, end_pfn) includes
114  * unmovable pages or not. The range must fall into a single pageblock and
115  * consequently belong to a single zone.
116  *
117  * PageLRU check without isolation or lru_lock could race so that
118  * MIGRATE_MOVABLE block might include unmovable pages. Similarly, pages
119  * with movable_ops can only be identified some time after they were
120  * allocated. So you can't expect this function should be exact.
121  *
122  * Returns a page without holding a reference. If the caller wants to
123  * dereference that page (e.g., dumping), it has to make sure that it
124  * cannot get removed (e.g., via memory unplug) concurrently.
125  *
126  */
127 static struct page *has_unmovable_pages(unsigned long start_pfn, unsigned long end_pfn,
128 				enum pb_isolate_mode mode)
129 {
130 	struct page *page = pfn_to_page(start_pfn);
131 	struct zone *zone = page_zone(page);
132 
133 	VM_BUG_ON(pageblock_start_pfn(start_pfn) !=
134 		  pageblock_start_pfn(end_pfn - 1));
135 
136 	if (is_migrate_cma_page(page)) {
137 		/*
138 		 * CMA allocations (alloc_contig_range) really need to mark
139 		 * isolate CMA pageblocks even when they are not movable in fact
140 		 * so consider them movable here.
141 		 */
142 		if (mode == PB_ISOLATE_MODE_CMA_ALLOC)
143 			return NULL;
144 
145 		return page;
146 	}
147 
148 	while (start_pfn < end_pfn) {
149 		unsigned long step = 1;
150 
151 		page = pfn_to_page(start_pfn);
152 		if (page_is_unmovable(zone, page, mode, &step))
153 			return page;
154 
155 		start_pfn += step;
156 	}
157 	return NULL;
158 }
159 
160 /*
161  * This function set pageblock migratetype to isolate if no unmovable page is
162  * present in [start_pfn, end_pfn). The pageblock must intersect with
163  * [start_pfn, end_pfn).
164  */
165 static int set_migratetype_isolate(struct page *page, enum pb_isolate_mode mode,
166 			unsigned long start_pfn, unsigned long end_pfn)
167 {
168 	struct zone *zone = page_zone(page);
169 	struct page *unmovable;
170 	unsigned long check_unmovable_start, check_unmovable_end;
171 
172 	if (PageUnaccepted(page))
173 		accept_page(page);
174 
175 	scoped_guard(spinlock_irqsave, &zone->lock) {
176 		/*
177 		 * We assume the caller intended to SET migrate type to
178 		 * isolate. If it is already set, then someone else must have
179 		 * raced and set it before us.
180 		 */
181 		if (is_migrate_isolate_page(page))
182 			return -EBUSY;
183 
184 		/*
185 		 * FIXME: Now, memory hotplug doesn't call shrink_slab() by
186 		 * itself. We just check MOVABLE pages.
187 		 *
188 		 * Pass the intersection of [start_pfn, end_pfn) and the page's
189 		 * pageblock to avoid redundant checks.
190 		 */
191 		check_unmovable_start = max(page_to_pfn(page), start_pfn);
192 		check_unmovable_end = min(pageblock_end_pfn(page_to_pfn(page)),
193 					  end_pfn);
194 
195 		unmovable = has_unmovable_pages(check_unmovable_start,
196 				check_unmovable_end, mode);
197 		if (!unmovable) {
198 			if (!pageblock_isolate_and_move_free_pages(zone, page))
199 				return -EBUSY;
200 			zone->nr_isolate_pageblock++;
201 			return 0;
202 		}
203 	}
204 	if (mode == PB_ISOLATE_MODE_MEM_OFFLINE) {
205 		/*
206 		 * printk() with zone->lock held will likely trigger a
207 		 * lockdep splat, so defer it here.
208 		 */
209 		dump_page(unmovable, "unmovable page");
210 	}
211 
212 	return -EBUSY;
213 }
214 
215 static void unset_migratetype_isolate(struct page *page)
216 {
217 	struct zone *zone;
218 	bool isolated_page = false;
219 	unsigned int order;
220 	struct page *buddy;
221 
222 	zone = page_zone(page);
223 	guard(spinlock_irqsave)(&zone->lock);
224 	if (!is_migrate_isolate_page(page))
225 		return;
226 
227 	/*
228 	 * Because freepage with more than pageblock_order on isolated
229 	 * pageblock is restricted to merge due to freepage counting problem,
230 	 * it is possible that there is free buddy page.
231 	 * move_freepages_block() doesn't care of merge so we need other
232 	 * approach in order to merge them. Isolation and free will make
233 	 * these pages to be merged.
234 	 */
235 	if (PageBuddy(page)) {
236 		order = buddy_order(page);
237 		if (order >= pageblock_order && order < MAX_PAGE_ORDER) {
238 			buddy = find_buddy_page_pfn(page, page_to_pfn(page),
239 						    order, NULL);
240 			if (buddy && !is_migrate_isolate_page(buddy)) {
241 				isolated_page = !!__isolate_free_page(page, order);
242 				/*
243 				 * Isolating a free page in an isolated pageblock
244 				 * is expected to always work as watermarks don't
245 				 * apply here.
246 				 */
247 				VM_WARN_ON(!isolated_page);
248 			}
249 		}
250 	}
251 
252 	/*
253 	 * If we isolate freepage with more than pageblock_order, there
254 	 * should be no freepage in the range, so we could avoid costly
255 	 * pageblock scanning for freepage moving.
256 	 *
257 	 * We didn't actually touch any of the isolated pages, so place them
258 	 * to the tail of the freelist. This is an optimization for memory
259 	 * onlining - just onlined memory won't immediately be considered for
260 	 * allocation.
261 	 */
262 	if (!isolated_page) {
263 		/*
264 		 * Isolating this block already succeeded, so this
265 		 * should not fail on zone boundaries.
266 		 */
267 		WARN_ON_ONCE(!pageblock_unisolate_and_move_free_pages(zone, page));
268 	} else {
269 		clear_pageblock_isolate(page);
270 		__putback_isolated_page(page, order, get_pageblock_migratetype(page));
271 	}
272 	zone->nr_isolate_pageblock--;
273 }
274 
275 static inline struct page *
276 __first_valid_page(unsigned long pfn, unsigned long nr_pages)
277 {
278 	int i;
279 
280 	for (i = 0; i < nr_pages; i++) {
281 		struct page *page;
282 
283 		page = pfn_to_online_page(pfn + i);
284 		if (!page)
285 			continue;
286 		return page;
287 	}
288 	return NULL;
289 }
290 
291 /**
292  * isolate_single_pageblock() -- tries to isolate a pageblock that might be
293  * within a free or in-use page.
294  * @boundary_pfn:		pageblock-aligned pfn that a page might cross
295  * @mode:			isolation mode
296  * @isolate_before:	isolate the pageblock before the boundary_pfn
297  * @skip_isolation:	the flag to skip the pageblock isolation in second
298  *			isolate_single_pageblock()
299  *
300  * Free and in-use pages can be as big as MAX_PAGE_ORDER and contain more than one
301  * pageblock. When not all pageblocks within a page are isolated at the same
302  * time, free page accounting can go wrong. For example, in the case of
303  * MAX_PAGE_ORDER = pageblock_order + 1, a MAX_PAGE_ORDER page has two
304  * pageblocks.
305  * [      MAX_PAGE_ORDER         ]
306  * [  pageblock0  |  pageblock1  ]
307  * When either pageblock is isolated, if it is a free page, the page is not
308  * split into separate migratetype lists, which is supposed to; if it is an
309  * in-use page and freed later, __free_one_page() does not split the free page
310  * either. The function handles this by splitting the free page or migrating
311  * the in-use page then splitting the free page.
312  */
313 static int isolate_single_pageblock(unsigned long boundary_pfn,
314 			enum pb_isolate_mode mode, bool isolate_before,
315 			bool skip_isolation)
316 {
317 	unsigned long start_pfn;
318 	unsigned long isolate_pageblock;
319 	unsigned long pfn;
320 	struct zone *zone;
321 	int ret;
322 
323 	VM_BUG_ON(!pageblock_aligned(boundary_pfn));
324 
325 	if (isolate_before)
326 		isolate_pageblock = boundary_pfn - pageblock_nr_pages;
327 	else
328 		isolate_pageblock = boundary_pfn;
329 
330 	/*
331 	 * scan at the beginning of MAX_ORDER_NR_PAGES aligned range to avoid
332 	 * only isolating a subset of pageblocks from a bigger than pageblock
333 	 * free or in-use page. Also make sure all to-be-isolated pageblocks
334 	 * are within the same zone.
335 	 */
336 	zone  = page_zone(pfn_to_page(isolate_pageblock));
337 	start_pfn  = max(ALIGN_DOWN(isolate_pageblock, MAX_ORDER_NR_PAGES),
338 				      zone->zone_start_pfn);
339 
340 	if (skip_isolation) {
341 		VM_BUG_ON(!get_pageblock_isolate(pfn_to_page(isolate_pageblock)));
342 	} else {
343 		ret = set_migratetype_isolate(pfn_to_page(isolate_pageblock),
344 				mode, isolate_pageblock,
345 				isolate_pageblock + pageblock_nr_pages);
346 
347 		if (ret)
348 			return ret;
349 	}
350 
351 	/*
352 	 * Bail out early when the to-be-isolated pageblock does not form
353 	 * a free or in-use page across boundary_pfn:
354 	 *
355 	 * 1. isolate before boundary_pfn: the page after is not online
356 	 * 2. isolate after boundary_pfn: the page before is not online
357 	 *
358 	 * This also ensures correctness. Without it, when isolate after
359 	 * boundary_pfn and [start_pfn, boundary_pfn) are not online,
360 	 * __first_valid_page() will return unexpected NULL in the for loop
361 	 * below.
362 	 */
363 	if (isolate_before) {
364 		if (!pfn_to_online_page(boundary_pfn))
365 			return 0;
366 	} else {
367 		if (!pfn_to_online_page(boundary_pfn - 1))
368 			return 0;
369 	}
370 
371 	for (pfn = start_pfn; pfn < boundary_pfn;) {
372 		struct page *page = __first_valid_page(pfn, boundary_pfn - pfn);
373 
374 		VM_BUG_ON(!page);
375 		pfn = page_to_pfn(page);
376 
377 		if (PageUnaccepted(page)) {
378 			pfn += MAX_ORDER_NR_PAGES;
379 			continue;
380 		}
381 
382 		if (PageBuddy(page)) {
383 			int order = buddy_order(page);
384 
385 			/* pageblock_isolate_and_move_free_pages() handled this */
386 			VM_WARN_ON_ONCE(pfn + (1 << order) > boundary_pfn);
387 
388 			pfn += 1UL << order;
389 			continue;
390 		}
391 
392 		/*
393 		 * If a compound page is straddling our block, attempt
394 		 * to migrate it out of the way.
395 		 *
396 		 * We don't have to worry about this creating a large
397 		 * free page that straddles into our block: gigantic
398 		 * pages are freed as order-0 chunks, and LRU pages
399 		 * (currently) do not exceed pageblock_order.
400 		 *
401 		 * The block of interest has already been marked
402 		 * MIGRATE_ISOLATE above, so when migration is done it
403 		 * will free its pages onto the correct freelists.
404 		 */
405 		if (PageCompound(page)) {
406 			struct page *head = compound_head(page);
407 			unsigned long head_pfn = page_to_pfn(head);
408 			unsigned long nr_pages = compound_nr(head);
409 
410 			if (head_pfn + nr_pages <= boundary_pfn ||
411 			    PageHuge(page)) {
412 				pfn = head_pfn + nr_pages;
413 				continue;
414 			}
415 
416 			/*
417 			 * These pages are movable too, but they're
418 			 * not expected to exceed pageblock_order.
419 			 *
420 			 * Let us know when they do, so we can add
421 			 * proper free and split handling for them.
422 			 */
423 			VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
424 			VM_WARN_ON_ONCE_PAGE(page_has_movable_ops(page), page);
425 
426 			goto failed;
427 		}
428 
429 		pfn++;
430 	}
431 	return 0;
432 failed:
433 	/* restore the original migratetype */
434 	if (!skip_isolation)
435 		unset_migratetype_isolate(pfn_to_page(isolate_pageblock));
436 	return -EBUSY;
437 }
438 
439 /**
440  * start_isolate_page_range() - mark page range MIGRATE_ISOLATE
441  * @start_pfn:		The first PFN of the range to be isolated.
442  * @end_pfn:		The last PFN of the range to be isolated.
443  * @mode:		isolation mode
444  *
445  * Making page-allocation-type to be MIGRATE_ISOLATE means free pages in
446  * the range will never be allocated. Any free pages and pages freed in the
447  * future will not be allocated again. If specified range includes migrate types
448  * other than MOVABLE or CMA, this will fail with -EBUSY. For isolating all
449  * pages in the range finally, the caller have to free all pages in the range.
450  * test_page_isolated() can be used for test it.
451  *
452  * The function first tries to isolate the pageblocks at the beginning and end
453  * of the range, since there might be pages across the range boundaries.
454  * Afterwards, it isolates the rest of the range.
455  *
456  * There is no high level synchronization mechanism that prevents two threads
457  * from trying to isolate overlapping ranges. If this happens, one thread
458  * will notice pageblocks in the overlapping range already set to isolate.
459  * This happens in set_migratetype_isolate, and set_migratetype_isolate
460  * returns an error. We then clean up by restoring the migration type on
461  * pageblocks we may have modified and return -EBUSY to caller. This
462  * prevents two threads from simultaneously working on overlapping ranges.
463  *
464  * Please note that there is no strong synchronization with the page allocator
465  * either. Pages might be freed while their page blocks are marked ISOLATED.
466  * A call to drain_all_pages() after isolation can flush most of them. However
467  * in some cases pages might still end up on pcp lists and that would allow
468  * for their allocation even when they are in fact isolated already. Depending
469  * on how strong of a guarantee the caller needs, zone_pcp_disable/enable()
470  * might be used to flush and disable pcplist before isolation and enable after
471  * unisolation.
472  *
473  * Return: 0 on success and -EBUSY if any part of range cannot be isolated.
474  */
475 int start_isolate_page_range(unsigned long start_pfn, unsigned long end_pfn,
476 			     enum pb_isolate_mode mode)
477 {
478 	unsigned long pfn;
479 	struct page *page;
480 	/* isolation is done at page block granularity */
481 	unsigned long isolate_start = pageblock_start_pfn(start_pfn);
482 	unsigned long isolate_end = pageblock_align(end_pfn);
483 	int ret;
484 	bool skip_isolation = false;
485 
486 	/* isolate [isolate_start, isolate_start + pageblock_nr_pages) pageblock */
487 	ret = isolate_single_pageblock(isolate_start, mode, false,
488 			skip_isolation);
489 	if (ret)
490 		return ret;
491 
492 	if (isolate_start == isolate_end - pageblock_nr_pages)
493 		skip_isolation = true;
494 
495 	/* isolate [isolate_end - pageblock_nr_pages, isolate_end) pageblock */
496 	ret = isolate_single_pageblock(isolate_end, mode, true, skip_isolation);
497 	if (ret) {
498 		unset_migratetype_isolate(pfn_to_page(isolate_start));
499 		return ret;
500 	}
501 
502 	/* skip isolated pageblocks at the beginning and end */
503 	for (pfn = isolate_start + pageblock_nr_pages;
504 	     pfn < isolate_end - pageblock_nr_pages;
505 	     pfn += pageblock_nr_pages) {
506 		page = __first_valid_page(pfn, pageblock_nr_pages);
507 		if (page && set_migratetype_isolate(page, mode, start_pfn,
508 					end_pfn)) {
509 			undo_isolate_page_range(isolate_start, pfn);
510 			unset_migratetype_isolate(
511 				pfn_to_page(isolate_end - pageblock_nr_pages));
512 			return -EBUSY;
513 		}
514 	}
515 	return 0;
516 }
517 
518 /**
519  * undo_isolate_page_range - undo effects of start_isolate_page_range()
520  * @start_pfn:		The first PFN of the isolated range
521  * @end_pfn:		The last PFN of the isolated range
522  *
523  * This finds and unsets every MIGRATE_ISOLATE page block in the given range
524  */
525 void undo_isolate_page_range(unsigned long start_pfn, unsigned long end_pfn)
526 {
527 	unsigned long pfn;
528 	struct page *page;
529 	unsigned long isolate_start = pageblock_start_pfn(start_pfn);
530 	unsigned long isolate_end = pageblock_align(end_pfn);
531 
532 	for (pfn = isolate_start;
533 	     pfn < isolate_end;
534 	     pfn += pageblock_nr_pages) {
535 		page = __first_valid_page(pfn, pageblock_nr_pages);
536 		if (!page || !is_migrate_isolate_page(page))
537 			continue;
538 		unset_migratetype_isolate(page);
539 	}
540 }
541 /*
542  * Test all pages in the range is free(means isolated) or not.
543  * all pages in [start_pfn...end_pfn) must be in the same zone.
544  * zone->lock must be held before call this.
545  *
546  * Returns the last tested pfn.
547  */
548 static unsigned long
549 __test_page_isolated_in_pageblock(unsigned long pfn, unsigned long end_pfn,
550 				  enum pb_isolate_mode mode)
551 {
552 	struct page *page;
553 
554 	while (pfn < end_pfn) {
555 		page = pfn_to_page(pfn);
556 		if (PageBuddy(page))
557 			/*
558 			 * If the page is on a free list, it has to be on
559 			 * the correct MIGRATE_ISOLATE freelist. There is no
560 			 * simple way to verify that as VM_BUG_ON(), though.
561 			 */
562 			pfn += 1 << buddy_order(page);
563 		else if ((mode == PB_ISOLATE_MODE_MEM_OFFLINE) &&
564 			 PageHWPoison(page))
565 			/* A HWPoisoned page cannot be also PageBuddy */
566 			pfn++;
567 		else if ((mode == PB_ISOLATE_MODE_MEM_OFFLINE) &&
568 			 PageOffline(page) && !page_count(page))
569 			/*
570 			 * The responsible driver agreed to skip PageOffline()
571 			 * pages when offlining memory by dropping its
572 			 * reference in MEM_GOING_OFFLINE.
573 			 */
574 			pfn++;
575 		else
576 			break;
577 	}
578 
579 	return pfn;
580 }
581 
582 /**
583  * test_pages_isolated - check if pageblocks in range are isolated
584  * @start_pfn:		The first PFN of the isolated range
585  * @end_pfn:		The first PFN *after* the isolated range
586  * @mode:		Testing mode
587  *
588  * This tests if all in the specified range are free.
589  *
590  * If %PB_ISOLATE_MODE_MEM_OFFLINE specified in @mode, it will consider
591  * poisoned and offlined pages free as well.
592  *
593  * Caller must ensure the requested range doesn't span zones.
594  *
595  * Returns 0 if true, -EBUSY if one or more pages are in use.
596  */
597 int test_pages_isolated(unsigned long start_pfn, unsigned long end_pfn,
598 			enum pb_isolate_mode mode)
599 {
600 	unsigned long pfn, flags;
601 	struct page *page;
602 	struct zone *zone;
603 	int ret;
604 
605 	/*
606 	 * Due to the deferred freeing of hugetlb folios, the hugepage folios may
607 	 * not immediately release to the buddy system. This can cause PageBuddy()
608 	 * to fail in __test_page_isolated_in_pageblock(). To ensure that the
609 	 * hugetlb folios are properly released back to the buddy system, we
610 	 * invoke the wait_for_freed_hugetlb_folios() function to wait for the
611 	 * release to complete.
612 	 */
613 	wait_for_freed_hugetlb_folios();
614 
615 	/*
616 	 * Note: pageblock_nr_pages != MAX_PAGE_ORDER. Then, chunks of free
617 	 * pages are not aligned to pageblock_nr_pages.
618 	 * Then we just check migratetype first.
619 	 */
620 	for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
621 		page = __first_valid_page(pfn, pageblock_nr_pages);
622 		if (page && !is_migrate_isolate_page(page))
623 			break;
624 	}
625 	page = __first_valid_page(start_pfn, end_pfn - start_pfn);
626 	if ((pfn < end_pfn) || !page) {
627 		ret = -EBUSY;
628 		goto out;
629 	}
630 
631 	/* Check all pages are free or marked as ISOLATED */
632 	zone = page_zone(page);
633 	spin_lock_irqsave(&zone->lock, flags);
634 	pfn = __test_page_isolated_in_pageblock(start_pfn, end_pfn, mode);
635 	spin_unlock_irqrestore(&zone->lock, flags);
636 
637 	ret = pfn < end_pfn ? -EBUSY : 0;
638 
639 out:
640 	trace_test_pages_isolated(start_pfn, end_pfn, pfn);
641 
642 	return ret;
643 }
644