• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * linux/mm/compaction.c
3  *
4  * Memory compaction for the reduction of external fragmentation. Note that
5  * this heavily depends upon page migration to do all the real heavy
6  * lifting
7  *
8  * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
9  */
10 #include <linux/swap.h>
11 #include <linux/migrate.h>
12 #include <linux/compaction.h>
13 #include <linux/mm_inline.h>
14 #include <linux/backing-dev.h>
15 #include <linux/sysctl.h>
16 #include <linux/sysfs.h>
17 #include <linux/balloon_compaction.h>
18 #include <linux/page-isolation.h>
19 #include "internal.h"
20 
21 #ifdef CONFIG_COMPACTION
count_compact_event(enum vm_event_item item)22 static inline void count_compact_event(enum vm_event_item item)
23 {
24 	count_vm_event(item);
25 }
26 
count_compact_events(enum vm_event_item item,long delta)27 static inline void count_compact_events(enum vm_event_item item, long delta)
28 {
29 	count_vm_events(item, delta);
30 }
31 #else
32 #define count_compact_event(item) do { } while (0)
33 #define count_compact_events(item, delta) do { } while (0)
34 #endif
35 
36 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
37 
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/compaction.h>
40 
release_freepages(struct list_head * freelist)41 static unsigned long release_freepages(struct list_head *freelist)
42 {
43 	struct page *page, *next;
44 	unsigned long count = 0;
45 
46 	list_for_each_entry_safe(page, next, freelist, lru) {
47 		list_del(&page->lru);
48 		__free_page(page);
49 		count++;
50 	}
51 
52 	return count;
53 }
54 
map_pages(struct list_head * list)55 static void map_pages(struct list_head *list)
56 {
57 	struct page *page;
58 
59 	list_for_each_entry(page, list, lru) {
60 		arch_alloc_page(page, 0);
61 		kernel_map_pages(page, 1, 1);
62 	}
63 }
64 
migrate_async_suitable(int migratetype)65 static inline bool migrate_async_suitable(int migratetype)
66 {
67 	return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
68 }
69 
70 /*
71  * Check that the whole (or subset of) a pageblock given by the interval of
72  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
73  * with the migration of free compaction scanner. The scanners then need to
74  * use only pfn_valid_within() check for arches that allow holes within
75  * pageblocks.
76  *
77  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
78  *
79  * It's possible on some configurations to have a setup like node0 node1 node0
80  * i.e. it's possible that all pages within a zones range of pages do not
81  * belong to a single zone. We assume that a border between node0 and node1
82  * can occur within a single pageblock, but not a node0 node1 node0
83  * interleaving within a single pageblock. It is therefore sufficient to check
84  * the first and last page of a pageblock and avoid checking each individual
85  * page in a pageblock.
86  */
pageblock_pfn_to_page(unsigned long start_pfn,unsigned long end_pfn,struct zone * zone)87 static struct page *pageblock_pfn_to_page(unsigned long start_pfn,
88 				unsigned long end_pfn, struct zone *zone)
89 {
90 	struct page *start_page;
91 	struct page *end_page;
92 
93 	/* end_pfn is one past the range we are checking */
94 	end_pfn--;
95 
96 	if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
97 		return NULL;
98 
99 	start_page = pfn_to_page(start_pfn);
100 
101 	if (page_zone(start_page) != zone)
102 		return NULL;
103 
104 	end_page = pfn_to_page(end_pfn);
105 
106 	/* This gives a shorter code than deriving page_zone(end_page) */
107 	if (page_zone_id(start_page) != page_zone_id(end_page))
108 		return NULL;
109 
110 	return start_page;
111 }
112 
113 #ifdef CONFIG_COMPACTION
114 /* Returns true if the pageblock should be scanned for pages to isolate. */
isolation_suitable(struct compact_control * cc,struct page * page)115 static inline bool isolation_suitable(struct compact_control *cc,
116 					struct page *page)
117 {
118 	if (cc->ignore_skip_hint)
119 		return true;
120 
121 	return !get_pageblock_skip(page);
122 }
123 
124 /*
125  * This function is called to clear all cached information on pageblocks that
126  * should be skipped for page isolation when the migrate and free page scanner
127  * meet.
128  */
__reset_isolation_suitable(struct zone * zone)129 static void __reset_isolation_suitable(struct zone *zone)
130 {
131 	unsigned long start_pfn = zone->zone_start_pfn;
132 	unsigned long end_pfn = zone_end_pfn(zone);
133 	unsigned long pfn;
134 
135 	zone->compact_cached_migrate_pfn[0] = start_pfn;
136 	zone->compact_cached_migrate_pfn[1] = start_pfn;
137 	zone->compact_cached_free_pfn = end_pfn;
138 	zone->compact_blockskip_flush = false;
139 
140 	/* Walk the zone and mark every pageblock as suitable for isolation */
141 	for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
142 		struct page *page;
143 
144 		cond_resched();
145 
146 		if (!pfn_valid(pfn))
147 			continue;
148 
149 		page = pfn_to_page(pfn);
150 		if (zone != page_zone(page))
151 			continue;
152 
153 		clear_pageblock_skip(page);
154 	}
155 }
156 
reset_isolation_suitable(pg_data_t * pgdat)157 void reset_isolation_suitable(pg_data_t *pgdat)
158 {
159 	int zoneid;
160 
161 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
162 		struct zone *zone = &pgdat->node_zones[zoneid];
163 		if (!populated_zone(zone))
164 			continue;
165 
166 		/* Only flush if a full compaction finished recently */
167 		if (zone->compact_blockskip_flush)
168 			__reset_isolation_suitable(zone);
169 	}
170 }
171 
172 /*
173  * If no pages were isolated then mark this pageblock to be skipped in the
174  * future. The information is later cleared by __reset_isolation_suitable().
175  */
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long nr_isolated,bool migrate_scanner)176 static void update_pageblock_skip(struct compact_control *cc,
177 			struct page *page, unsigned long nr_isolated,
178 			bool migrate_scanner)
179 {
180 	struct zone *zone = cc->zone;
181 	unsigned long pfn;
182 
183 	if (cc->ignore_skip_hint)
184 		return;
185 
186 	if (!page)
187 		return;
188 
189 	if (nr_isolated)
190 		return;
191 
192 	set_pageblock_skip(page);
193 
194 	pfn = page_to_pfn(page);
195 
196 	/* Update where async and sync compaction should restart */
197 	if (migrate_scanner) {
198 		if (cc->finished_update_migrate)
199 			return;
200 		if (pfn > zone->compact_cached_migrate_pfn[0])
201 			zone->compact_cached_migrate_pfn[0] = pfn;
202 		if (cc->mode != MIGRATE_ASYNC &&
203 		    pfn > zone->compact_cached_migrate_pfn[1])
204 			zone->compact_cached_migrate_pfn[1] = pfn;
205 	} else {
206 		if (cc->finished_update_free)
207 			return;
208 		if (pfn < zone->compact_cached_free_pfn)
209 			zone->compact_cached_free_pfn = pfn;
210 	}
211 }
212 #else
isolation_suitable(struct compact_control * cc,struct page * page)213 static inline bool isolation_suitable(struct compact_control *cc,
214 					struct page *page)
215 {
216 	return true;
217 }
218 
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long nr_isolated,bool migrate_scanner)219 static void update_pageblock_skip(struct compact_control *cc,
220 			struct page *page, unsigned long nr_isolated,
221 			bool migrate_scanner)
222 {
223 }
224 #endif /* CONFIG_COMPACTION */
225 
226 /*
227  * Compaction requires the taking of some coarse locks that are potentially
228  * very heavily contended. For async compaction, back out if the lock cannot
229  * be taken immediately. For sync compaction, spin on the lock if needed.
230  *
231  * Returns true if the lock is held
232  * Returns false if the lock is not held and compaction should abort
233  */
compact_trylock_irqsave(spinlock_t * lock,unsigned long * flags,struct compact_control * cc)234 static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
235 						struct compact_control *cc)
236 {
237 	if (cc->mode == MIGRATE_ASYNC) {
238 		if (!spin_trylock_irqsave(lock, *flags)) {
239 			cc->contended = COMPACT_CONTENDED_LOCK;
240 			return false;
241 		}
242 	} else {
243 		spin_lock_irqsave(lock, *flags);
244 	}
245 
246 	return true;
247 }
248 
249 /*
250  * Compaction requires the taking of some coarse locks that are potentially
251  * very heavily contended. The lock should be periodically unlocked to avoid
252  * having disabled IRQs for a long time, even when there is nobody waiting on
253  * the lock. It might also be that allowing the IRQs will result in
254  * need_resched() becoming true. If scheduling is needed, async compaction
255  * aborts. Sync compaction schedules.
256  * Either compaction type will also abort if a fatal signal is pending.
257  * In either case if the lock was locked, it is dropped and not regained.
258  *
259  * Returns true if compaction should abort due to fatal signal pending, or
260  *		async compaction due to need_resched()
261  * Returns false when compaction can continue (sync compaction might have
262  *		scheduled)
263  */
compact_unlock_should_abort(spinlock_t * lock,unsigned long flags,bool * locked,struct compact_control * cc)264 static bool compact_unlock_should_abort(spinlock_t *lock,
265 		unsigned long flags, bool *locked, struct compact_control *cc)
266 {
267 	if (*locked) {
268 		spin_unlock_irqrestore(lock, flags);
269 		*locked = false;
270 	}
271 
272 	if (fatal_signal_pending(current)) {
273 		cc->contended = COMPACT_CONTENDED_SCHED;
274 		return true;
275 	}
276 
277 	if (need_resched()) {
278 		if (cc->mode == MIGRATE_ASYNC) {
279 			cc->contended = COMPACT_CONTENDED_SCHED;
280 			return true;
281 		}
282 		cond_resched();
283 	}
284 
285 	return false;
286 }
287 
288 /*
289  * Aside from avoiding lock contention, compaction also periodically checks
290  * need_resched() and either schedules in sync compaction or aborts async
291  * compaction. This is similar to what compact_unlock_should_abort() does, but
292  * is used where no lock is concerned.
293  *
294  * Returns false when no scheduling was needed, or sync compaction scheduled.
295  * Returns true when async compaction should abort.
296  */
compact_should_abort(struct compact_control * cc)297 static inline bool compact_should_abort(struct compact_control *cc)
298 {
299 	/* async compaction aborts if contended */
300 	if (need_resched()) {
301 		if (cc->mode == MIGRATE_ASYNC) {
302 			cc->contended = COMPACT_CONTENDED_SCHED;
303 			return true;
304 		}
305 
306 		cond_resched();
307 	}
308 
309 	return false;
310 }
311 
312 /* Returns true if the page is within a block suitable for migration to */
suitable_migration_target(struct page * page)313 static bool suitable_migration_target(struct page *page)
314 {
315 	/* If the page is a large free page, then disallow migration */
316 	if (PageBuddy(page)) {
317 		/*
318 		 * We are checking page_order without zone->lock taken. But
319 		 * the only small danger is that we skip a potentially suitable
320 		 * pageblock, so it's not worth to check order for valid range.
321 		 */
322 		if (page_order_unsafe(page) >= pageblock_order)
323 			return false;
324 	}
325 
326 	/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
327 	if (migrate_async_suitable(get_pageblock_migratetype(page)))
328 		return true;
329 
330 	/* Otherwise skip the block */
331 	return false;
332 }
333 
334 /*
335  * Isolate free pages onto a private freelist. If @strict is true, will abort
336  * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
337  * (even though it may still end up isolating some pages).
338  */
isolate_freepages_block(struct compact_control * cc,unsigned long * start_pfn,unsigned long end_pfn,struct list_head * freelist,bool strict)339 static unsigned long isolate_freepages_block(struct compact_control *cc,
340 				unsigned long *start_pfn,
341 				unsigned long end_pfn,
342 				struct list_head *freelist,
343 				bool strict)
344 {
345 	int nr_scanned = 0, total_isolated = 0;
346 	struct page *cursor, *valid_page = NULL;
347 	unsigned long flags = 0;
348 	bool locked = false;
349 	unsigned long blockpfn = *start_pfn;
350 
351 	cursor = pfn_to_page(blockpfn);
352 
353 	/* Isolate free pages. */
354 	for (; blockpfn < end_pfn; blockpfn++, cursor++) {
355 		int isolated, i;
356 		struct page *page = cursor;
357 
358 		/*
359 		 * Periodically drop the lock (if held) regardless of its
360 		 * contention, to give chance to IRQs. Abort if fatal signal
361 		 * pending or async compaction detects need_resched()
362 		 */
363 		if (!(blockpfn % SWAP_CLUSTER_MAX)
364 		    && compact_unlock_should_abort(&cc->zone->lock, flags,
365 								&locked, cc))
366 			break;
367 
368 		nr_scanned++;
369 		if (!pfn_valid_within(blockpfn))
370 			goto isolate_fail;
371 
372 		if (!valid_page)
373 			valid_page = page;
374 
375 		/*
376 		 * For compound pages such as THP and hugetlbfs, we can save
377 		 * potentially a lot of iterations if we skip them at once.
378 		 * The check is racy, but we can consider only valid values
379 		 * and the only danger is skipping too much.
380 		 */
381 		if (PageCompound(page)) {
382 			unsigned int comp_order = compound_order(page);
383 
384 			if (likely(comp_order < MAX_ORDER)) {
385 				blockpfn += (1UL << comp_order) - 1;
386 				cursor += (1UL << comp_order) - 1;
387 			}
388 
389 			goto isolate_fail;
390 		}
391 
392 		if (!PageBuddy(page))
393 			goto isolate_fail;
394 
395 		/*
396 		 * If we already hold the lock, we can skip some rechecking.
397 		 * Note that if we hold the lock now, checked_pageblock was
398 		 * already set in some previous iteration (or strict is true),
399 		 * so it is correct to skip the suitable migration target
400 		 * recheck as well.
401 		 */
402 		if (!locked) {
403 			/*
404 			 * The zone lock must be held to isolate freepages.
405 			 * Unfortunately this is a very coarse lock and can be
406 			 * heavily contended if there are parallel allocations
407 			 * or parallel compactions. For async compaction do not
408 			 * spin on the lock and we acquire the lock as late as
409 			 * possible.
410 			 */
411 			locked = compact_trylock_irqsave(&cc->zone->lock,
412 								&flags, cc);
413 			if (!locked)
414 				break;
415 
416 			/* Recheck this is a buddy page under lock */
417 			if (!PageBuddy(page))
418 				goto isolate_fail;
419 		}
420 
421 		/* Found a free page, break it into order-0 pages */
422 		isolated = split_free_page(page);
423 		if (!isolated)
424 			break;
425 
426 		total_isolated += isolated;
427 		cc->nr_freepages += isolated;
428 		for (i = 0; i < isolated; i++) {
429 			list_add(&page->lru, freelist);
430 			page++;
431 		}
432 		if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
433 			blockpfn += isolated;
434 			break;
435 		}
436 		/* Advance to the end of split page */
437 		blockpfn += isolated - 1;
438 		cursor += isolated - 1;
439 		continue;
440 
441 isolate_fail:
442 		if (strict)
443 			break;
444 		else
445 			continue;
446 
447 	}
448 
449 	if (locked)
450 		spin_unlock_irqrestore(&cc->zone->lock, flags);
451 
452 	/*
453 	 * There is a tiny chance that we have read bogus compound_order(),
454 	 * so be careful to not go outside of the pageblock.
455 	 */
456 	if (unlikely(blockpfn > end_pfn))
457 		blockpfn = end_pfn;
458 
459 	/* Record how far we have got within the block */
460 	*start_pfn = blockpfn;
461 
462 	trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);
463 
464 	/*
465 	 * If strict isolation is requested by CMA then check that all the
466 	 * pages requested were isolated. If there were any failures, 0 is
467 	 * returned and CMA will fail.
468 	 */
469 	if (strict && blockpfn < end_pfn)
470 		total_isolated = 0;
471 
472 	/* Update the pageblock-skip if the whole pageblock was scanned */
473 	if (blockpfn == end_pfn)
474 		update_pageblock_skip(cc, valid_page, total_isolated, false);
475 
476 	count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
477 	if (total_isolated)
478 		count_compact_events(COMPACTISOLATED, total_isolated);
479 	return total_isolated;
480 }
481 
482 /**
483  * isolate_freepages_range() - isolate free pages.
484  * @start_pfn: The first PFN to start isolating.
485  * @end_pfn:   The one-past-last PFN.
486  *
487  * Non-free pages, invalid PFNs, or zone boundaries within the
488  * [start_pfn, end_pfn) range are considered errors, cause function to
489  * undo its actions and return zero.
490  *
491  * Otherwise, function returns one-past-the-last PFN of isolated page
492  * (which may be greater then end_pfn if end fell in a middle of
493  * a free page).
494  */
495 unsigned long
isolate_freepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)496 isolate_freepages_range(struct compact_control *cc,
497 			unsigned long start_pfn, unsigned long end_pfn)
498 {
499 	unsigned long isolated, pfn, block_end_pfn;
500 	LIST_HEAD(freelist);
501 
502 	pfn = start_pfn;
503 	block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
504 
505 	for (; pfn < end_pfn; pfn += isolated,
506 				block_end_pfn += pageblock_nr_pages) {
507 		/* Protect pfn from changing by isolate_freepages_block */
508 		unsigned long isolate_start_pfn = pfn;
509 
510 		block_end_pfn = min(block_end_pfn, end_pfn);
511 
512 		/*
513 		 * pfn could pass the block_end_pfn if isolated freepage
514 		 * is more than pageblock order. In this case, we adjust
515 		 * scanning range to right one.
516 		 */
517 		if (pfn >= block_end_pfn) {
518 			block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
519 			block_end_pfn = min(block_end_pfn, end_pfn);
520 		}
521 
522 		if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
523 			break;
524 
525 		isolated = isolate_freepages_block(cc, &isolate_start_pfn,
526 						block_end_pfn, &freelist, true);
527 
528 		/*
529 		 * In strict mode, isolate_freepages_block() returns 0 if
530 		 * there are any holes in the block (ie. invalid PFNs or
531 		 * non-free pages).
532 		 */
533 		if (!isolated)
534 			break;
535 
536 		/*
537 		 * If we managed to isolate pages, it is always (1 << n) *
538 		 * pageblock_nr_pages for some non-negative n.  (Max order
539 		 * page may span two pageblocks).
540 		 */
541 	}
542 
543 	/* split_free_page does not map the pages */
544 	map_pages(&freelist);
545 
546 	if (pfn < end_pfn) {
547 		/* Loop terminated early, cleanup. */
548 		release_freepages(&freelist);
549 		return 0;
550 	}
551 
552 	/* We don't use freelists for anything. */
553 	return pfn;
554 }
555 
556 /* Update the number of anon and file isolated pages in the zone */
acct_isolated(struct zone * zone,struct compact_control * cc)557 static void acct_isolated(struct zone *zone, struct compact_control *cc)
558 {
559 	struct page *page;
560 	unsigned int count[2] = { 0, };
561 
562 	if (list_empty(&cc->migratepages))
563 		return;
564 
565 	list_for_each_entry(page, &cc->migratepages, lru)
566 		count[!!page_is_file_cache(page)]++;
567 
568 	mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
569 	mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
570 }
571 
572 /* Similar to reclaim, but different enough that they don't share logic */
too_many_isolated(struct zone * zone)573 static bool too_many_isolated(struct zone *zone)
574 {
575 	unsigned long active, inactive, isolated;
576 
577 	inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
578 					zone_page_state(zone, NR_INACTIVE_ANON);
579 	active = zone_page_state(zone, NR_ACTIVE_FILE) +
580 					zone_page_state(zone, NR_ACTIVE_ANON);
581 	isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
582 					zone_page_state(zone, NR_ISOLATED_ANON);
583 
584 	return isolated > (inactive + active) / 2;
585 }
586 
587 /**
588  * isolate_migratepages_block() - isolate all migrate-able pages within
589  *				  a single pageblock
590  * @cc:		Compaction control structure.
591  * @low_pfn:	The first PFN to isolate
592  * @end_pfn:	The one-past-the-last PFN to isolate, within same pageblock
593  * @isolate_mode: Isolation mode to be used.
594  *
595  * Isolate all pages that can be migrated from the range specified by
596  * [low_pfn, end_pfn). The range is expected to be within same pageblock.
597  * Returns zero if there is a fatal signal pending, otherwise PFN of the
598  * first page that was not scanned (which may be both less, equal to or more
599  * than end_pfn).
600  *
601  * The pages are isolated on cc->migratepages list (not required to be empty),
602  * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
603  * is neither read nor updated.
604  */
605 static unsigned long
isolate_migratepages_block(struct compact_control * cc,unsigned long low_pfn,unsigned long end_pfn,isolate_mode_t isolate_mode)606 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
607 			unsigned long end_pfn, isolate_mode_t isolate_mode)
608 {
609 	struct zone *zone = cc->zone;
610 	unsigned long nr_scanned = 0, nr_isolated = 0;
611 	struct list_head *migratelist = &cc->migratepages;
612 	struct lruvec *lruvec;
613 	unsigned long flags = 0;
614 	bool locked = false;
615 	struct page *page = NULL, *valid_page = NULL;
616 
617 	/*
618 	 * Ensure that there are not too many pages isolated from the LRU
619 	 * list by either parallel reclaimers or compaction. If there are,
620 	 * delay for some time until fewer pages are isolated
621 	 */
622 	while (unlikely(too_many_isolated(zone))) {
623 		/* async migration should just abort */
624 		if (cc->mode == MIGRATE_ASYNC)
625 			return 0;
626 
627 		congestion_wait(BLK_RW_ASYNC, HZ/10);
628 
629 		if (fatal_signal_pending(current))
630 			return 0;
631 	}
632 
633 	if (compact_should_abort(cc))
634 		return 0;
635 
636 	/* Time to isolate some pages for migration */
637 	for (; low_pfn < end_pfn; low_pfn++) {
638 		/*
639 		 * Periodically drop the lock (if held) regardless of its
640 		 * contention, to give chance to IRQs. Abort async compaction
641 		 * if contended.
642 		 */
643 		if (!(low_pfn % SWAP_CLUSTER_MAX)
644 		    && compact_unlock_should_abort(&zone->lru_lock, flags,
645 								&locked, cc))
646 			break;
647 
648 		if (!pfn_valid_within(low_pfn))
649 			continue;
650 		nr_scanned++;
651 
652 		page = pfn_to_page(low_pfn);
653 
654 		if (!valid_page)
655 			valid_page = page;
656 
657 		/*
658 		 * Skip if free. We read page order here without zone lock
659 		 * which is generally unsafe, but the race window is small and
660 		 * the worst thing that can happen is that we skip some
661 		 * potential isolation targets.
662 		 */
663 		if (PageBuddy(page)) {
664 			unsigned long freepage_order = page_order_unsafe(page);
665 
666 			/*
667 			 * Without lock, we cannot be sure that what we got is
668 			 * a valid page order. Consider only values in the
669 			 * valid order range to prevent low_pfn overflow.
670 			 */
671 			if (freepage_order > 0 && freepage_order < MAX_ORDER)
672 				low_pfn += (1UL << freepage_order) - 1;
673 			continue;
674 		}
675 
676 		/*
677 		 * Check may be lockless but that's ok as we recheck later.
678 		 * It's possible to migrate LRU pages and balloon pages
679 		 * Skip any other type of page
680 		 */
681 		if (!PageLRU(page)) {
682 			if (unlikely(balloon_page_movable(page))) {
683 				if (balloon_page_isolate(page)) {
684 					/* Successfully isolated */
685 					goto isolate_success;
686 				}
687 			}
688 			continue;
689 		}
690 
691 		/*
692 		 * PageLRU is set. lru_lock normally excludes isolation
693 		 * splitting and collapsing (collapsing has already happened
694 		 * if PageLRU is set) but the lock is not necessarily taken
695 		 * here and it is wasteful to take it just to check transhuge.
696 		 * Check TransHuge without lock and skip the whole pageblock if
697 		 * it's either a transhuge or hugetlbfs page, as calling
698 		 * compound_order() without preventing THP from splitting the
699 		 * page underneath us may return surprising results.
700 		 */
701 		if (PageTransHuge(page)) {
702 			if (!locked)
703 				low_pfn = ALIGN(low_pfn + 1,
704 						pageblock_nr_pages) - 1;
705 			else
706 				low_pfn += (1 << compound_order(page)) - 1;
707 
708 			continue;
709 		}
710 
711 		/*
712 		 * Migration will fail if an anonymous page is pinned in memory,
713 		 * so avoid taking lru_lock and isolating it unnecessarily in an
714 		 * admittedly racy check.
715 		 */
716 		if (!page_mapping(page) &&
717 		    page_count(page) > page_mapcount(page))
718 			continue;
719 
720 		/* If we already hold the lock, we can skip some rechecking */
721 		if (!locked) {
722 			locked = compact_trylock_irqsave(&zone->lru_lock,
723 								&flags, cc);
724 			if (!locked)
725 				break;
726 
727 			/* Recheck PageLRU and PageTransHuge under lock */
728 			if (!PageLRU(page))
729 				continue;
730 			if (PageTransHuge(page)) {
731 				low_pfn += (1 << compound_order(page)) - 1;
732 				continue;
733 			}
734 		}
735 
736 		lruvec = mem_cgroup_page_lruvec(page, zone);
737 
738 		/* Try isolate the page */
739 		if (__isolate_lru_page(page, isolate_mode) != 0)
740 			continue;
741 
742 		VM_BUG_ON_PAGE(PageTransCompound(page), page);
743 
744 		/* Successfully isolated */
745 		del_page_from_lru_list(page, lruvec, page_lru(page));
746 
747 isolate_success:
748 		cc->finished_update_migrate = true;
749 		list_add(&page->lru, migratelist);
750 		cc->nr_migratepages++;
751 		nr_isolated++;
752 
753 		/* Avoid isolating too much */
754 		if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
755 			++low_pfn;
756 			break;
757 		}
758 	}
759 
760 	/*
761 	 * The PageBuddy() check could have potentially brought us outside
762 	 * the range to be scanned.
763 	 */
764 	if (unlikely(low_pfn > end_pfn))
765 		low_pfn = end_pfn;
766 
767 	if (locked)
768 		spin_unlock_irqrestore(&zone->lru_lock, flags);
769 
770 	/*
771 	 * Update the pageblock-skip information and cached scanner pfn,
772 	 * if the whole pageblock was scanned without isolating any page.
773 	 */
774 	if (low_pfn == end_pfn)
775 		update_pageblock_skip(cc, valid_page, nr_isolated, true);
776 
777 	trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);
778 
779 	count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
780 	if (nr_isolated)
781 		count_compact_events(COMPACTISOLATED, nr_isolated);
782 
783 	return low_pfn;
784 }
785 
786 /**
787  * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
788  * @cc:        Compaction control structure.
789  * @start_pfn: The first PFN to start isolating.
790  * @end_pfn:   The one-past-last PFN.
791  *
792  * Returns zero if isolation fails fatally due to e.g. pending signal.
793  * Otherwise, function returns one-past-the-last PFN of isolated page
794  * (which may be greater than end_pfn if end fell in a middle of a THP page).
795  */
796 unsigned long
isolate_migratepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)797 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
798 							unsigned long end_pfn)
799 {
800 	unsigned long pfn, block_end_pfn;
801 
802 	/* Scan block by block. First and last block may be incomplete */
803 	pfn = start_pfn;
804 	block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
805 
806 	for (; pfn < end_pfn; pfn = block_end_pfn,
807 				block_end_pfn += pageblock_nr_pages) {
808 
809 		block_end_pfn = min(block_end_pfn, end_pfn);
810 
811 		if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
812 			continue;
813 
814 		pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
815 							ISOLATE_UNEVICTABLE);
816 
817 		if (!pfn)
818 			break;
819 
820 		if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
821 			break;
822 	}
823 	acct_isolated(cc->zone, cc);
824 
825 	return pfn;
826 }
827 
828 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
829 #ifdef CONFIG_COMPACTION
830 /*
831  * Based on information in the current compact_control, find blocks
832  * suitable for isolating free pages from and then isolate them.
833  */
isolate_freepages(struct compact_control * cc)834 static void isolate_freepages(struct compact_control *cc)
835 {
836 	struct zone *zone = cc->zone;
837 	struct page *page;
838 	unsigned long block_start_pfn;	/* start of current pageblock */
839 	unsigned long isolate_start_pfn; /* exact pfn we start at */
840 	unsigned long block_end_pfn;	/* end of current pageblock */
841 	unsigned long low_pfn;	     /* lowest pfn scanner is able to scan */
842 	int nr_freepages = cc->nr_freepages;
843 	struct list_head *freelist = &cc->freepages;
844 
845 	/*
846 	 * Initialise the free scanner. The starting point is where we last
847 	 * successfully isolated from, zone-cached value, or the end of the
848 	 * zone when isolating for the first time. For looping we also need
849 	 * this pfn aligned down to the pageblock boundary, because we do
850 	 * block_start_pfn -= pageblock_nr_pages in the for loop.
851 	 * For ending point, take care when isolating in last pageblock of a
852 	 * a zone which ends in the middle of a pageblock.
853 	 * The low boundary is the end of the pageblock the migration scanner
854 	 * is using.
855 	 */
856 	isolate_start_pfn = cc->free_pfn;
857 	block_start_pfn = cc->free_pfn & ~(pageblock_nr_pages-1);
858 	block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
859 						zone_end_pfn(zone));
860 	low_pfn = ALIGN(cc->migrate_pfn + 1, pageblock_nr_pages);
861 
862 	/*
863 	 * Isolate free pages until enough are available to migrate the
864 	 * pages on cc->migratepages. We stop searching if the migrate
865 	 * and free page scanners meet or enough free pages are isolated.
866 	 */
867 	for (; block_start_pfn >= low_pfn && cc->nr_migratepages > nr_freepages;
868 				block_end_pfn = block_start_pfn,
869 				block_start_pfn -= pageblock_nr_pages,
870 				isolate_start_pfn = block_start_pfn) {
871 		unsigned long isolated;
872 
873 		/*
874 		 * This can iterate a massively long zone without finding any
875 		 * suitable migration targets, so periodically check if we need
876 		 * to schedule, or even abort async compaction.
877 		 */
878 		if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
879 						&& compact_should_abort(cc))
880 			break;
881 
882 		page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
883 									zone);
884 		if (!page)
885 			continue;
886 
887 		/* Check the block is suitable for migration */
888 		if (!suitable_migration_target(page))
889 			continue;
890 
891 		/* If isolation recently failed, do not retry */
892 		if (!isolation_suitable(cc, page))
893 			continue;
894 
895 		/* Found a block suitable for isolating free pages from. */
896 		isolated = isolate_freepages_block(cc, &isolate_start_pfn,
897 						block_end_pfn, freelist, false);
898 		/* If isolation failed early, do not continue needlessly */
899 		if (!isolated && isolate_start_pfn < block_end_pfn &&
900 		    cc->nr_migratepages > cc->nr_freepages)
901 			break;
902 
903 		nr_freepages += isolated;
904 
905 		/*
906 		 * Remember where the free scanner should restart next time,
907 		 * which is where isolate_freepages_block() left off.
908 		 * But if it scanned the whole pageblock, isolate_start_pfn
909 		 * now points at block_end_pfn, which is the start of the next
910 		 * pageblock.
911 		 * In that case we will however want to restart at the start
912 		 * of the previous pageblock.
913 		 */
914 		cc->free_pfn = (isolate_start_pfn < block_end_pfn) ?
915 				isolate_start_pfn :
916 				block_start_pfn - pageblock_nr_pages;
917 
918 		/*
919 		 * Set a flag that we successfully isolated in this pageblock.
920 		 * In the next loop iteration, zone->compact_cached_free_pfn
921 		 * will not be updated and thus it will effectively contain the
922 		 * highest pageblock we isolated pages from.
923 		 */
924 		if (isolated)
925 			cc->finished_update_free = true;
926 
927 		/*
928 		 * isolate_freepages_block() might have aborted due to async
929 		 * compaction being contended
930 		 */
931 		if (cc->contended)
932 			break;
933 	}
934 
935 	/* split_free_page does not map the pages */
936 	map_pages(freelist);
937 
938 	/*
939 	 * If we crossed the migrate scanner, we want to keep it that way
940 	 * so that compact_finished() may detect this
941 	 */
942 	if (block_start_pfn < low_pfn)
943 		cc->free_pfn = cc->migrate_pfn;
944 
945 	cc->nr_freepages = nr_freepages;
946 }
947 
948 /*
949  * This is a migrate-callback that "allocates" freepages by taking pages
950  * from the isolated freelists in the block we are migrating to.
951  */
compaction_alloc(struct page * migratepage,unsigned long data,int ** result)952 static struct page *compaction_alloc(struct page *migratepage,
953 					unsigned long data,
954 					int **result)
955 {
956 	struct compact_control *cc = (struct compact_control *)data;
957 	struct page *freepage;
958 
959 	/*
960 	 * Isolate free pages if necessary, and if we are not aborting due to
961 	 * contention.
962 	 */
963 	if (list_empty(&cc->freepages)) {
964 		if (!cc->contended)
965 			isolate_freepages(cc);
966 
967 		if (list_empty(&cc->freepages))
968 			return NULL;
969 	}
970 
971 	freepage = list_entry(cc->freepages.next, struct page, lru);
972 	list_del(&freepage->lru);
973 	cc->nr_freepages--;
974 
975 	return freepage;
976 }
977 
978 /*
979  * This is a migrate-callback that "frees" freepages back to the isolated
980  * freelist.  All pages on the freelist are from the same zone, so there is no
981  * special handling needed for NUMA.
982  */
compaction_free(struct page * page,unsigned long data)983 static void compaction_free(struct page *page, unsigned long data)
984 {
985 	struct compact_control *cc = (struct compact_control *)data;
986 
987 	list_add(&page->lru, &cc->freepages);
988 	cc->nr_freepages++;
989 }
990 
991 /* possible outcome of isolate_migratepages */
992 typedef enum {
993 	ISOLATE_ABORT,		/* Abort compaction now */
994 	ISOLATE_NONE,		/* No pages isolated, continue scanning */
995 	ISOLATE_SUCCESS,	/* Pages isolated, migrate */
996 } isolate_migrate_t;
997 
998 /*
999  * Isolate all pages that can be migrated from the first suitable block,
1000  * starting at the block pointed to by the migrate scanner pfn within
1001  * compact_control.
1002  */
isolate_migratepages(struct zone * zone,struct compact_control * cc)1003 static isolate_migrate_t isolate_migratepages(struct zone *zone,
1004 					struct compact_control *cc)
1005 {
1006 	unsigned long low_pfn, end_pfn;
1007 	struct page *page;
1008 	const isolate_mode_t isolate_mode =
1009 		(cc->mode == MIGRATE_ASYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1010 
1011 	/*
1012 	 * Start at where we last stopped, or beginning of the zone as
1013 	 * initialized by compact_zone()
1014 	 */
1015 	low_pfn = cc->migrate_pfn;
1016 
1017 	/* Only scan within a pageblock boundary */
1018 	end_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages);
1019 
1020 	/*
1021 	 * Iterate over whole pageblocks until we find the first suitable.
1022 	 * Do not cross the free scanner.
1023 	 */
1024 	for (; end_pfn <= cc->free_pfn;
1025 			low_pfn = end_pfn, end_pfn += pageblock_nr_pages) {
1026 
1027 		/*
1028 		 * This can potentially iterate a massively long zone with
1029 		 * many pageblocks unsuitable, so periodically check if we
1030 		 * need to schedule, or even abort async compaction.
1031 		 */
1032 		if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1033 						&& compact_should_abort(cc))
1034 			break;
1035 
1036 		page = pageblock_pfn_to_page(low_pfn, end_pfn, zone);
1037 		if (!page)
1038 			continue;
1039 
1040 		/* If isolation recently failed, do not retry */
1041 		if (!isolation_suitable(cc, page))
1042 			continue;
1043 
1044 		/*
1045 		 * For async compaction, also only scan in MOVABLE blocks.
1046 		 * Async compaction is optimistic to see if the minimum amount
1047 		 * of work satisfies the allocation.
1048 		 */
1049 		if (cc->mode == MIGRATE_ASYNC &&
1050 		    !migrate_async_suitable(get_pageblock_migratetype(page)))
1051 			continue;
1052 
1053 		/* Perform the isolation */
1054 		low_pfn = isolate_migratepages_block(cc, low_pfn, end_pfn,
1055 								isolate_mode);
1056 
1057 		if (!low_pfn || cc->contended) {
1058 			acct_isolated(zone, cc);
1059 			return ISOLATE_ABORT;
1060 		}
1061 
1062 		/*
1063 		 * Either we isolated something and proceed with migration. Or
1064 		 * we failed and compact_zone should decide if we should
1065 		 * continue or not.
1066 		 */
1067 		break;
1068 	}
1069 
1070 	acct_isolated(zone, cc);
1071 	/*
1072 	 * Record where migration scanner will be restarted. If we end up in
1073 	 * the same pageblock as the free scanner, make the scanners fully
1074 	 * meet so that compact_finished() terminates compaction.
1075 	 */
1076 	cc->migrate_pfn = (end_pfn <= cc->free_pfn) ? low_pfn : cc->free_pfn;
1077 
1078 	return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1079 }
1080 
compact_finished(struct zone * zone,struct compact_control * cc,const int migratetype)1081 static int compact_finished(struct zone *zone, struct compact_control *cc,
1082 			    const int migratetype)
1083 {
1084 	unsigned int order;
1085 	unsigned long watermark;
1086 
1087 	if (cc->contended || fatal_signal_pending(current))
1088 		return COMPACT_PARTIAL;
1089 
1090 	/* Compaction run completes if the migrate and free scanner meet */
1091 	if (cc->free_pfn <= cc->migrate_pfn) {
1092 		/* Let the next compaction start anew. */
1093 		zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
1094 		zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
1095 		zone->compact_cached_free_pfn = zone_end_pfn(zone);
1096 
1097 		/*
1098 		 * Mark that the PG_migrate_skip information should be cleared
1099 		 * by kswapd when it goes to sleep. kswapd does not set the
1100 		 * flag itself as the decision to be clear should be directly
1101 		 * based on an allocation request.
1102 		 */
1103 		if (!current_is_kswapd())
1104 			zone->compact_blockskip_flush = true;
1105 
1106 		return COMPACT_COMPLETE;
1107 	}
1108 
1109 	/*
1110 	 * order == -1 is expected when compacting via
1111 	 * /proc/sys/vm/compact_memory
1112 	 */
1113 	if (cc->order == -1)
1114 		return COMPACT_CONTINUE;
1115 
1116 	/* Compaction run is not finished if the watermark is not met */
1117 	watermark = low_wmark_pages(zone);
1118 	watermark += (1 << cc->order);
1119 
1120 	if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
1121 		return COMPACT_CONTINUE;
1122 
1123 	/* Direct compactor: Is a suitable page free? */
1124 	for (order = cc->order; order < MAX_ORDER; order++) {
1125 		struct free_area *area = &zone->free_area[order];
1126 
1127 		/* Job done if page is free of the right migratetype */
1128 		if (!list_empty(&area->free_list[migratetype]))
1129 			return COMPACT_PARTIAL;
1130 
1131 		/* Job done if allocation would set block type */
1132 		if (order >= pageblock_order && area->nr_free)
1133 			return COMPACT_PARTIAL;
1134 	}
1135 
1136 	return COMPACT_CONTINUE;
1137 }
1138 
1139 /*
1140  * compaction_suitable: Is this suitable to run compaction on this zone now?
1141  * Returns
1142  *   COMPACT_SKIPPED  - If there are too few free pages for compaction
1143  *   COMPACT_PARTIAL  - If the allocation would succeed without compaction
1144  *   COMPACT_CONTINUE - If compaction should run now
1145  */
compaction_suitable(struct zone * zone,int order)1146 unsigned long compaction_suitable(struct zone *zone, int order)
1147 {
1148 	int fragindex;
1149 	unsigned long watermark;
1150 
1151 	/*
1152 	 * order == -1 is expected when compacting via
1153 	 * /proc/sys/vm/compact_memory
1154 	 */
1155 	if (order == -1)
1156 		return COMPACT_CONTINUE;
1157 
1158 	/*
1159 	 * Watermarks for order-0 must be met for compaction. Note the 2UL.
1160 	 * This is because during migration, copies of pages need to be
1161 	 * allocated and for a short time, the footprint is higher
1162 	 */
1163 	watermark = low_wmark_pages(zone) + (2UL << order);
1164 	if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1165 		return COMPACT_SKIPPED;
1166 
1167 	/*
1168 	 * fragmentation index determines if allocation failures are due to
1169 	 * low memory or external fragmentation
1170 	 *
1171 	 * index of -1000 implies allocations might succeed depending on
1172 	 * watermarks
1173 	 * index towards 0 implies failure is due to lack of memory
1174 	 * index towards 1000 implies failure is due to fragmentation
1175 	 *
1176 	 * Only compact if a failure would be due to fragmentation.
1177 	 */
1178 	fragindex = fragmentation_index(zone, order);
1179 	if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
1180 		return COMPACT_SKIPPED;
1181 
1182 	if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
1183 	    0, 0))
1184 		return COMPACT_PARTIAL;
1185 
1186 	return COMPACT_CONTINUE;
1187 }
1188 
compact_zone(struct zone * zone,struct compact_control * cc)1189 static int compact_zone(struct zone *zone, struct compact_control *cc)
1190 {
1191 	int ret;
1192 	unsigned long start_pfn = zone->zone_start_pfn;
1193 	unsigned long end_pfn = zone_end_pfn(zone);
1194 	const int migratetype = gfpflags_to_migratetype(cc->gfp_mask);
1195 	const bool sync = cc->mode != MIGRATE_ASYNC;
1196 
1197 	ret = compaction_suitable(zone, cc->order);
1198 	switch (ret) {
1199 	case COMPACT_PARTIAL:
1200 	case COMPACT_SKIPPED:
1201 		/* Compaction is likely to fail */
1202 		return ret;
1203 	case COMPACT_CONTINUE:
1204 		/* Fall through to compaction */
1205 		;
1206 	}
1207 
1208 	/*
1209 	 * Clear pageblock skip if there were failures recently and compaction
1210 	 * is about to be retried after being deferred. kswapd does not do
1211 	 * this reset as it'll reset the cached information when going to sleep.
1212 	 */
1213 	if (compaction_restarting(zone, cc->order) && !current_is_kswapd())
1214 		__reset_isolation_suitable(zone);
1215 
1216 	/*
1217 	 * Setup to move all movable pages to the end of the zone. Used cached
1218 	 * information on where the scanners should start but check that it
1219 	 * is initialised by ensuring the values are within zone boundaries.
1220 	 */
1221 	cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
1222 	cc->free_pfn = zone->compact_cached_free_pfn;
1223 	if (cc->free_pfn < start_pfn || cc->free_pfn > end_pfn) {
1224 		cc->free_pfn = end_pfn & ~(pageblock_nr_pages-1);
1225 		zone->compact_cached_free_pfn = cc->free_pfn;
1226 	}
1227 	if (cc->migrate_pfn < start_pfn || cc->migrate_pfn > end_pfn) {
1228 		cc->migrate_pfn = start_pfn;
1229 		zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
1230 		zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
1231 	}
1232 
1233 	trace_mm_compaction_begin(start_pfn, cc->migrate_pfn, cc->free_pfn, end_pfn);
1234 
1235 	migrate_prep_local();
1236 
1237 	while ((ret = compact_finished(zone, cc, migratetype)) ==
1238 						COMPACT_CONTINUE) {
1239 		int err;
1240 
1241 		switch (isolate_migratepages(zone, cc)) {
1242 		case ISOLATE_ABORT:
1243 			ret = COMPACT_PARTIAL;
1244 			putback_movable_pages(&cc->migratepages);
1245 			cc->nr_migratepages = 0;
1246 			goto out;
1247 		case ISOLATE_NONE:
1248 			continue;
1249 		case ISOLATE_SUCCESS:
1250 			;
1251 		}
1252 
1253 		err = migrate_pages(&cc->migratepages, compaction_alloc,
1254 				compaction_free, (unsigned long)cc, cc->mode,
1255 				MR_COMPACTION);
1256 
1257 		trace_mm_compaction_migratepages(cc->nr_migratepages, err,
1258 							&cc->migratepages);
1259 
1260 		/* All pages were either migrated or will be released */
1261 		cc->nr_migratepages = 0;
1262 		if (err) {
1263 			putback_movable_pages(&cc->migratepages);
1264 			/*
1265 			 * migrate_pages() may return -ENOMEM when scanners meet
1266 			 * and we want compact_finished() to detect it
1267 			 */
1268 			if (err == -ENOMEM && cc->free_pfn > cc->migrate_pfn) {
1269 				ret = COMPACT_PARTIAL;
1270 				goto out;
1271 			}
1272 		}
1273 	}
1274 
1275 out:
1276 	/* Release free pages and check accounting */
1277 	cc->nr_freepages -= release_freepages(&cc->freepages);
1278 	VM_BUG_ON(cc->nr_freepages != 0);
1279 
1280 	trace_mm_compaction_end(ret);
1281 
1282 	return ret;
1283 }
1284 
compact_zone_order(struct zone * zone,int order,gfp_t gfp_mask,enum migrate_mode mode,int * contended)1285 static unsigned long compact_zone_order(struct zone *zone, int order,
1286 		gfp_t gfp_mask, enum migrate_mode mode, int *contended)
1287 {
1288 	unsigned long ret;
1289 	struct compact_control cc = {
1290 		.nr_freepages = 0,
1291 		.nr_migratepages = 0,
1292 		.order = order,
1293 		.gfp_mask = gfp_mask,
1294 		.zone = zone,
1295 		.mode = mode,
1296 	};
1297 	INIT_LIST_HEAD(&cc.freepages);
1298 	INIT_LIST_HEAD(&cc.migratepages);
1299 
1300 	ret = compact_zone(zone, &cc);
1301 
1302 	VM_BUG_ON(!list_empty(&cc.freepages));
1303 	VM_BUG_ON(!list_empty(&cc.migratepages));
1304 
1305 	*contended = cc.contended;
1306 	return ret;
1307 }
1308 
1309 int sysctl_extfrag_threshold = 500;
1310 
1311 /**
1312  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1313  * @zonelist: The zonelist used for the current allocation
1314  * @order: The order of the current allocation
1315  * @gfp_mask: The GFP mask of the current allocation
1316  * @nodemask: The allowed nodes to allocate from
1317  * @mode: The migration mode for async, sync light, or sync migration
1318  * @contended: Return value that determines if compaction was aborted due to
1319  *	       need_resched() or lock contention
1320  * @candidate_zone: Return the zone where we think allocation should succeed
1321  *
1322  * This is the main entry point for direct page compaction.
1323  */
try_to_compact_pages(struct zonelist * zonelist,int order,gfp_t gfp_mask,nodemask_t * nodemask,enum migrate_mode mode,int * contended,struct zone ** candidate_zone)1324 unsigned long try_to_compact_pages(struct zonelist *zonelist,
1325 			int order, gfp_t gfp_mask, nodemask_t *nodemask,
1326 			enum migrate_mode mode, int *contended,
1327 			struct zone **candidate_zone)
1328 {
1329 	enum zone_type high_zoneidx = gfp_zone(gfp_mask);
1330 	int may_enter_fs = gfp_mask & __GFP_FS;
1331 	int may_perform_io = gfp_mask & __GFP_IO;
1332 	struct zoneref *z;
1333 	struct zone *zone;
1334 	int rc = COMPACT_DEFERRED;
1335 	int alloc_flags = 0;
1336 	int all_zones_contended = COMPACT_CONTENDED_LOCK; /* init for &= op */
1337 
1338 	*contended = COMPACT_CONTENDED_NONE;
1339 
1340 	/* Check if the GFP flags allow compaction */
1341 	if (!order || !may_enter_fs || !may_perform_io)
1342 		return COMPACT_SKIPPED;
1343 
1344 #ifdef CONFIG_CMA
1345 	if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
1346 		alloc_flags |= ALLOC_CMA;
1347 #endif
1348 	/* Compact each zone in the list */
1349 	for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
1350 								nodemask) {
1351 		int status;
1352 		int zone_contended;
1353 
1354 		if (compaction_deferred(zone, order))
1355 			continue;
1356 
1357 		status = compact_zone_order(zone, order, gfp_mask, mode,
1358 							&zone_contended);
1359 		rc = max(status, rc);
1360 		/*
1361 		 * It takes at least one zone that wasn't lock contended
1362 		 * to clear all_zones_contended.
1363 		 */
1364 		all_zones_contended &= zone_contended;
1365 
1366 		/* If a normal allocation would succeed, stop compacting */
1367 		if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0,
1368 				      alloc_flags)) {
1369 			*candidate_zone = zone;
1370 			/*
1371 			 * We think the allocation will succeed in this zone,
1372 			 * but it is not certain, hence the false. The caller
1373 			 * will repeat this with true if allocation indeed
1374 			 * succeeds in this zone.
1375 			 */
1376 			compaction_defer_reset(zone, order, false);
1377 			/*
1378 			 * It is possible that async compaction aborted due to
1379 			 * need_resched() and the watermarks were ok thanks to
1380 			 * somebody else freeing memory. The allocation can
1381 			 * however still fail so we better signal the
1382 			 * need_resched() contention anyway (this will not
1383 			 * prevent the allocation attempt).
1384 			 */
1385 			if (zone_contended == COMPACT_CONTENDED_SCHED)
1386 				*contended = COMPACT_CONTENDED_SCHED;
1387 
1388 			goto break_loop;
1389 		}
1390 
1391 		if (mode != MIGRATE_ASYNC) {
1392 			/*
1393 			 * We think that allocation won't succeed in this zone
1394 			 * so we defer compaction there. If it ends up
1395 			 * succeeding after all, it will be reset.
1396 			 */
1397 			defer_compaction(zone, order);
1398 		}
1399 
1400 		/*
1401 		 * We might have stopped compacting due to need_resched() in
1402 		 * async compaction, or due to a fatal signal detected. In that
1403 		 * case do not try further zones and signal need_resched()
1404 		 * contention.
1405 		 */
1406 		if ((zone_contended == COMPACT_CONTENDED_SCHED)
1407 					|| fatal_signal_pending(current)) {
1408 			*contended = COMPACT_CONTENDED_SCHED;
1409 			goto break_loop;
1410 		}
1411 
1412 		continue;
1413 break_loop:
1414 		/*
1415 		 * We might not have tried all the zones, so  be conservative
1416 		 * and assume they are not all lock contended.
1417 		 */
1418 		all_zones_contended = 0;
1419 		break;
1420 	}
1421 
1422 	/*
1423 	 * If at least one zone wasn't deferred or skipped, we report if all
1424 	 * zones that were tried were lock contended.
1425 	 */
1426 	if (rc > COMPACT_SKIPPED && all_zones_contended)
1427 		*contended = COMPACT_CONTENDED_LOCK;
1428 
1429 	return rc;
1430 }
1431 
1432 
1433 /* Compact all zones within a node */
__compact_pgdat(pg_data_t * pgdat,struct compact_control * cc)1434 static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1435 {
1436 	int zoneid;
1437 	struct zone *zone;
1438 
1439 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1440 
1441 		zone = &pgdat->node_zones[zoneid];
1442 		if (!populated_zone(zone))
1443 			continue;
1444 
1445 		cc->nr_freepages = 0;
1446 		cc->nr_migratepages = 0;
1447 		cc->zone = zone;
1448 		INIT_LIST_HEAD(&cc->freepages);
1449 		INIT_LIST_HEAD(&cc->migratepages);
1450 
1451 		if (cc->order == -1 || !compaction_deferred(zone, cc->order))
1452 			compact_zone(zone, cc);
1453 
1454 		if (cc->order > 0) {
1455 			if (zone_watermark_ok(zone, cc->order,
1456 						low_wmark_pages(zone), 0, 0))
1457 				compaction_defer_reset(zone, cc->order, false);
1458 		}
1459 
1460 		VM_BUG_ON(!list_empty(&cc->freepages));
1461 		VM_BUG_ON(!list_empty(&cc->migratepages));
1462 	}
1463 }
1464 
compact_pgdat(pg_data_t * pgdat,int order)1465 void compact_pgdat(pg_data_t *pgdat, int order)
1466 {
1467 	struct compact_control cc = {
1468 		.order = order,
1469 		.mode = MIGRATE_ASYNC,
1470 	};
1471 
1472 	if (!order)
1473 		return;
1474 
1475 	__compact_pgdat(pgdat, &cc);
1476 }
1477 
compact_node(int nid)1478 static void compact_node(int nid)
1479 {
1480 	struct compact_control cc = {
1481 		.order = -1,
1482 		.mode = MIGRATE_SYNC,
1483 		.ignore_skip_hint = true,
1484 	};
1485 
1486 	__compact_pgdat(NODE_DATA(nid), &cc);
1487 }
1488 
1489 /* Compact all nodes in the system */
compact_nodes(void)1490 static void compact_nodes(void)
1491 {
1492 	int nid;
1493 
1494 	/* Flush pending updates to the LRU lists */
1495 	lru_add_drain_all();
1496 
1497 	for_each_online_node(nid)
1498 		compact_node(nid);
1499 }
1500 
1501 /* The written value is actually unused, all memory is compacted */
1502 int sysctl_compact_memory;
1503 
1504 /* This is the entry point for compacting all nodes via /proc/sys/vm */
sysctl_compaction_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)1505 int sysctl_compaction_handler(struct ctl_table *table, int write,
1506 			void __user *buffer, size_t *length, loff_t *ppos)
1507 {
1508 	if (write)
1509 		compact_nodes();
1510 
1511 	return 0;
1512 }
1513 
sysctl_extfrag_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)1514 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1515 			void __user *buffer, size_t *length, loff_t *ppos)
1516 {
1517 	proc_dointvec_minmax(table, write, buffer, length, ppos);
1518 
1519 	return 0;
1520 }
1521 
1522 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
sysfs_compact_node(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1523 static ssize_t sysfs_compact_node(struct device *dev,
1524 			struct device_attribute *attr,
1525 			const char *buf, size_t count)
1526 {
1527 	int nid = dev->id;
1528 
1529 	if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1530 		/* Flush pending updates to the LRU lists */
1531 		lru_add_drain_all();
1532 
1533 		compact_node(nid);
1534 	}
1535 
1536 	return count;
1537 }
1538 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1539 
compaction_register_node(struct node * node)1540 int compaction_register_node(struct node *node)
1541 {
1542 	return device_create_file(&node->dev, &dev_attr_compact);
1543 }
1544 
compaction_unregister_node(struct node * node)1545 void compaction_unregister_node(struct node *node)
1546 {
1547 	return device_remove_file(&node->dev, &dev_attr_compact);
1548 }
1549 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1550 
1551 #endif /* CONFIG_COMPACTION */
1552