]> git.karo-electronics.de Git - karo-tx-linux.git/blob - mm/compaction.c
197d4ee76672bd26b916161b58a5ab58a5b418d1
[karo-tx-linux.git] / mm / compaction.c
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 "internal.h"
18
19 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
20
21 #define CREATE_TRACE_POINTS
22 #include <trace/events/compaction.h>
23
24 static unsigned long release_freepages(struct list_head *freelist)
25 {
26         struct page *page, *next;
27         unsigned long count = 0;
28
29         list_for_each_entry_safe(page, next, freelist, lru) {
30                 list_del(&page->lru);
31                 __free_page(page);
32                 count++;
33         }
34
35         return count;
36 }
37
38 static void map_pages(struct list_head *list)
39 {
40         struct page *page;
41
42         list_for_each_entry(page, list, lru) {
43                 arch_alloc_page(page, 0);
44                 kernel_map_pages(page, 1, 1);
45         }
46 }
47
48 static inline bool migrate_async_suitable(int migratetype)
49 {
50         return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
51 }
52
53 /*
54  * Compaction requires the taking of some coarse locks that are potentially
55  * very heavily contended. Check if the process needs to be scheduled or
56  * if the lock is contended. For async compaction, back out in the event
57  * if contention is severe. For sync compaction, schedule.
58  *
59  * Returns true if the lock is held.
60  * Returns false if the lock is released and compaction should abort
61  */
62 static bool compact_checklock_irqsave(spinlock_t *lock, unsigned long *flags,
63                                       bool locked, struct compact_control *cc)
64 {
65         if (need_resched() || spin_is_contended(lock)) {
66                 if (locked) {
67                         spin_unlock_irqrestore(lock, *flags);
68                         locked = false;
69                 }
70
71                 /* async aborts if taking too long or contended */
72                 if (!cc->sync) {
73                         cc->contended = true;
74                         return false;
75                 }
76
77                 cond_resched();
78                 if (fatal_signal_pending(current))
79                         return false;
80         }
81
82         if (!locked)
83                 spin_lock_irqsave(lock, *flags);
84         return true;
85 }
86
87 static inline bool compact_trylock_irqsave(spinlock_t *lock,
88                         unsigned long *flags, struct compact_control *cc)
89 {
90         return compact_checklock_irqsave(lock, flags, false, cc);
91 }
92
93 static void compact_capture_page(struct compact_control *cc)
94 {
95         unsigned long flags;
96         int mtype, mtype_low, mtype_high;
97
98         if (!cc->page || *cc->page)
99                 return;
100
101         /*
102          * For MIGRATE_MOVABLE allocations we capture a suitable page ASAP
103          * regardless of the migratetype of the freelist is is captured from.
104          * This is fine because the order for a high-order MIGRATE_MOVABLE
105          * allocation is typically at least a pageblock size and overall
106          * fragmentation is not impaired. Other allocation types must
107          * capture pages from their own migratelist because otherwise they
108          * could pollute other pageblocks like MIGRATE_MOVABLE with
109          * difficult to move pages and making fragmentation worse overall.
110          */
111         if (cc->migratetype == MIGRATE_MOVABLE) {
112                 mtype_low = 0;
113                 mtype_high = MIGRATE_PCPTYPES;
114         } else {
115                 mtype_low = cc->migratetype;
116                 mtype_high = cc->migratetype + 1;
117         }
118
119         /* Speculatively examine the free lists without zone lock */
120         for (mtype = mtype_low; mtype < mtype_high; mtype++) {
121                 int order;
122                 for (order = cc->order; order < MAX_ORDER; order++) {
123                         struct page *page;
124                         struct free_area *area;
125                         area = &(cc->zone->free_area[order]);
126                         if (list_empty(&area->free_list[mtype]))
127                                 continue;
128
129                         /* Take the lock and attempt capture of the page */
130                         if (!compact_trylock_irqsave(&cc->zone->lock, &flags, cc))
131                                 return;
132                         if (!list_empty(&area->free_list[mtype])) {
133                                 page = list_entry(area->free_list[mtype].next,
134                                                         struct page, lru);
135                                 if (capture_free_page(page, cc->order, mtype)) {
136                                         spin_unlock_irqrestore(&cc->zone->lock,
137                                                                         flags);
138                                         *cc->page = page;
139                                         return;
140                                 }
141                         }
142                         spin_unlock_irqrestore(&cc->zone->lock, flags);
143                 }
144         }
145 }
146
147 /*
148  * Isolate free pages onto a private freelist. Caller must hold zone->lock.
149  * If @strict is true, will abort returning 0 on any invalid PFNs or non-free
150  * pages inside of the pageblock (even though it may still end up isolating
151  * some pages).
152  */
153 static unsigned long isolate_freepages_block(unsigned long blockpfn,
154                                 unsigned long end_pfn,
155                                 struct list_head *freelist,
156                                 bool strict)
157 {
158         int nr_scanned = 0, total_isolated = 0;
159         struct page *cursor;
160
161         cursor = pfn_to_page(blockpfn);
162
163         /* Isolate free pages. This assumes the block is valid */
164         for (; blockpfn < end_pfn; blockpfn++, cursor++) {
165                 int isolated, i;
166                 struct page *page = cursor;
167
168                 if (!pfn_valid_within(blockpfn)) {
169                         if (strict)
170                                 return 0;
171                         continue;
172                 }
173                 nr_scanned++;
174
175                 if (!PageBuddy(page)) {
176                         if (strict)
177                                 return 0;
178                         continue;
179                 }
180
181                 /* Found a free page, break it into order-0 pages */
182                 isolated = split_free_page(page);
183                 if (!isolated && strict)
184                         return 0;
185                 total_isolated += isolated;
186                 for (i = 0; i < isolated; i++) {
187                         list_add(&page->lru, freelist);
188                         page++;
189                 }
190
191                 /* If a page was split, advance to the end of it */
192                 if (isolated) {
193                         blockpfn += isolated - 1;
194                         cursor += isolated - 1;
195                 }
196         }
197
198         trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);
199         return total_isolated;
200 }
201
202 /**
203  * isolate_freepages_range() - isolate free pages.
204  * @start_pfn: The first PFN to start isolating.
205  * @end_pfn:   The one-past-last PFN.
206  *
207  * Non-free pages, invalid PFNs, or zone boundaries within the
208  * [start_pfn, end_pfn) range are considered errors, cause function to
209  * undo its actions and return zero.
210  *
211  * Otherwise, function returns one-past-the-last PFN of isolated page
212  * (which may be greater then end_pfn if end fell in a middle of
213  * a free page).
214  */
215 unsigned long
216 isolate_freepages_range(unsigned long start_pfn, unsigned long end_pfn)
217 {
218         unsigned long isolated, pfn, block_end_pfn, flags;
219         struct zone *zone = NULL;
220         LIST_HEAD(freelist);
221
222         if (pfn_valid(start_pfn))
223                 zone = page_zone(pfn_to_page(start_pfn));
224
225         for (pfn = start_pfn; pfn < end_pfn; pfn += isolated) {
226                 if (!pfn_valid(pfn) || zone != page_zone(pfn_to_page(pfn)))
227                         break;
228
229                 /*
230                  * On subsequent iterations ALIGN() is actually not needed,
231                  * but we keep it that we not to complicate the code.
232                  */
233                 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
234                 block_end_pfn = min(block_end_pfn, end_pfn);
235
236                 spin_lock_irqsave(&zone->lock, flags);
237                 isolated = isolate_freepages_block(pfn, block_end_pfn,
238                                                    &freelist, true);
239                 spin_unlock_irqrestore(&zone->lock, flags);
240
241                 /*
242                  * In strict mode, isolate_freepages_block() returns 0 if
243                  * there are any holes in the block (ie. invalid PFNs or
244                  * non-free pages).
245                  */
246                 if (!isolated)
247                         break;
248
249                 /*
250                  * If we managed to isolate pages, it is always (1 << n) *
251                  * pageblock_nr_pages for some non-negative n.  (Max order
252                  * page may span two pageblocks).
253                  */
254         }
255
256         /* split_free_page does not map the pages */
257         map_pages(&freelist);
258
259         if (pfn < end_pfn) {
260                 /* Loop terminated early, cleanup. */
261                 release_freepages(&freelist);
262                 return 0;
263         }
264
265         /* We don't use freelists for anything. */
266         return pfn;
267 }
268
269 /* Update the number of anon and file isolated pages in the zone */
270 static void acct_isolated(struct zone *zone, bool locked, struct compact_control *cc)
271 {
272         struct page *page;
273         unsigned int count[2] = { 0, };
274
275         list_for_each_entry(page, &cc->migratepages, lru)
276                 count[!!page_is_file_cache(page)]++;
277
278         /* If locked we can use the interrupt unsafe versions */
279         if (locked) {
280                 __mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
281                 __mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
282         } else {
283                 mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
284                 mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
285         }
286 }
287
288 /* Similar to reclaim, but different enough that they don't share logic */
289 static bool too_many_isolated(struct zone *zone)
290 {
291         unsigned long active, inactive, isolated;
292
293         inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
294                                         zone_page_state(zone, NR_INACTIVE_ANON);
295         active = zone_page_state(zone, NR_ACTIVE_FILE) +
296                                         zone_page_state(zone, NR_ACTIVE_ANON);
297         isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
298                                         zone_page_state(zone, NR_ISOLATED_ANON);
299
300         return isolated > (inactive + active) / 2;
301 }
302
303 /**
304  * isolate_migratepages_range() - isolate all migrate-able pages in range.
305  * @zone:       Zone pages are in.
306  * @cc:         Compaction control structure.
307  * @low_pfn:    The first PFN of the range.
308  * @end_pfn:    The one-past-the-last PFN of the range.
309  *
310  * Isolate all pages that can be migrated from the range specified by
311  * [low_pfn, end_pfn).  Returns zero if there is a fatal signal
312  * pending), otherwise PFN of the first page that was not scanned
313  * (which may be both less, equal to or more then end_pfn).
314  *
315  * Assumes that cc->migratepages is empty and cc->nr_migratepages is
316  * zero.
317  *
318  * Apart from cc->migratepages and cc->nr_migratetypes this function
319  * does not modify any cc's fields, in particular it does not modify
320  * (or read for that matter) cc->migrate_pfn.
321  */
322 unsigned long
323 isolate_migratepages_range(struct zone *zone, struct compact_control *cc,
324                            unsigned long low_pfn, unsigned long end_pfn)
325 {
326         unsigned long last_pageblock_nr = 0, pageblock_nr;
327         unsigned long nr_scanned = 0, nr_isolated = 0;
328         struct list_head *migratelist = &cc->migratepages;
329         isolate_mode_t mode = 0;
330         struct lruvec *lruvec;
331         unsigned long flags;
332         bool locked;
333
334         /*
335          * Ensure that there are not too many pages isolated from the LRU
336          * list by either parallel reclaimers or compaction. If there are,
337          * delay for some time until fewer pages are isolated
338          */
339         while (unlikely(too_many_isolated(zone))) {
340                 /* async migration should just abort */
341                 if (!cc->sync)
342                         return 0;
343
344                 congestion_wait(BLK_RW_ASYNC, HZ/10);
345
346                 if (fatal_signal_pending(current))
347                         return 0;
348         }
349
350         /* Time to isolate some pages for migration */
351         cond_resched();
352         spin_lock_irqsave(&zone->lru_lock, flags);
353         locked = true;
354         for (; low_pfn < end_pfn; low_pfn++) {
355                 struct page *page;
356
357                 /* give a chance to irqs before checking need_resched() */
358                 if (!((low_pfn+1) % SWAP_CLUSTER_MAX)) {
359                         spin_unlock_irqrestore(&zone->lru_lock, flags);
360                         locked = false;
361                 }
362
363                 /* Check if it is ok to still hold the lock */
364                 locked = compact_checklock_irqsave(&zone->lru_lock, &flags,
365                                                                 locked, cc);
366                 if (!locked)
367                         break;
368
369                 /*
370                  * migrate_pfn does not necessarily start aligned to a
371                  * pageblock. Ensure that pfn_valid is called when moving
372                  * into a new MAX_ORDER_NR_PAGES range in case of large
373                  * memory holes within the zone
374                  */
375                 if ((low_pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
376                         if (!pfn_valid(low_pfn)) {
377                                 low_pfn += MAX_ORDER_NR_PAGES - 1;
378                                 continue;
379                         }
380                 }
381
382                 if (!pfn_valid_within(low_pfn))
383                         continue;
384                 nr_scanned++;
385
386                 /*
387                  * Get the page and ensure the page is within the same zone.
388                  * See the comment in isolate_freepages about overlapping
389                  * nodes. It is deliberate that the new zone lock is not taken
390                  * as memory compaction should not move pages between nodes.
391                  */
392                 page = pfn_to_page(low_pfn);
393                 if (page_zone(page) != zone)
394                         continue;
395
396                 /* Skip if free */
397                 if (PageBuddy(page))
398                         continue;
399
400                 /*
401                  * For async migration, also only scan in MOVABLE blocks. Async
402                  * migration is optimistic to see if the minimum amount of work
403                  * satisfies the allocation
404                  */
405                 pageblock_nr = low_pfn >> pageblock_order;
406                 if (!cc->sync && last_pageblock_nr != pageblock_nr &&
407                     !migrate_async_suitable(get_pageblock_migratetype(page))) {
408                         low_pfn += pageblock_nr_pages;
409                         low_pfn = ALIGN(low_pfn, pageblock_nr_pages) - 1;
410                         last_pageblock_nr = pageblock_nr;
411                         continue;
412                 }
413
414                 if (!PageLRU(page))
415                         continue;
416
417                 /*
418                  * PageLRU is set, and lru_lock excludes isolation,
419                  * splitting and collapsing (collapsing has already
420                  * happened if PageLRU is set).
421                  */
422                 if (PageTransHuge(page)) {
423                         low_pfn += (1 << compound_order(page)) - 1;
424                         continue;
425                 }
426
427                 if (!cc->sync)
428                         mode |= ISOLATE_ASYNC_MIGRATE;
429
430                 lruvec = mem_cgroup_page_lruvec(page, zone);
431
432                 /* Try isolate the page */
433                 if (__isolate_lru_page(page, mode) != 0)
434                         continue;
435
436                 VM_BUG_ON(PageTransCompound(page));
437
438                 /* Successfully isolated */
439                 del_page_from_lru_list(page, lruvec, page_lru(page));
440                 list_add(&page->lru, migratelist);
441                 cc->nr_migratepages++;
442                 nr_isolated++;
443
444                 /* Avoid isolating too much */
445                 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
446                         ++low_pfn;
447                         break;
448                 }
449         }
450
451         acct_isolated(zone, locked, cc);
452
453         if (locked)
454                 spin_unlock_irqrestore(&zone->lru_lock, flags);
455
456         trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);
457
458         return low_pfn;
459 }
460
461 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
462 #ifdef CONFIG_COMPACTION
463
464 /* Returns true if the page is within a block suitable for migration to */
465 static bool suitable_migration_target(struct page *page)
466 {
467
468         int migratetype = get_pageblock_migratetype(page);
469
470         /* Don't interfere with memory hot-remove or the min_free_kbytes blocks */
471         if (migratetype == MIGRATE_ISOLATE || migratetype == MIGRATE_RESERVE)
472                 return false;
473
474         /* If the page is a large free page, then allow migration */
475         if (PageBuddy(page) && page_order(page) >= pageblock_order)
476                 return true;
477
478         /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
479         if (migrate_async_suitable(migratetype))
480                 return true;
481
482         /* Otherwise skip the block */
483         return false;
484 }
485
486 /*
487  * Returns the start pfn of the last page block in a zone.  This is the starting
488  * point for full compaction of a zone.  Compaction searches for free pages from
489  * the end of each zone, while isolate_freepages_block scans forward inside each
490  * page block.
491  */
492 static unsigned long start_free_pfn(struct zone *zone)
493 {
494         unsigned long free_pfn;
495         free_pfn = zone->zone_start_pfn + zone->spanned_pages;
496         free_pfn &= ~(pageblock_nr_pages-1);
497         return free_pfn;
498 }
499
500 /*
501  * Based on information in the current compact_control, find blocks
502  * suitable for isolating free pages from and then isolate them.
503  */
504 static void isolate_freepages(struct zone *zone,
505                                 struct compact_control *cc)
506 {
507         struct page *page;
508         unsigned long high_pfn, low_pfn, pfn, zone_end_pfn, end_pfn;
509         unsigned long flags;
510         int nr_freepages = cc->nr_freepages;
511         struct list_head *freelist = &cc->freepages;
512
513         /*
514          * Initialise the free scanner. The starting point is where we last
515          * scanned from (or the end of the zone if starting). The low point
516          * is the end of the pageblock the migration scanner is using.
517          */
518         pfn = cc->free_pfn;
519         low_pfn = cc->migrate_pfn + pageblock_nr_pages;
520
521         /*
522          * Take care that if the migration scanner is at the end of the zone
523          * that the free scanner does not accidentally move to the next zone
524          * in the next isolation cycle.
525          */
526         high_pfn = min(low_pfn, pfn);
527
528         zone_end_pfn = zone->zone_start_pfn + zone->spanned_pages;
529
530         /*
531          * Isolate free pages until enough are available to migrate the
532          * pages on cc->migratepages. We stop searching if the migrate
533          * and free page scanners meet or enough free pages are isolated.
534          */
535         for (; pfn > low_pfn && cc->nr_migratepages > nr_freepages;
536                                         pfn -= pageblock_nr_pages) {
537                 unsigned long isolated;
538
539                 if (!pfn_valid(pfn))
540                         continue;
541
542                 /*
543                  * Check for overlapping nodes/zones. It's possible on some
544                  * configurations to have a setup like
545                  * node0 node1 node0
546                  * i.e. it's possible that all pages within a zones range of
547                  * pages do not belong to a single zone.
548                  */
549                 page = pfn_to_page(pfn);
550                 if (page_zone(page) != zone)
551                         continue;
552
553                 /* Check the block is suitable for migration */
554                 if (!suitable_migration_target(page))
555                         continue;
556
557                 /*
558                  * Found a block suitable for isolating free pages from. Now
559                  * we disabled interrupts, double check things are ok and
560                  * isolate the pages. This is to minimise the time IRQs
561                  * are disabled
562                  */
563                 isolated = 0;
564
565                 /*
566                  * The zone lock must be held to isolate freepages. This
567                  * unfortunately this is a very coarse lock and can be
568                  * heavily contended if there are parallel allocations
569                  * or parallel compactions. For async compaction do not
570                  * spin on the lock
571                  */
572                 if (!compact_trylock_irqsave(&zone->lock, &flags, cc))
573                         break;
574                 if (suitable_migration_target(page)) {
575                         end_pfn = min(pfn + pageblock_nr_pages, zone_end_pfn);
576                         isolated = isolate_freepages_block(pfn, end_pfn,
577                                                            freelist, false);
578                         nr_freepages += isolated;
579                 }
580                 spin_unlock_irqrestore(&zone->lock, flags);
581
582                 /*
583                  * Record the highest PFN we isolated pages from. When next
584                  * looking for free pages, the search will restart here as
585                  * page migration may have returned some pages to the allocator
586                  */
587                 if (isolated) {
588                         high_pfn = max(high_pfn, pfn);
589
590                         /*
591                          * If the free scanner has wrapped, update
592                          * compact_cached_free_pfn to point to the highest
593                          * pageblock with free pages. This reduces excessive
594                          * scanning of full pageblocks near the end of the
595                          * zone
596                          */
597                         if (cc->order > 0 && cc->wrapped)
598                                 zone->compact_cached_free_pfn = high_pfn;
599                 }
600         }
601
602         /* split_free_page does not map the pages */
603         map_pages(freelist);
604
605         cc->free_pfn = high_pfn;
606         cc->nr_freepages = nr_freepages;
607
608         /* If compact_cached_free_pfn is reset then set it now */
609         if (cc->order > 0 && !cc->wrapped &&
610                         zone->compact_cached_free_pfn == start_free_pfn(zone))
611                 zone->compact_cached_free_pfn = high_pfn;
612 }
613
614 /*
615  * This is a migrate-callback that "allocates" freepages by taking pages
616  * from the isolated freelists in the block we are migrating to.
617  */
618 static struct page *compaction_alloc(struct page *migratepage,
619                                         unsigned long data,
620                                         int **result)
621 {
622         struct compact_control *cc = (struct compact_control *)data;
623         struct page *freepage;
624
625         /* Isolate free pages if necessary */
626         if (list_empty(&cc->freepages)) {
627                 isolate_freepages(cc->zone, cc);
628
629                 if (list_empty(&cc->freepages))
630                         return NULL;
631         }
632
633         freepage = list_entry(cc->freepages.next, struct page, lru);
634         list_del(&freepage->lru);
635         cc->nr_freepages--;
636
637         return freepage;
638 }
639
640 /*
641  * We cannot control nr_migratepages and nr_freepages fully when migration is
642  * running as migrate_pages() has no knowledge of compact_control. When
643  * migration is complete, we count the number of pages on the lists by hand.
644  */
645 static void update_nr_listpages(struct compact_control *cc)
646 {
647         int nr_migratepages = 0;
648         int nr_freepages = 0;
649         struct page *page;
650
651         list_for_each_entry(page, &cc->migratepages, lru)
652                 nr_migratepages++;
653         list_for_each_entry(page, &cc->freepages, lru)
654                 nr_freepages++;
655
656         cc->nr_migratepages = nr_migratepages;
657         cc->nr_freepages = nr_freepages;
658 }
659
660 /* possible outcome of isolate_migratepages */
661 typedef enum {
662         ISOLATE_ABORT,          /* Abort compaction now */
663         ISOLATE_NONE,           /* No pages isolated, continue scanning */
664         ISOLATE_SUCCESS,        /* Pages isolated, migrate */
665 } isolate_migrate_t;
666
667 /*
668  * Isolate all pages that can be migrated from the block pointed to by
669  * the migrate scanner within compact_control.
670  */
671 static isolate_migrate_t isolate_migratepages(struct zone *zone,
672                                         struct compact_control *cc)
673 {
674         unsigned long low_pfn, end_pfn;
675
676         /* Do not scan outside zone boundaries */
677         low_pfn = max(cc->migrate_pfn, zone->zone_start_pfn);
678
679         /* Only scan within a pageblock boundary */
680         end_pfn = ALIGN(low_pfn + pageblock_nr_pages, pageblock_nr_pages);
681
682         /* Do not cross the free scanner or scan within a memory hole */
683         if (end_pfn > cc->free_pfn || !pfn_valid(low_pfn)) {
684                 cc->migrate_pfn = end_pfn;
685                 return ISOLATE_NONE;
686         }
687
688         /* Perform the isolation */
689         low_pfn = isolate_migratepages_range(zone, cc, low_pfn, end_pfn);
690         if (!low_pfn || cc->contended)
691                 return ISOLATE_ABORT;
692
693         cc->migrate_pfn = low_pfn;
694
695         return ISOLATE_SUCCESS;
696 }
697
698 static int compact_finished(struct zone *zone,
699                             struct compact_control *cc)
700 {
701         unsigned long watermark;
702
703         if (fatal_signal_pending(current))
704                 return COMPACT_PARTIAL;
705
706         /*
707          * A full (order == -1) compaction run starts at the beginning and
708          * end of a zone; it completes when the migrate and free scanner meet.
709          * A partial (order > 0) compaction can start with the free scanner
710          * at a random point in the zone, and may have to restart.
711          */
712         if (cc->free_pfn <= cc->migrate_pfn) {
713                 if (cc->order > 0 && !cc->wrapped) {
714                         /* We started partway through; restart at the end. */
715                         unsigned long free_pfn = start_free_pfn(zone);
716                         zone->compact_cached_free_pfn = free_pfn;
717                         cc->free_pfn = free_pfn;
718                         cc->wrapped = 1;
719                         return COMPACT_CONTINUE;
720                 }
721                 return COMPACT_COMPLETE;
722         }
723
724         /* We wrapped around and ended up where we started. */
725         if (cc->wrapped && cc->free_pfn <= cc->start_free_pfn)
726                 return COMPACT_COMPLETE;
727
728         /*
729          * order == -1 is expected when compacting via
730          * /proc/sys/vm/compact_memory
731          */
732         if (cc->order == -1)
733                 return COMPACT_CONTINUE;
734
735         /* Compaction run is not finished if the watermark is not met */
736         watermark = low_wmark_pages(zone);
737         watermark += (1 << cc->order);
738
739         if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
740                 return COMPACT_CONTINUE;
741
742         /* Direct compactor: Is a suitable page free? */
743         if (cc->page) {
744                 /* Was a suitable page captured? */
745                 if (*cc->page)
746                         return COMPACT_PARTIAL;
747         } else {
748                 unsigned int order;
749                 for (order = cc->order; order < MAX_ORDER; order++) {
750                         struct free_area *area = &zone->free_area[cc->order];
751                         /* Job done if page is free of the right migratetype */
752                         if (!list_empty(&area->free_list[cc->migratetype]))
753                                 return COMPACT_PARTIAL;
754
755                         /* Job done if allocation would set block type */
756                         if (cc->order >= pageblock_order && area->nr_free)
757                                 return COMPACT_PARTIAL;
758                 }
759         }
760
761         return COMPACT_CONTINUE;
762 }
763
764 /*
765  * compaction_suitable: Is this suitable to run compaction on this zone now?
766  * Returns
767  *   COMPACT_SKIPPED  - If there are too few free pages for compaction
768  *   COMPACT_PARTIAL  - If the allocation would succeed without compaction
769  *   COMPACT_CONTINUE - If compaction should run now
770  */
771 unsigned long compaction_suitable(struct zone *zone, int order)
772 {
773         int fragindex;
774         unsigned long watermark;
775
776         /*
777          * order == -1 is expected when compacting via
778          * /proc/sys/vm/compact_memory
779          */
780         if (order == -1)
781                 return COMPACT_CONTINUE;
782
783         /*
784          * Watermarks for order-0 must be met for compaction. Note the 2UL.
785          * This is because during migration, copies of pages need to be
786          * allocated and for a short time, the footprint is higher
787          */
788         watermark = low_wmark_pages(zone) + (2UL << order);
789         if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
790                 return COMPACT_SKIPPED;
791
792         /*
793          * fragmentation index determines if allocation failures are due to
794          * low memory or external fragmentation
795          *
796          * index of -1000 implies allocations might succeed depending on
797          * watermarks
798          * index towards 0 implies failure is due to lack of memory
799          * index towards 1000 implies failure is due to fragmentation
800          *
801          * Only compact if a failure would be due to fragmentation.
802          */
803         fragindex = fragmentation_index(zone, order);
804         if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
805                 return COMPACT_SKIPPED;
806
807         if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
808             0, 0))
809                 return COMPACT_PARTIAL;
810
811         return COMPACT_CONTINUE;
812 }
813
814 static int compact_zone(struct zone *zone, struct compact_control *cc)
815 {
816         int ret;
817
818         ret = compaction_suitable(zone, cc->order);
819         switch (ret) {
820         case COMPACT_PARTIAL:
821         case COMPACT_SKIPPED:
822                 /* Compaction is likely to fail */
823                 return ret;
824         case COMPACT_CONTINUE:
825                 /* Fall through to compaction */
826                 ;
827         }
828
829         /* Setup to move all movable pages to the end of the zone */
830         cc->migrate_pfn = zone->zone_start_pfn;
831
832         if (cc->order > 0) {
833                 /* Incremental compaction. Start where the last one stopped. */
834                 cc->free_pfn = zone->compact_cached_free_pfn;
835                 cc->start_free_pfn = cc->free_pfn;
836         } else {
837                 /* Order == -1 starts at the end of the zone. */
838                 cc->free_pfn = start_free_pfn(zone);
839         }
840
841         migrate_prep_local();
842
843         while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
844                 unsigned long nr_migrate, nr_remaining;
845                 int err;
846
847                 switch (isolate_migratepages(zone, cc)) {
848                 case ISOLATE_ABORT:
849                         ret = COMPACT_PARTIAL;
850                         goto out;
851                 case ISOLATE_NONE:
852                         continue;
853                 case ISOLATE_SUCCESS:
854                         ;
855                 }
856
857                 nr_migrate = cc->nr_migratepages;
858                 err = migrate_pages(&cc->migratepages, compaction_alloc,
859                                 (unsigned long)cc, false,
860                                 cc->sync ? MIGRATE_SYNC_LIGHT : MIGRATE_ASYNC);
861                 update_nr_listpages(cc);
862                 nr_remaining = cc->nr_migratepages;
863
864                 count_vm_event(COMPACTBLOCKS);
865                 count_vm_events(COMPACTPAGES, nr_migrate - nr_remaining);
866                 if (nr_remaining)
867                         count_vm_events(COMPACTPAGEFAILED, nr_remaining);
868                 trace_mm_compaction_migratepages(nr_migrate - nr_remaining,
869                                                 nr_remaining);
870
871                 /* Release LRU pages not migrated */
872                 if (err) {
873                         putback_lru_pages(&cc->migratepages);
874                         cc->nr_migratepages = 0;
875                         if (err == -ENOMEM) {
876                                 ret = COMPACT_PARTIAL;
877                                 goto out;
878                         }
879                 }
880
881                 /* Capture a page now if it is a suitable size */
882                 compact_capture_page(cc);
883         }
884
885 out:
886         /* Release free pages and check accounting */
887         cc->nr_freepages -= release_freepages(&cc->freepages);
888         VM_BUG_ON(cc->nr_freepages != 0);
889
890         return ret;
891 }
892
893 static unsigned long compact_zone_order(struct zone *zone,
894                                  int order, gfp_t gfp_mask,
895                                  bool sync, bool *contended,
896                                  struct page **page)
897 {
898         unsigned long ret;
899         struct compact_control cc = {
900                 .nr_freepages = 0,
901                 .nr_migratepages = 0,
902                 .order = order,
903                 .migratetype = allocflags_to_migratetype(gfp_mask),
904                 .zone = zone,
905                 .sync = sync,
906                 .page = page,
907         };
908         INIT_LIST_HEAD(&cc.freepages);
909         INIT_LIST_HEAD(&cc.migratepages);
910
911         ret = compact_zone(zone, &cc);
912         if (contended)
913                 *contended = cc.contended;
914         return ret;
915 }
916
917 int sysctl_extfrag_threshold = 500;
918
919 /**
920  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
921  * @zonelist: The zonelist used for the current allocation
922  * @order: The order of the current allocation
923  * @gfp_mask: The GFP mask of the current allocation
924  * @nodemask: The allowed nodes to allocate from
925  * @sync: Whether migration is synchronous or not
926  *
927  * This is the main entry point for direct page compaction.
928  */
929 unsigned long try_to_compact_pages(struct zonelist *zonelist,
930                         int order, gfp_t gfp_mask, nodemask_t *nodemask,
931                         bool sync, bool *contended, struct page **page)
932 {
933         enum zone_type high_zoneidx = gfp_zone(gfp_mask);
934         int may_enter_fs = gfp_mask & __GFP_FS;
935         int may_perform_io = gfp_mask & __GFP_IO;
936         struct zoneref *z;
937         struct zone *zone;
938         int rc = COMPACT_SKIPPED;
939         int alloc_flags = 0;
940
941         /* Check if the GFP flags allow compaction */
942         if (!order || !may_enter_fs || !may_perform_io)
943                 return rc;
944
945         count_vm_event(COMPACTSTALL);
946
947 #ifdef CONFIG_CMA
948         if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
949                 alloc_flags |= ALLOC_CMA;
950 #endif
951         /* Compact each zone in the list */
952         for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
953                                                                 nodemask) {
954                 int status;
955
956                 status = compact_zone_order(zone, order, gfp_mask, sync,
957                                                 contended, page);
958                 rc = max(status, rc);
959
960                 /* If a normal allocation would succeed, stop compacting */
961                 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0,
962                                       alloc_flags))
963                         break;
964         }
965
966         return rc;
967 }
968
969
970 /* Compact all zones within a node */
971 static int __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
972 {
973         int zoneid;
974         struct zone *zone;
975
976         for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
977
978                 zone = &pgdat->node_zones[zoneid];
979                 if (!populated_zone(zone))
980                         continue;
981
982                 cc->nr_freepages = 0;
983                 cc->nr_migratepages = 0;
984                 cc->zone = zone;
985                 INIT_LIST_HEAD(&cc->freepages);
986                 INIT_LIST_HEAD(&cc->migratepages);
987
988                 if (cc->order == -1 || !compaction_deferred(zone, cc->order))
989                         compact_zone(zone, cc);
990
991                 if (cc->order > 0) {
992                         int ok = zone_watermark_ok(zone, cc->order,
993                                                 low_wmark_pages(zone), 0, 0);
994                         if (ok && cc->order >= zone->compact_order_failed)
995                                 zone->compact_order_failed = cc->order + 1;
996                         /* Currently async compaction is never deferred. */
997                         else if (!ok && cc->sync)
998                                 defer_compaction(zone, cc->order);
999                 }
1000
1001                 VM_BUG_ON(!list_empty(&cc->freepages));
1002                 VM_BUG_ON(!list_empty(&cc->migratepages));
1003         }
1004
1005         return 0;
1006 }
1007
1008 int compact_pgdat(pg_data_t *pgdat, int order)
1009 {
1010         struct compact_control cc = {
1011                 .order = order,
1012                 .sync = false,
1013                 .page = NULL,
1014         };
1015
1016         return __compact_pgdat(pgdat, &cc);
1017 }
1018
1019 static int compact_node(int nid)
1020 {
1021         struct compact_control cc = {
1022                 .order = -1,
1023                 .sync = true,
1024                 .page = NULL,
1025         };
1026
1027         return __compact_pgdat(NODE_DATA(nid), &cc);
1028 }
1029
1030 /* Compact all nodes in the system */
1031 static int compact_nodes(void)
1032 {
1033         int nid;
1034
1035         /* Flush pending updates to the LRU lists */
1036         lru_add_drain_all();
1037
1038         for_each_online_node(nid)
1039                 compact_node(nid);
1040
1041         return COMPACT_COMPLETE;
1042 }
1043
1044 /* The written value is actually unused, all memory is compacted */
1045 int sysctl_compact_memory;
1046
1047 /* This is the entry point for compacting all nodes via /proc/sys/vm */
1048 int sysctl_compaction_handler(struct ctl_table *table, int write,
1049                         void __user *buffer, size_t *length, loff_t *ppos)
1050 {
1051         if (write)
1052                 return compact_nodes();
1053
1054         return 0;
1055 }
1056
1057 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1058                         void __user *buffer, size_t *length, loff_t *ppos)
1059 {
1060         proc_dointvec_minmax(table, write, buffer, length, ppos);
1061
1062         return 0;
1063 }
1064
1065 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1066 ssize_t sysfs_compact_node(struct device *dev,
1067                         struct device_attribute *attr,
1068                         const char *buf, size_t count)
1069 {
1070         int nid = dev->id;
1071
1072         if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1073                 /* Flush pending updates to the LRU lists */
1074                 lru_add_drain_all();
1075
1076                 compact_node(nid);
1077         }
1078
1079         return count;
1080 }
1081 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1082
1083 int compaction_register_node(struct node *node)
1084 {
1085         return device_create_file(&node->dev, &dev_attr_compact);
1086 }
1087
1088 void compaction_unregister_node(struct node *node)
1089 {
1090         return device_remove_file(&node->dev, &dev_attr_compact);
1091 }
1092 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1093
1094 #endif /* CONFIG_COMPACTION */