compaction.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * linux/mm/compaction.c
  4. *
  5. * Memory compaction for the reduction of external fragmentation. Note that
  6. * this heavily depends upon page migration to do all the real heavy
  7. * lifting
  8. *
  9. * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
  10. */
  11. #include <linux/cpu.h>
  12. #include <linux/swap.h>
  13. #include <linux/migrate.h>
  14. #include <linux/compaction.h>
  15. #include <linux/mm_inline.h>
  16. #include <linux/sched/signal.h>
  17. #include <linux/backing-dev.h>
  18. #include <linux/sysctl.h>
  19. #include <linux/sysfs.h>
  20. #include <linux/page-isolation.h>
  21. #include <linux/kasan.h>
  22. #include <linux/kthread.h>
  23. #include <linux/freezer.h>
  24. #include <linux/page_owner.h>
  25. #include <linux/psi.h>
  26. #include "internal.h"
  27. #ifdef CONFIG_COMPACTION
  28. static inline void count_compact_event(enum vm_event_item item)
  29. {
  30. count_vm_event(item);
  31. }
  32. static inline void count_compact_events(enum vm_event_item item, long delta)
  33. {
  34. count_vm_events(item, delta);
  35. }
  36. #else
  37. #define count_compact_event(item) do { } while (0)
  38. #define count_compact_events(item, delta) do { } while (0)
  39. #endif
  40. #if defined CONFIG_COMPACTION || defined CONFIG_CMA
  41. #define CREATE_TRACE_POINTS
  42. #include <trace/events/compaction.h>
  43. #define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
  44. #define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
  45. #define pageblock_start_pfn(pfn) block_start_pfn(pfn, pageblock_order)
  46. #define pageblock_end_pfn(pfn) block_end_pfn(pfn, pageblock_order)
  47. static unsigned long release_freepages(struct list_head *freelist)
  48. {
  49. struct page *page, *next;
  50. unsigned long high_pfn = 0;
  51. list_for_each_entry_safe(page, next, freelist, lru) {
  52. unsigned long pfn = page_to_pfn(page);
  53. list_del(&page->lru);
  54. __free_page(page);
  55. if (pfn > high_pfn)
  56. high_pfn = pfn;
  57. }
  58. return high_pfn;
  59. }
  60. static void map_pages(struct list_head *list)
  61. {
  62. unsigned int i, order, nr_pages;
  63. struct page *page, *next;
  64. LIST_HEAD(tmp_list);
  65. list_for_each_entry_safe(page, next, list, lru) {
  66. list_del(&page->lru);
  67. order = page_private(page);
  68. nr_pages = 1 << order;
  69. post_alloc_hook(page, order, __GFP_MOVABLE);
  70. if (order)
  71. split_page(page, order);
  72. for (i = 0; i < nr_pages; i++) {
  73. list_add(&page->lru, &tmp_list);
  74. page++;
  75. }
  76. }
  77. list_splice(&tmp_list, list);
  78. }
  79. #ifdef CONFIG_COMPACTION
  80. int PageMovable(struct page *page)
  81. {
  82. struct address_space *mapping;
  83. VM_BUG_ON_PAGE(!PageLocked(page), page);
  84. if (!__PageMovable(page))
  85. return 0;
  86. mapping = page_mapping(page);
  87. if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
  88. return 1;
  89. return 0;
  90. }
  91. EXPORT_SYMBOL(PageMovable);
  92. void __SetPageMovable(struct page *page, struct address_space *mapping)
  93. {
  94. VM_BUG_ON_PAGE(!PageLocked(page), page);
  95. VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
  96. page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
  97. }
  98. EXPORT_SYMBOL(__SetPageMovable);
  99. void __ClearPageMovable(struct page *page)
  100. {
  101. VM_BUG_ON_PAGE(!PageLocked(page), page);
  102. VM_BUG_ON_PAGE(!PageMovable(page), page);
  103. /*
  104. * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
  105. * flag so that VM can catch up released page by driver after isolation.
  106. * With it, VM migration doesn't try to put it back.
  107. */
  108. page->mapping = (void *)((unsigned long)page->mapping &
  109. PAGE_MAPPING_MOVABLE);
  110. }
  111. EXPORT_SYMBOL(__ClearPageMovable);
  112. /* Do not skip compaction more than 64 times */
  113. #define COMPACT_MAX_DEFER_SHIFT 6
  114. /*
  115. * Compaction is deferred when compaction fails to result in a page
  116. * allocation success. 1 << compact_defer_limit compactions are skipped up
  117. * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
  118. */
  119. void defer_compaction(struct zone *zone, int order)
  120. {
  121. zone->compact_considered = 0;
  122. zone->compact_defer_shift++;
  123. if (order < zone->compact_order_failed)
  124. zone->compact_order_failed = order;
  125. if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
  126. zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
  127. trace_mm_compaction_defer_compaction(zone, order);
  128. }
  129. /* Returns true if compaction should be skipped this time */
  130. bool compaction_deferred(struct zone *zone, int order)
  131. {
  132. unsigned long defer_limit = 1UL << zone->compact_defer_shift;
  133. if (order < zone->compact_order_failed)
  134. return false;
  135. /* Avoid possible overflow */
  136. if (++zone->compact_considered > defer_limit)
  137. zone->compact_considered = defer_limit;
  138. if (zone->compact_considered >= defer_limit)
  139. return false;
  140. trace_mm_compaction_deferred(zone, order);
  141. return true;
  142. }
  143. /*
  144. * Update defer tracking counters after successful compaction of given order,
  145. * which means an allocation either succeeded (alloc_success == true) or is
  146. * expected to succeed.
  147. */
  148. void compaction_defer_reset(struct zone *zone, int order,
  149. bool alloc_success)
  150. {
  151. if (alloc_success) {
  152. zone->compact_considered = 0;
  153. zone->compact_defer_shift = 0;
  154. }
  155. if (order >= zone->compact_order_failed)
  156. zone->compact_order_failed = order + 1;
  157. trace_mm_compaction_defer_reset(zone, order);
  158. }
  159. /* Returns true if restarting compaction after many failures */
  160. bool compaction_restarting(struct zone *zone, int order)
  161. {
  162. if (order < zone->compact_order_failed)
  163. return false;
  164. return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
  165. zone->compact_considered >= 1UL << zone->compact_defer_shift;
  166. }
  167. /* Returns true if the pageblock should be scanned for pages to isolate. */
  168. static inline bool isolation_suitable(struct compact_control *cc,
  169. struct page *page)
  170. {
  171. if (cc->ignore_skip_hint)
  172. return true;
  173. return !get_pageblock_skip(page);
  174. }
  175. static void reset_cached_positions(struct zone *zone)
  176. {
  177. zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
  178. zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
  179. zone->compact_cached_free_pfn =
  180. pageblock_start_pfn(zone_end_pfn(zone) - 1);
  181. }
  182. /*
  183. * Compound pages of >= pageblock_order should consistenly be skipped until
  184. * released. It is always pointless to compact pages of such order (if they are
  185. * migratable), and the pageblocks they occupy cannot contain any free pages.
  186. */
  187. static bool pageblock_skip_persistent(struct page *page)
  188. {
  189. if (!PageCompound(page))
  190. return false;
  191. page = compound_head(page);
  192. if (compound_order(page) >= pageblock_order)
  193. return true;
  194. return false;
  195. }
  196. /*
  197. * This function is called to clear all cached information on pageblocks that
  198. * should be skipped for page isolation when the migrate and free page scanner
  199. * meet.
  200. */
  201. static void __reset_isolation_suitable(struct zone *zone)
  202. {
  203. unsigned long start_pfn = zone->zone_start_pfn;
  204. unsigned long end_pfn = zone_end_pfn(zone);
  205. unsigned long pfn;
  206. zone->compact_blockskip_flush = false;
  207. /* Walk the zone and mark every pageblock as suitable for isolation */
  208. for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
  209. struct page *page;
  210. cond_resched();
  211. page = pfn_to_online_page(pfn);
  212. if (!page)
  213. continue;
  214. if (zone != page_zone(page))
  215. continue;
  216. if (pageblock_skip_persistent(page))
  217. continue;
  218. clear_pageblock_skip(page);
  219. }
  220. reset_cached_positions(zone);
  221. }
  222. void reset_isolation_suitable(pg_data_t *pgdat)
  223. {
  224. int zoneid;
  225. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  226. struct zone *zone = &pgdat->node_zones[zoneid];
  227. if (!populated_zone(zone))
  228. continue;
  229. /* Only flush if a full compaction finished recently */
  230. if (zone->compact_blockskip_flush)
  231. __reset_isolation_suitable(zone);
  232. }
  233. }
  234. /*
  235. * If no pages were isolated then mark this pageblock to be skipped in the
  236. * future. The information is later cleared by __reset_isolation_suitable().
  237. */
  238. static void update_pageblock_skip(struct compact_control *cc,
  239. struct page *page, unsigned long nr_isolated,
  240. bool migrate_scanner)
  241. {
  242. struct zone *zone = cc->zone;
  243. unsigned long pfn;
  244. if (cc->no_set_skip_hint)
  245. return;
  246. if (!page)
  247. return;
  248. if (nr_isolated)
  249. return;
  250. set_pageblock_skip(page);
  251. pfn = page_to_pfn(page);
  252. /* Update where async and sync compaction should restart */
  253. if (migrate_scanner) {
  254. if (pfn > zone->compact_cached_migrate_pfn[0])
  255. zone->compact_cached_migrate_pfn[0] = pfn;
  256. if (cc->mode != MIGRATE_ASYNC &&
  257. pfn > zone->compact_cached_migrate_pfn[1])
  258. zone->compact_cached_migrate_pfn[1] = pfn;
  259. } else {
  260. if (pfn < zone->compact_cached_free_pfn)
  261. zone->compact_cached_free_pfn = pfn;
  262. }
  263. }
  264. #else
  265. static inline bool isolation_suitable(struct compact_control *cc,
  266. struct page *page)
  267. {
  268. return true;
  269. }
  270. static inline bool pageblock_skip_persistent(struct page *page)
  271. {
  272. return false;
  273. }
  274. static inline void update_pageblock_skip(struct compact_control *cc,
  275. struct page *page, unsigned long nr_isolated,
  276. bool migrate_scanner)
  277. {
  278. }
  279. #endif /* CONFIG_COMPACTION */
  280. /*
  281. * Compaction requires the taking of some coarse locks that are potentially
  282. * very heavily contended. For async compaction, back out if the lock cannot
  283. * be taken immediately. For sync compaction, spin on the lock if needed.
  284. *
  285. * Returns true if the lock is held
  286. * Returns false if the lock is not held and compaction should abort
  287. */
  288. static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
  289. struct compact_control *cc)
  290. {
  291. if (cc->mode == MIGRATE_ASYNC) {
  292. if (!spin_trylock_irqsave(lock, *flags)) {
  293. cc->contended = true;
  294. return false;
  295. }
  296. } else {
  297. spin_lock_irqsave(lock, *flags);
  298. }
  299. return true;
  300. }
  301. /*
  302. * Compaction requires the taking of some coarse locks that are potentially
  303. * very heavily contended. The lock should be periodically unlocked to avoid
  304. * having disabled IRQs for a long time, even when there is nobody waiting on
  305. * the lock. It might also be that allowing the IRQs will result in
  306. * need_resched() becoming true. If scheduling is needed, async compaction
  307. * aborts. Sync compaction schedules.
  308. * Either compaction type will also abort if a fatal signal is pending.
  309. * In either case if the lock was locked, it is dropped and not regained.
  310. *
  311. * Returns true if compaction should abort due to fatal signal pending, or
  312. * async compaction due to need_resched()
  313. * Returns false when compaction can continue (sync compaction might have
  314. * scheduled)
  315. */
  316. static bool compact_unlock_should_abort(spinlock_t *lock,
  317. unsigned long flags, bool *locked, struct compact_control *cc)
  318. {
  319. if (*locked) {
  320. spin_unlock_irqrestore(lock, flags);
  321. *locked = false;
  322. }
  323. if (fatal_signal_pending(current)) {
  324. cc->contended = true;
  325. return true;
  326. }
  327. if (need_resched()) {
  328. if (cc->mode == MIGRATE_ASYNC) {
  329. cc->contended = true;
  330. return true;
  331. }
  332. cond_resched();
  333. }
  334. return false;
  335. }
  336. /*
  337. * Aside from avoiding lock contention, compaction also periodically checks
  338. * need_resched() and either schedules in sync compaction or aborts async
  339. * compaction. This is similar to what compact_unlock_should_abort() does, but
  340. * is used where no lock is concerned.
  341. *
  342. * Returns false when no scheduling was needed, or sync compaction scheduled.
  343. * Returns true when async compaction should abort.
  344. */
  345. static inline bool compact_should_abort(struct compact_control *cc)
  346. {
  347. /* async compaction aborts if contended */
  348. if (need_resched()) {
  349. if (cc->mode == MIGRATE_ASYNC) {
  350. cc->contended = true;
  351. return true;
  352. }
  353. cond_resched();
  354. }
  355. return false;
  356. }
  357. /*
  358. * Isolate free pages onto a private freelist. If @strict is true, will abort
  359. * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
  360. * (even though it may still end up isolating some pages).
  361. */
  362. static unsigned long isolate_freepages_block(struct compact_control *cc,
  363. unsigned long *start_pfn,
  364. unsigned long end_pfn,
  365. struct list_head *freelist,
  366. bool strict)
  367. {
  368. int nr_scanned = 0, total_isolated = 0;
  369. struct page *cursor, *valid_page = NULL;
  370. unsigned long flags = 0;
  371. bool locked = false;
  372. unsigned long blockpfn = *start_pfn;
  373. unsigned int order;
  374. cursor = pfn_to_page(blockpfn);
  375. /* Isolate free pages. */
  376. for (; blockpfn < end_pfn; blockpfn++, cursor++) {
  377. int isolated;
  378. struct page *page = cursor;
  379. /*
  380. * Periodically drop the lock (if held) regardless of its
  381. * contention, to give chance to IRQs. Abort if fatal signal
  382. * pending or async compaction detects need_resched()
  383. */
  384. if (!(blockpfn % SWAP_CLUSTER_MAX)
  385. && compact_unlock_should_abort(&cc->zone->lock, flags,
  386. &locked, cc))
  387. break;
  388. nr_scanned++;
  389. if (!pfn_valid_within(blockpfn))
  390. goto isolate_fail;
  391. if (!valid_page)
  392. valid_page = page;
  393. /*
  394. * For compound pages such as THP and hugetlbfs, we can save
  395. * potentially a lot of iterations if we skip them at once.
  396. * The check is racy, but we can consider only valid values
  397. * and the only danger is skipping too much.
  398. */
  399. if (PageCompound(page)) {
  400. const unsigned int order = compound_order(page);
  401. if (likely(order < MAX_ORDER)) {
  402. blockpfn += (1UL << order) - 1;
  403. cursor += (1UL << order) - 1;
  404. }
  405. goto isolate_fail;
  406. }
  407. if (!PageBuddy(page))
  408. goto isolate_fail;
  409. /*
  410. * If we already hold the lock, we can skip some rechecking.
  411. * Note that if we hold the lock now, checked_pageblock was
  412. * already set in some previous iteration (or strict is true),
  413. * so it is correct to skip the suitable migration target
  414. * recheck as well.
  415. */
  416. if (!locked) {
  417. /*
  418. * The zone lock must be held to isolate freepages.
  419. * Unfortunately this is a very coarse lock and can be
  420. * heavily contended if there are parallel allocations
  421. * or parallel compactions. For async compaction do not
  422. * spin on the lock and we acquire the lock as late as
  423. * possible.
  424. */
  425. locked = compact_trylock_irqsave(&cc->zone->lock,
  426. &flags, cc);
  427. if (!locked)
  428. break;
  429. /* Recheck this is a buddy page under lock */
  430. if (!PageBuddy(page))
  431. goto isolate_fail;
  432. }
  433. /* Found a free page, will break it into order-0 pages */
  434. order = page_order(page);
  435. isolated = __isolate_free_page(page, order);
  436. if (!isolated)
  437. break;
  438. set_page_private(page, order);
  439. total_isolated += isolated;
  440. cc->nr_freepages += isolated;
  441. list_add_tail(&page->lru, freelist);
  442. if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
  443. blockpfn += isolated;
  444. break;
  445. }
  446. /* Advance to the end of split page */
  447. blockpfn += isolated - 1;
  448. cursor += isolated - 1;
  449. continue;
  450. isolate_fail:
  451. if (strict)
  452. break;
  453. else
  454. continue;
  455. }
  456. if (locked)
  457. spin_unlock_irqrestore(&cc->zone->lock, flags);
  458. /*
  459. * There is a tiny chance that we have read bogus compound_order(),
  460. * so be careful to not go outside of the pageblock.
  461. */
  462. if (unlikely(blockpfn > end_pfn))
  463. blockpfn = end_pfn;
  464. trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
  465. nr_scanned, total_isolated);
  466. /* Record how far we have got within the block */
  467. *start_pfn = blockpfn;
  468. /*
  469. * If strict isolation is requested by CMA then check that all the
  470. * pages requested were isolated. If there were any failures, 0 is
  471. * returned and CMA will fail.
  472. */
  473. if (strict && blockpfn < end_pfn)
  474. total_isolated = 0;
  475. /* Update the pageblock-skip if the whole pageblock was scanned */
  476. if (blockpfn == end_pfn)
  477. update_pageblock_skip(cc, valid_page, total_isolated, false);
  478. cc->total_free_scanned += nr_scanned;
  479. if (total_isolated)
  480. count_compact_events(COMPACTISOLATED, total_isolated);
  481. return total_isolated;
  482. }
  483. /**
  484. * isolate_freepages_range() - isolate free pages.
  485. * @cc: Compaction control structure.
  486. * @start_pfn: The first PFN to start isolating.
  487. * @end_pfn: The one-past-last PFN.
  488. *
  489. * Non-free pages, invalid PFNs, or zone boundaries within the
  490. * [start_pfn, end_pfn) range are considered errors, cause function to
  491. * undo its actions and return zero.
  492. *
  493. * Otherwise, function returns one-past-the-last PFN of isolated page
  494. * (which may be greater then end_pfn if end fell in a middle of
  495. * a free page).
  496. */
  497. unsigned long
  498. isolate_freepages_range(struct compact_control *cc,
  499. unsigned long start_pfn, unsigned long end_pfn)
  500. {
  501. unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
  502. LIST_HEAD(freelist);
  503. pfn = start_pfn;
  504. block_start_pfn = pageblock_start_pfn(pfn);
  505. if (block_start_pfn < cc->zone->zone_start_pfn)
  506. block_start_pfn = cc->zone->zone_start_pfn;
  507. block_end_pfn = pageblock_end_pfn(pfn);
  508. for (; pfn < end_pfn; pfn += isolated,
  509. block_start_pfn = block_end_pfn,
  510. block_end_pfn += pageblock_nr_pages) {
  511. /* Protect pfn from changing by isolate_freepages_block */
  512. unsigned long isolate_start_pfn = pfn;
  513. block_end_pfn = min(block_end_pfn, end_pfn);
  514. /*
  515. * pfn could pass the block_end_pfn if isolated freepage
  516. * is more than pageblock order. In this case, we adjust
  517. * scanning range to right one.
  518. */
  519. if (pfn >= block_end_pfn) {
  520. block_start_pfn = pageblock_start_pfn(pfn);
  521. block_end_pfn = pageblock_end_pfn(pfn);
  522. block_end_pfn = min(block_end_pfn, end_pfn);
  523. }
  524. if (!pageblock_pfn_to_page(block_start_pfn,
  525. block_end_pfn, cc->zone))
  526. break;
  527. isolated = isolate_freepages_block(cc, &isolate_start_pfn,
  528. block_end_pfn, &freelist, true);
  529. /*
  530. * In strict mode, isolate_freepages_block() returns 0 if
  531. * there are any holes in the block (ie. invalid PFNs or
  532. * non-free pages).
  533. */
  534. if (!isolated)
  535. break;
  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. /* __isolate_free_page() does not map the pages */
  543. map_pages(&freelist);
  544. if (pfn < end_pfn) {
  545. /* Loop terminated early, cleanup. */
  546. release_freepages(&freelist);
  547. return 0;
  548. }
  549. /* We don't use freelists for anything. */
  550. return pfn;
  551. }
  552. /* Similar to reclaim, but different enough that they don't share logic */
  553. static bool too_many_isolated(struct zone *zone)
  554. {
  555. unsigned long active, inactive, isolated;
  556. inactive = node_page_state(zone->zone_pgdat, NR_INACTIVE_FILE) +
  557. node_page_state(zone->zone_pgdat, NR_INACTIVE_ANON);
  558. active = node_page_state(zone->zone_pgdat, NR_ACTIVE_FILE) +
  559. node_page_state(zone->zone_pgdat, NR_ACTIVE_ANON);
  560. isolated = node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE) +
  561. node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON);
  562. return isolated > (inactive + active) / 2;
  563. }
  564. /**
  565. * isolate_migratepages_block() - isolate all migrate-able pages within
  566. * a single pageblock
  567. * @cc: Compaction control structure.
  568. * @low_pfn: The first PFN to isolate
  569. * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
  570. * @isolate_mode: Isolation mode to be used.
  571. *
  572. * Isolate all pages that can be migrated from the range specified by
  573. * [low_pfn, end_pfn). The range is expected to be within same pageblock.
  574. * Returns zero if there is a fatal signal pending, otherwise PFN of the
  575. * first page that was not scanned (which may be both less, equal to or more
  576. * than end_pfn).
  577. *
  578. * The pages are isolated on cc->migratepages list (not required to be empty),
  579. * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
  580. * is neither read nor updated.
  581. */
  582. static unsigned long
  583. isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
  584. unsigned long end_pfn, isolate_mode_t isolate_mode)
  585. {
  586. struct zone *zone = cc->zone;
  587. unsigned long nr_scanned = 0, nr_isolated = 0;
  588. struct lruvec *lruvec;
  589. unsigned long flags = 0;
  590. bool locked = false;
  591. struct page *page = NULL, *valid_page = NULL;
  592. unsigned long start_pfn = low_pfn;
  593. bool skip_on_failure = false;
  594. unsigned long next_skip_pfn = 0;
  595. /*
  596. * Ensure that there are not too many pages isolated from the LRU
  597. * list by either parallel reclaimers or compaction. If there are,
  598. * delay for some time until fewer pages are isolated
  599. */
  600. while (unlikely(too_many_isolated(zone))) {
  601. /* async migration should just abort */
  602. if (cc->mode == MIGRATE_ASYNC)
  603. return 0;
  604. congestion_wait(BLK_RW_ASYNC, HZ/10);
  605. if (fatal_signal_pending(current))
  606. return 0;
  607. }
  608. if (compact_should_abort(cc))
  609. return 0;
  610. if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
  611. skip_on_failure = true;
  612. next_skip_pfn = block_end_pfn(low_pfn, cc->order);
  613. }
  614. /* Time to isolate some pages for migration */
  615. for (; low_pfn < end_pfn; low_pfn++) {
  616. if (skip_on_failure && low_pfn >= next_skip_pfn) {
  617. /*
  618. * We have isolated all migration candidates in the
  619. * previous order-aligned block, and did not skip it due
  620. * to failure. We should migrate the pages now and
  621. * hopefully succeed compaction.
  622. */
  623. if (nr_isolated)
  624. break;
  625. /*
  626. * We failed to isolate in the previous order-aligned
  627. * block. Set the new boundary to the end of the
  628. * current block. Note we can't simply increase
  629. * next_skip_pfn by 1 << order, as low_pfn might have
  630. * been incremented by a higher number due to skipping
  631. * a compound or a high-order buddy page in the
  632. * previous loop iteration.
  633. */
  634. next_skip_pfn = block_end_pfn(low_pfn, cc->order);
  635. }
  636. /*
  637. * Periodically drop the lock (if held) regardless of its
  638. * contention, to give chance to IRQs. Abort async compaction
  639. * if contended.
  640. */
  641. if (!(low_pfn % SWAP_CLUSTER_MAX)
  642. && compact_unlock_should_abort(zone_lru_lock(zone), flags,
  643. &locked, cc))
  644. break;
  645. if (!pfn_valid_within(low_pfn))
  646. goto isolate_fail;
  647. nr_scanned++;
  648. page = pfn_to_page(low_pfn);
  649. if (!valid_page)
  650. valid_page = page;
  651. /*
  652. * Skip if free. We read page order here without zone lock
  653. * which is generally unsafe, but the race window is small and
  654. * the worst thing that can happen is that we skip some
  655. * potential isolation targets.
  656. */
  657. if (PageBuddy(page)) {
  658. unsigned long freepage_order = page_order_unsafe(page);
  659. /*
  660. * Without lock, we cannot be sure that what we got is
  661. * a valid page order. Consider only values in the
  662. * valid order range to prevent low_pfn overflow.
  663. */
  664. if (freepage_order > 0 && freepage_order < MAX_ORDER)
  665. low_pfn += (1UL << freepage_order) - 1;
  666. continue;
  667. }
  668. /*
  669. * Regardless of being on LRU, compound pages such as THP and
  670. * hugetlbfs are not to be compacted. We can potentially save
  671. * a lot of iterations if we skip them at once. The check is
  672. * racy, but we can consider only valid values and the only
  673. * danger is skipping too much.
  674. */
  675. if (PageCompound(page)) {
  676. const unsigned int order = compound_order(page);
  677. if (likely(order < MAX_ORDER))
  678. low_pfn += (1UL << order) - 1;
  679. goto isolate_fail;
  680. }
  681. /*
  682. * Check may be lockless but that's ok as we recheck later.
  683. * It's possible to migrate LRU and non-lru movable pages.
  684. * Skip any other type of page
  685. */
  686. if (!PageLRU(page)) {
  687. /*
  688. * __PageMovable can return false positive so we need
  689. * to verify it under page_lock.
  690. */
  691. if (unlikely(__PageMovable(page)) &&
  692. !PageIsolated(page)) {
  693. if (locked) {
  694. spin_unlock_irqrestore(zone_lru_lock(zone),
  695. flags);
  696. locked = false;
  697. }
  698. if (!isolate_movable_page(page, isolate_mode))
  699. goto isolate_success;
  700. }
  701. goto isolate_fail;
  702. }
  703. /*
  704. * Migration will fail if an anonymous page is pinned in memory,
  705. * so avoid taking lru_lock and isolating it unnecessarily in an
  706. * admittedly racy check.
  707. */
  708. if (!page_mapping(page) &&
  709. page_count(page) > page_mapcount(page))
  710. goto isolate_fail;
  711. /*
  712. * Only allow to migrate anonymous pages in GFP_NOFS context
  713. * because those do not depend on fs locks.
  714. */
  715. if (!(cc->gfp_mask & __GFP_FS) && page_mapping(page))
  716. goto isolate_fail;
  717. /* If we already hold the lock, we can skip some rechecking */
  718. if (!locked) {
  719. locked = compact_trylock_irqsave(zone_lru_lock(zone),
  720. &flags, cc);
  721. if (!locked)
  722. break;
  723. /* Recheck PageLRU and PageCompound under lock */
  724. if (!PageLRU(page))
  725. goto isolate_fail;
  726. /*
  727. * Page become compound since the non-locked check,
  728. * and it's on LRU. It can only be a THP so the order
  729. * is safe to read and it's 0 for tail pages.
  730. */
  731. if (unlikely(PageCompound(page))) {
  732. low_pfn += (1UL << compound_order(page)) - 1;
  733. goto isolate_fail;
  734. }
  735. }
  736. lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
  737. /* Try isolate the page */
  738. if (__isolate_lru_page(page, isolate_mode) != 0)
  739. goto isolate_fail;
  740. VM_BUG_ON_PAGE(PageCompound(page), page);
  741. /* Successfully isolated */
  742. del_page_from_lru_list(page, lruvec, page_lru(page));
  743. inc_node_page_state(page,
  744. NR_ISOLATED_ANON + page_is_file_cache(page));
  745. isolate_success:
  746. list_add(&page->lru, &cc->migratepages);
  747. cc->nr_migratepages++;
  748. nr_isolated++;
  749. /*
  750. * Record where we could have freed pages by migration and not
  751. * yet flushed them to buddy allocator.
  752. * - this is the lowest page that was isolated and likely be
  753. * then freed by migration.
  754. */
  755. if (!cc->last_migrated_pfn)
  756. cc->last_migrated_pfn = low_pfn;
  757. /* Avoid isolating too much */
  758. if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
  759. ++low_pfn;
  760. break;
  761. }
  762. continue;
  763. isolate_fail:
  764. if (!skip_on_failure)
  765. continue;
  766. /*
  767. * We have isolated some pages, but then failed. Release them
  768. * instead of migrating, as we cannot form the cc->order buddy
  769. * page anyway.
  770. */
  771. if (nr_isolated) {
  772. if (locked) {
  773. spin_unlock_irqrestore(zone_lru_lock(zone), flags);
  774. locked = false;
  775. }
  776. putback_movable_pages(&cc->migratepages);
  777. cc->nr_migratepages = 0;
  778. cc->last_migrated_pfn = 0;
  779. nr_isolated = 0;
  780. }
  781. if (low_pfn < next_skip_pfn) {
  782. low_pfn = next_skip_pfn - 1;
  783. /*
  784. * The check near the loop beginning would have updated
  785. * next_skip_pfn too, but this is a bit simpler.
  786. */
  787. next_skip_pfn += 1UL << cc->order;
  788. }
  789. }
  790. /*
  791. * The PageBuddy() check could have potentially brought us outside
  792. * the range to be scanned.
  793. */
  794. if (unlikely(low_pfn > end_pfn))
  795. low_pfn = end_pfn;
  796. if (locked)
  797. spin_unlock_irqrestore(zone_lru_lock(zone), flags);
  798. /*
  799. * Update the pageblock-skip information and cached scanner pfn,
  800. * if the whole pageblock was scanned without isolating any page.
  801. */
  802. if (low_pfn == end_pfn)
  803. update_pageblock_skip(cc, valid_page, nr_isolated, true);
  804. trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
  805. nr_scanned, nr_isolated);
  806. cc->total_migrate_scanned += nr_scanned;
  807. if (nr_isolated)
  808. count_compact_events(COMPACTISOLATED, nr_isolated);
  809. return low_pfn;
  810. }
  811. /**
  812. * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
  813. * @cc: Compaction control structure.
  814. * @start_pfn: The first PFN to start isolating.
  815. * @end_pfn: The one-past-last PFN.
  816. *
  817. * Returns zero if isolation fails fatally due to e.g. pending signal.
  818. * Otherwise, function returns one-past-the-last PFN of isolated page
  819. * (which may be greater than end_pfn if end fell in a middle of a THP page).
  820. */
  821. unsigned long
  822. isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
  823. unsigned long end_pfn)
  824. {
  825. unsigned long pfn, block_start_pfn, block_end_pfn;
  826. /* Scan block by block. First and last block may be incomplete */
  827. pfn = start_pfn;
  828. block_start_pfn = pageblock_start_pfn(pfn);
  829. if (block_start_pfn < cc->zone->zone_start_pfn)
  830. block_start_pfn = cc->zone->zone_start_pfn;
  831. block_end_pfn = pageblock_end_pfn(pfn);
  832. for (; pfn < end_pfn; pfn = block_end_pfn,
  833. block_start_pfn = block_end_pfn,
  834. block_end_pfn += pageblock_nr_pages) {
  835. block_end_pfn = min(block_end_pfn, end_pfn);
  836. if (!pageblock_pfn_to_page(block_start_pfn,
  837. block_end_pfn, cc->zone))
  838. continue;
  839. pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
  840. ISOLATE_UNEVICTABLE);
  841. if (!pfn)
  842. break;
  843. if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
  844. break;
  845. }
  846. return pfn;
  847. }
  848. #endif /* CONFIG_COMPACTION || CONFIG_CMA */
  849. #ifdef CONFIG_COMPACTION
  850. static bool suitable_migration_source(struct compact_control *cc,
  851. struct page *page)
  852. {
  853. int block_mt;
  854. if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
  855. return true;
  856. block_mt = get_pageblock_migratetype(page);
  857. if (cc->migratetype == MIGRATE_MOVABLE)
  858. return is_migrate_movable(block_mt);
  859. else
  860. return block_mt == cc->migratetype;
  861. }
  862. /* Returns true if the page is within a block suitable for migration to */
  863. static bool suitable_migration_target(struct compact_control *cc,
  864. struct page *page)
  865. {
  866. /* If the page is a large free page, then disallow migration */
  867. if (PageBuddy(page)) {
  868. /*
  869. * We are checking page_order without zone->lock taken. But
  870. * the only small danger is that we skip a potentially suitable
  871. * pageblock, so it's not worth to check order for valid range.
  872. */
  873. if (page_order_unsafe(page) >= pageblock_order)
  874. return false;
  875. }
  876. if (cc->ignore_block_suitable)
  877. return true;
  878. /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
  879. if (is_migrate_movable(get_pageblock_migratetype(page)))
  880. return true;
  881. /* Otherwise skip the block */
  882. return false;
  883. }
  884. /*
  885. * Test whether the free scanner has reached the same or lower pageblock than
  886. * the migration scanner, and compaction should thus terminate.
  887. */
  888. static inline bool compact_scanners_met(struct compact_control *cc)
  889. {
  890. return (cc->free_pfn >> pageblock_order)
  891. <= (cc->migrate_pfn >> pageblock_order);
  892. }
  893. /*
  894. * Based on information in the current compact_control, find blocks
  895. * suitable for isolating free pages from and then isolate them.
  896. */
  897. static void isolate_freepages(struct compact_control *cc)
  898. {
  899. struct zone *zone = cc->zone;
  900. struct page *page;
  901. unsigned long block_start_pfn; /* start of current pageblock */
  902. unsigned long isolate_start_pfn; /* exact pfn we start at */
  903. unsigned long block_end_pfn; /* end of current pageblock */
  904. unsigned long low_pfn; /* lowest pfn scanner is able to scan */
  905. struct list_head *freelist = &cc->freepages;
  906. /*
  907. * Initialise the free scanner. The starting point is where we last
  908. * successfully isolated from, zone-cached value, or the end of the
  909. * zone when isolating for the first time. For looping we also need
  910. * this pfn aligned down to the pageblock boundary, because we do
  911. * block_start_pfn -= pageblock_nr_pages in the for loop.
  912. * For ending point, take care when isolating in last pageblock of a
  913. * a zone which ends in the middle of a pageblock.
  914. * The low boundary is the end of the pageblock the migration scanner
  915. * is using.
  916. */
  917. isolate_start_pfn = cc->free_pfn;
  918. block_start_pfn = pageblock_start_pfn(cc->free_pfn);
  919. block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
  920. zone_end_pfn(zone));
  921. low_pfn = pageblock_end_pfn(cc->migrate_pfn);
  922. /*
  923. * Isolate free pages until enough are available to migrate the
  924. * pages on cc->migratepages. We stop searching if the migrate
  925. * and free page scanners meet or enough free pages are isolated.
  926. */
  927. for (; block_start_pfn >= low_pfn;
  928. block_end_pfn = block_start_pfn,
  929. block_start_pfn -= pageblock_nr_pages,
  930. isolate_start_pfn = block_start_pfn) {
  931. /*
  932. * This can iterate a massively long zone without finding any
  933. * suitable migration targets, so periodically check if we need
  934. * to schedule, or even abort async compaction.
  935. */
  936. if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
  937. && compact_should_abort(cc))
  938. break;
  939. page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
  940. zone);
  941. if (!page)
  942. continue;
  943. /* Check the block is suitable for migration */
  944. if (!suitable_migration_target(cc, page))
  945. continue;
  946. /* If isolation recently failed, do not retry */
  947. if (!isolation_suitable(cc, page))
  948. continue;
  949. /* Found a block suitable for isolating free pages from. */
  950. isolate_freepages_block(cc, &isolate_start_pfn, block_end_pfn,
  951. freelist, false);
  952. /*
  953. * If we isolated enough freepages, or aborted due to lock
  954. * contention, terminate.
  955. */
  956. if ((cc->nr_freepages >= cc->nr_migratepages)
  957. || cc->contended) {
  958. if (isolate_start_pfn >= block_end_pfn) {
  959. /*
  960. * Restart at previous pageblock if more
  961. * freepages can be isolated next time.
  962. */
  963. isolate_start_pfn =
  964. block_start_pfn - pageblock_nr_pages;
  965. }
  966. break;
  967. } else if (isolate_start_pfn < block_end_pfn) {
  968. /*
  969. * If isolation failed early, do not continue
  970. * needlessly.
  971. */
  972. break;
  973. }
  974. }
  975. /* __isolate_free_page() does not map the pages */
  976. map_pages(freelist);
  977. /*
  978. * Record where the free scanner will restart next time. Either we
  979. * broke from the loop and set isolate_start_pfn based on the last
  980. * call to isolate_freepages_block(), or we met the migration scanner
  981. * and the loop terminated due to isolate_start_pfn < low_pfn
  982. */
  983. cc->free_pfn = isolate_start_pfn;
  984. }
  985. /*
  986. * This is a migrate-callback that "allocates" freepages by taking pages
  987. * from the isolated freelists in the block we are migrating to.
  988. */
  989. static struct page *compaction_alloc(struct page *migratepage,
  990. unsigned long data)
  991. {
  992. struct compact_control *cc = (struct compact_control *)data;
  993. struct page *freepage;
  994. /*
  995. * Isolate free pages if necessary, and if we are not aborting due to
  996. * contention.
  997. */
  998. if (list_empty(&cc->freepages)) {
  999. if (!cc->contended)
  1000. isolate_freepages(cc);
  1001. if (list_empty(&cc->freepages))
  1002. return NULL;
  1003. }
  1004. freepage = list_entry(cc->freepages.next, struct page, lru);
  1005. list_del(&freepage->lru);
  1006. cc->nr_freepages--;
  1007. return freepage;
  1008. }
  1009. /*
  1010. * This is a migrate-callback that "frees" freepages back to the isolated
  1011. * freelist. All pages on the freelist are from the same zone, so there is no
  1012. * special handling needed for NUMA.
  1013. */
  1014. static void compaction_free(struct page *page, unsigned long data)
  1015. {
  1016. struct compact_control *cc = (struct compact_control *)data;
  1017. list_add(&page->lru, &cc->freepages);
  1018. cc->nr_freepages++;
  1019. }
  1020. /* possible outcome of isolate_migratepages */
  1021. typedef enum {
  1022. ISOLATE_ABORT, /* Abort compaction now */
  1023. ISOLATE_NONE, /* No pages isolated, continue scanning */
  1024. ISOLATE_SUCCESS, /* Pages isolated, migrate */
  1025. } isolate_migrate_t;
  1026. /*
  1027. * Allow userspace to control policy on scanning the unevictable LRU for
  1028. * compactable pages.
  1029. */
  1030. int sysctl_compact_unevictable_allowed __read_mostly = 1;
  1031. /*
  1032. * Isolate all pages that can be migrated from the first suitable block,
  1033. * starting at the block pointed to by the migrate scanner pfn within
  1034. * compact_control.
  1035. */
  1036. static isolate_migrate_t isolate_migratepages(struct zone *zone,
  1037. struct compact_control *cc)
  1038. {
  1039. unsigned long block_start_pfn;
  1040. unsigned long block_end_pfn;
  1041. unsigned long low_pfn;
  1042. struct page *page;
  1043. const isolate_mode_t isolate_mode =
  1044. (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
  1045. (cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
  1046. /*
  1047. * Start at where we last stopped, or beginning of the zone as
  1048. * initialized by compact_zone()
  1049. */
  1050. low_pfn = cc->migrate_pfn;
  1051. block_start_pfn = pageblock_start_pfn(low_pfn);
  1052. if (block_start_pfn < zone->zone_start_pfn)
  1053. block_start_pfn = zone->zone_start_pfn;
  1054. /* Only scan within a pageblock boundary */
  1055. block_end_pfn = pageblock_end_pfn(low_pfn);
  1056. /*
  1057. * Iterate over whole pageblocks until we find the first suitable.
  1058. * Do not cross the free scanner.
  1059. */
  1060. for (; block_end_pfn <= cc->free_pfn;
  1061. low_pfn = block_end_pfn,
  1062. block_start_pfn = block_end_pfn,
  1063. block_end_pfn += pageblock_nr_pages) {
  1064. /*
  1065. * This can potentially iterate a massively long zone with
  1066. * many pageblocks unsuitable, so periodically check if we
  1067. * need to schedule, or even abort async compaction.
  1068. */
  1069. if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
  1070. && compact_should_abort(cc))
  1071. break;
  1072. page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
  1073. zone);
  1074. if (!page)
  1075. continue;
  1076. /* If isolation recently failed, do not retry */
  1077. if (!isolation_suitable(cc, page))
  1078. continue;
  1079. /*
  1080. * For async compaction, also only scan in MOVABLE blocks.
  1081. * Async compaction is optimistic to see if the minimum amount
  1082. * of work satisfies the allocation.
  1083. */
  1084. if (!suitable_migration_source(cc, page))
  1085. continue;
  1086. /* Perform the isolation */
  1087. low_pfn = isolate_migratepages_block(cc, low_pfn,
  1088. block_end_pfn, isolate_mode);
  1089. if (!low_pfn || cc->contended)
  1090. return ISOLATE_ABORT;
  1091. /*
  1092. * Either we isolated something and proceed with migration. Or
  1093. * we failed and compact_zone should decide if we should
  1094. * continue or not.
  1095. */
  1096. break;
  1097. }
  1098. /* Record where migration scanner will be restarted. */
  1099. cc->migrate_pfn = low_pfn;
  1100. return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
  1101. }
  1102. /*
  1103. * order == -1 is expected when compacting via
  1104. * /proc/sys/vm/compact_memory
  1105. */
  1106. static inline bool is_via_compact_memory(int order)
  1107. {
  1108. return order == -1;
  1109. }
  1110. static enum compact_result __compact_finished(struct zone *zone,
  1111. struct compact_control *cc)
  1112. {
  1113. unsigned int order;
  1114. const int migratetype = cc->migratetype;
  1115. if (cc->contended || fatal_signal_pending(current))
  1116. return COMPACT_CONTENDED;
  1117. /* Compaction run completes if the migrate and free scanner meet */
  1118. if (compact_scanners_met(cc)) {
  1119. /* Let the next compaction start anew. */
  1120. reset_cached_positions(zone);
  1121. /*
  1122. * Mark that the PG_migrate_skip information should be cleared
  1123. * by kswapd when it goes to sleep. kcompactd does not set the
  1124. * flag itself as the decision to be clear should be directly
  1125. * based on an allocation request.
  1126. */
  1127. if (cc->direct_compaction)
  1128. zone->compact_blockskip_flush = true;
  1129. if (cc->whole_zone)
  1130. return COMPACT_COMPLETE;
  1131. else
  1132. return COMPACT_PARTIAL_SKIPPED;
  1133. }
  1134. if (is_via_compact_memory(cc->order))
  1135. return COMPACT_CONTINUE;
  1136. if (cc->finishing_block) {
  1137. /*
  1138. * We have finished the pageblock, but better check again that
  1139. * we really succeeded.
  1140. */
  1141. if (IS_ALIGNED(cc->migrate_pfn, pageblock_nr_pages))
  1142. cc->finishing_block = false;
  1143. else
  1144. return COMPACT_CONTINUE;
  1145. }
  1146. /* Direct compactor: Is a suitable page free? */
  1147. for (order = cc->order; order < MAX_ORDER; order++) {
  1148. struct free_area *area = &zone->free_area[order];
  1149. bool can_steal;
  1150. /* Job done if page is free of the right migratetype */
  1151. if (!list_empty(&area->free_list[migratetype]))
  1152. return COMPACT_SUCCESS;
  1153. #ifdef CONFIG_CMA
  1154. /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
  1155. if (migratetype == MIGRATE_MOVABLE &&
  1156. !list_empty(&area->free_list[MIGRATE_CMA]))
  1157. return COMPACT_SUCCESS;
  1158. #endif
  1159. /*
  1160. * Job done if allocation would steal freepages from
  1161. * other migratetype buddy lists.
  1162. */
  1163. if (find_suitable_fallback(area, order, migratetype,
  1164. true, &can_steal) != -1) {
  1165. /* movable pages are OK in any pageblock */
  1166. if (migratetype == MIGRATE_MOVABLE)
  1167. return COMPACT_SUCCESS;
  1168. /*
  1169. * We are stealing for a non-movable allocation. Make
  1170. * sure we finish compacting the current pageblock
  1171. * first so it is as free as possible and we won't
  1172. * have to steal another one soon. This only applies
  1173. * to sync compaction, as async compaction operates
  1174. * on pageblocks of the same migratetype.
  1175. */
  1176. if (cc->mode == MIGRATE_ASYNC ||
  1177. IS_ALIGNED(cc->migrate_pfn,
  1178. pageblock_nr_pages)) {
  1179. return COMPACT_SUCCESS;
  1180. }
  1181. cc->finishing_block = true;
  1182. return COMPACT_CONTINUE;
  1183. }
  1184. }
  1185. return COMPACT_NO_SUITABLE_PAGE;
  1186. }
  1187. static enum compact_result compact_finished(struct zone *zone,
  1188. struct compact_control *cc)
  1189. {
  1190. int ret;
  1191. ret = __compact_finished(zone, cc);
  1192. trace_mm_compaction_finished(zone, cc->order, ret);
  1193. if (ret == COMPACT_NO_SUITABLE_PAGE)
  1194. ret = COMPACT_CONTINUE;
  1195. return ret;
  1196. }
  1197. /*
  1198. * compaction_suitable: Is this suitable to run compaction on this zone now?
  1199. * Returns
  1200. * COMPACT_SKIPPED - If there are too few free pages for compaction
  1201. * COMPACT_SUCCESS - If the allocation would succeed without compaction
  1202. * COMPACT_CONTINUE - If compaction should run now
  1203. */
  1204. static enum compact_result __compaction_suitable(struct zone *zone, int order,
  1205. unsigned int alloc_flags,
  1206. int classzone_idx,
  1207. unsigned long wmark_target)
  1208. {
  1209. unsigned long watermark;
  1210. if (is_via_compact_memory(order))
  1211. return COMPACT_CONTINUE;
  1212. watermark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
  1213. /*
  1214. * If watermarks for high-order allocation are already met, there
  1215. * should be no need for compaction at all.
  1216. */
  1217. if (zone_watermark_ok(zone, order, watermark, classzone_idx,
  1218. alloc_flags))
  1219. return COMPACT_SUCCESS;
  1220. /*
  1221. * Watermarks for order-0 must be met for compaction to be able to
  1222. * isolate free pages for migration targets. This means that the
  1223. * watermark and alloc_flags have to match, or be more pessimistic than
  1224. * the check in __isolate_free_page(). We don't use the direct
  1225. * compactor's alloc_flags, as they are not relevant for freepage
  1226. * isolation. We however do use the direct compactor's classzone_idx to
  1227. * skip over zones where lowmem reserves would prevent allocation even
  1228. * if compaction succeeds.
  1229. * For costly orders, we require low watermark instead of min for
  1230. * compaction to proceed to increase its chances.
  1231. * ALLOC_CMA is used, as pages in CMA pageblocks are considered
  1232. * suitable migration targets
  1233. */
  1234. watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
  1235. low_wmark_pages(zone) : min_wmark_pages(zone);
  1236. watermark += compact_gap(order);
  1237. if (!__zone_watermark_ok(zone, 0, watermark, classzone_idx,
  1238. ALLOC_CMA, wmark_target))
  1239. return COMPACT_SKIPPED;
  1240. return COMPACT_CONTINUE;
  1241. }
  1242. enum compact_result compaction_suitable(struct zone *zone, int order,
  1243. unsigned int alloc_flags,
  1244. int classzone_idx)
  1245. {
  1246. enum compact_result ret;
  1247. int fragindex;
  1248. ret = __compaction_suitable(zone, order, alloc_flags, classzone_idx,
  1249. zone_page_state(zone, NR_FREE_PAGES));
  1250. /*
  1251. * fragmentation index determines if allocation failures are due to
  1252. * low memory or external fragmentation
  1253. *
  1254. * index of -1000 would imply allocations might succeed depending on
  1255. * watermarks, but we already failed the high-order watermark check
  1256. * index towards 0 implies failure is due to lack of memory
  1257. * index towards 1000 implies failure is due to fragmentation
  1258. *
  1259. * Only compact if a failure would be due to fragmentation. Also
  1260. * ignore fragindex for non-costly orders where the alternative to
  1261. * a successful reclaim/compaction is OOM. Fragindex and the
  1262. * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
  1263. * excessive compaction for costly orders, but it should not be at the
  1264. * expense of system stability.
  1265. */
  1266. if (ret == COMPACT_CONTINUE && (order > PAGE_ALLOC_COSTLY_ORDER)) {
  1267. fragindex = fragmentation_index(zone, order);
  1268. if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
  1269. ret = COMPACT_NOT_SUITABLE_ZONE;
  1270. }
  1271. trace_mm_compaction_suitable(zone, order, ret);
  1272. if (ret == COMPACT_NOT_SUITABLE_ZONE)
  1273. ret = COMPACT_SKIPPED;
  1274. return ret;
  1275. }
  1276. bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
  1277. int alloc_flags)
  1278. {
  1279. struct zone *zone;
  1280. struct zoneref *z;
  1281. /*
  1282. * Make sure at least one zone would pass __compaction_suitable if we continue
  1283. * retrying the reclaim.
  1284. */
  1285. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
  1286. ac->nodemask) {
  1287. unsigned long available;
  1288. enum compact_result compact_result;
  1289. /*
  1290. * Do not consider all the reclaimable memory because we do not
  1291. * want to trash just for a single high order allocation which
  1292. * is even not guaranteed to appear even if __compaction_suitable
  1293. * is happy about the watermark check.
  1294. */
  1295. available = zone_reclaimable_pages(zone) / order;
  1296. available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  1297. compact_result = __compaction_suitable(zone, order, alloc_flags,
  1298. ac_classzone_idx(ac), available);
  1299. if (compact_result != COMPACT_SKIPPED)
  1300. return true;
  1301. }
  1302. return false;
  1303. }
  1304. static enum compact_result compact_zone(struct zone *zone, struct compact_control *cc)
  1305. {
  1306. enum compact_result ret;
  1307. unsigned long start_pfn = zone->zone_start_pfn;
  1308. unsigned long end_pfn = zone_end_pfn(zone);
  1309. const bool sync = cc->mode != MIGRATE_ASYNC;
  1310. cc->migratetype = gfpflags_to_migratetype(cc->gfp_mask);
  1311. ret = compaction_suitable(zone, cc->order, cc->alloc_flags,
  1312. cc->classzone_idx);
  1313. /* Compaction is likely to fail */
  1314. if (ret == COMPACT_SUCCESS || ret == COMPACT_SKIPPED)
  1315. return ret;
  1316. /* huh, compaction_suitable is returning something unexpected */
  1317. VM_BUG_ON(ret != COMPACT_CONTINUE);
  1318. /*
  1319. * Clear pageblock skip if there were failures recently and compaction
  1320. * is about to be retried after being deferred.
  1321. */
  1322. if (compaction_restarting(zone, cc->order))
  1323. __reset_isolation_suitable(zone);
  1324. /*
  1325. * Setup to move all movable pages to the end of the zone. Used cached
  1326. * information on where the scanners should start (unless we explicitly
  1327. * want to compact the whole zone), but check that it is initialised
  1328. * by ensuring the values are within zone boundaries.
  1329. */
  1330. if (cc->whole_zone) {
  1331. cc->migrate_pfn = start_pfn;
  1332. cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
  1333. } else {
  1334. cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
  1335. cc->free_pfn = zone->compact_cached_free_pfn;
  1336. if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
  1337. cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
  1338. zone->compact_cached_free_pfn = cc->free_pfn;
  1339. }
  1340. if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
  1341. cc->migrate_pfn = start_pfn;
  1342. zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
  1343. zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
  1344. }
  1345. if (cc->migrate_pfn == start_pfn)
  1346. cc->whole_zone = true;
  1347. }
  1348. cc->last_migrated_pfn = 0;
  1349. trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
  1350. cc->free_pfn, end_pfn, sync);
  1351. migrate_prep_local();
  1352. while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
  1353. int err;
  1354. switch (isolate_migratepages(zone, cc)) {
  1355. case ISOLATE_ABORT:
  1356. ret = COMPACT_CONTENDED;
  1357. putback_movable_pages(&cc->migratepages);
  1358. cc->nr_migratepages = 0;
  1359. goto out;
  1360. case ISOLATE_NONE:
  1361. /*
  1362. * We haven't isolated and migrated anything, but
  1363. * there might still be unflushed migrations from
  1364. * previous cc->order aligned block.
  1365. */
  1366. goto check_drain;
  1367. case ISOLATE_SUCCESS:
  1368. ;
  1369. }
  1370. err = migrate_pages(&cc->migratepages, compaction_alloc,
  1371. compaction_free, (unsigned long)cc, cc->mode,
  1372. MR_COMPACTION);
  1373. trace_mm_compaction_migratepages(cc->nr_migratepages, err,
  1374. &cc->migratepages);
  1375. /* All pages were either migrated or will be released */
  1376. cc->nr_migratepages = 0;
  1377. if (err) {
  1378. putback_movable_pages(&cc->migratepages);
  1379. /*
  1380. * migrate_pages() may return -ENOMEM when scanners meet
  1381. * and we want compact_finished() to detect it
  1382. */
  1383. if (err == -ENOMEM && !compact_scanners_met(cc)) {
  1384. ret = COMPACT_CONTENDED;
  1385. goto out;
  1386. }
  1387. /*
  1388. * We failed to migrate at least one page in the current
  1389. * order-aligned block, so skip the rest of it.
  1390. */
  1391. if (cc->direct_compaction &&
  1392. (cc->mode == MIGRATE_ASYNC)) {
  1393. cc->migrate_pfn = block_end_pfn(
  1394. cc->migrate_pfn - 1, cc->order);
  1395. /* Draining pcplists is useless in this case */
  1396. cc->last_migrated_pfn = 0;
  1397. }
  1398. }
  1399. check_drain:
  1400. /*
  1401. * Has the migration scanner moved away from the previous
  1402. * cc->order aligned block where we migrated from? If yes,
  1403. * flush the pages that were freed, so that they can merge and
  1404. * compact_finished() can detect immediately if allocation
  1405. * would succeed.
  1406. */
  1407. if (cc->order > 0 && cc->last_migrated_pfn) {
  1408. int cpu;
  1409. unsigned long current_block_start =
  1410. block_start_pfn(cc->migrate_pfn, cc->order);
  1411. if (cc->last_migrated_pfn < current_block_start) {
  1412. cpu = get_cpu();
  1413. lru_add_drain_cpu(cpu);
  1414. drain_local_pages(zone);
  1415. put_cpu();
  1416. /* No more flushing until we migrate again */
  1417. cc->last_migrated_pfn = 0;
  1418. }
  1419. }
  1420. }
  1421. out:
  1422. /*
  1423. * Release free pages and update where the free scanner should restart,
  1424. * so we don't leave any returned pages behind in the next attempt.
  1425. */
  1426. if (cc->nr_freepages > 0) {
  1427. unsigned long free_pfn = release_freepages(&cc->freepages);
  1428. cc->nr_freepages = 0;
  1429. VM_BUG_ON(free_pfn == 0);
  1430. /* The cached pfn is always the first in a pageblock */
  1431. free_pfn = pageblock_start_pfn(free_pfn);
  1432. /*
  1433. * Only go back, not forward. The cached pfn might have been
  1434. * already reset to zone end in compact_finished()
  1435. */
  1436. if (free_pfn > zone->compact_cached_free_pfn)
  1437. zone->compact_cached_free_pfn = free_pfn;
  1438. }
  1439. count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
  1440. count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
  1441. trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
  1442. cc->free_pfn, end_pfn, sync, ret);
  1443. return ret;
  1444. }
  1445. static enum compact_result compact_zone_order(struct zone *zone, int order,
  1446. gfp_t gfp_mask, enum compact_priority prio,
  1447. unsigned int alloc_flags, int classzone_idx)
  1448. {
  1449. enum compact_result ret;
  1450. struct compact_control cc = {
  1451. .nr_freepages = 0,
  1452. .nr_migratepages = 0,
  1453. .total_migrate_scanned = 0,
  1454. .total_free_scanned = 0,
  1455. .order = order,
  1456. .gfp_mask = gfp_mask,
  1457. .zone = zone,
  1458. .mode = (prio == COMPACT_PRIO_ASYNC) ?
  1459. MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT,
  1460. .alloc_flags = alloc_flags,
  1461. .classzone_idx = classzone_idx,
  1462. .direct_compaction = true,
  1463. .whole_zone = (prio == MIN_COMPACT_PRIORITY),
  1464. .ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
  1465. .ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
  1466. };
  1467. INIT_LIST_HEAD(&cc.freepages);
  1468. INIT_LIST_HEAD(&cc.migratepages);
  1469. ret = compact_zone(zone, &cc);
  1470. VM_BUG_ON(!list_empty(&cc.freepages));
  1471. VM_BUG_ON(!list_empty(&cc.migratepages));
  1472. return ret;
  1473. }
  1474. int sysctl_extfrag_threshold = 500;
  1475. /**
  1476. * try_to_compact_pages - Direct compact to satisfy a high-order allocation
  1477. * @gfp_mask: The GFP mask of the current allocation
  1478. * @order: The order of the current allocation
  1479. * @alloc_flags: The allocation flags of the current allocation
  1480. * @ac: The context of current allocation
  1481. * @prio: Determines how hard direct compaction should try to succeed
  1482. *
  1483. * This is the main entry point for direct page compaction.
  1484. */
  1485. enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
  1486. unsigned int alloc_flags, const struct alloc_context *ac,
  1487. enum compact_priority prio)
  1488. {
  1489. int may_perform_io = gfp_mask & __GFP_IO;
  1490. struct zoneref *z;
  1491. struct zone *zone;
  1492. enum compact_result rc = COMPACT_SKIPPED;
  1493. /*
  1494. * Check if the GFP flags allow compaction - GFP_NOIO is really
  1495. * tricky context because the migration might require IO
  1496. */
  1497. if (!may_perform_io)
  1498. return COMPACT_SKIPPED;
  1499. trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
  1500. /* Compact each zone in the list */
  1501. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
  1502. ac->nodemask) {
  1503. enum compact_result status;
  1504. if (prio > MIN_COMPACT_PRIORITY
  1505. && compaction_deferred(zone, order)) {
  1506. rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
  1507. continue;
  1508. }
  1509. status = compact_zone_order(zone, order, gfp_mask, prio,
  1510. alloc_flags, ac_classzone_idx(ac));
  1511. rc = max(status, rc);
  1512. /* The allocation should succeed, stop compacting */
  1513. if (status == COMPACT_SUCCESS) {
  1514. /*
  1515. * We think the allocation will succeed in this zone,
  1516. * but it is not certain, hence the false. The caller
  1517. * will repeat this with true if allocation indeed
  1518. * succeeds in this zone.
  1519. */
  1520. compaction_defer_reset(zone, order, false);
  1521. break;
  1522. }
  1523. if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
  1524. status == COMPACT_PARTIAL_SKIPPED))
  1525. /*
  1526. * We think that allocation won't succeed in this zone
  1527. * so we defer compaction there. If it ends up
  1528. * succeeding after all, it will be reset.
  1529. */
  1530. defer_compaction(zone, order);
  1531. /*
  1532. * We might have stopped compacting due to need_resched() in
  1533. * async compaction, or due to a fatal signal detected. In that
  1534. * case do not try further zones
  1535. */
  1536. if ((prio == COMPACT_PRIO_ASYNC && need_resched())
  1537. || fatal_signal_pending(current))
  1538. break;
  1539. }
  1540. return rc;
  1541. }
  1542. /* Compact all zones within a node */
  1543. static void compact_node(int nid)
  1544. {
  1545. pg_data_t *pgdat = NODE_DATA(nid);
  1546. int zoneid;
  1547. struct zone *zone;
  1548. struct compact_control cc = {
  1549. .order = -1,
  1550. .total_migrate_scanned = 0,
  1551. .total_free_scanned = 0,
  1552. .mode = MIGRATE_SYNC,
  1553. .ignore_skip_hint = true,
  1554. .whole_zone = true,
  1555. .gfp_mask = GFP_KERNEL,
  1556. };
  1557. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  1558. zone = &pgdat->node_zones[zoneid];
  1559. if (!populated_zone(zone))
  1560. continue;
  1561. cc.nr_freepages = 0;
  1562. cc.nr_migratepages = 0;
  1563. cc.zone = zone;
  1564. INIT_LIST_HEAD(&cc.freepages);
  1565. INIT_LIST_HEAD(&cc.migratepages);
  1566. compact_zone(zone, &cc);
  1567. VM_BUG_ON(!list_empty(&cc.freepages));
  1568. VM_BUG_ON(!list_empty(&cc.migratepages));
  1569. }
  1570. }
  1571. /* Compact all nodes in the system */
  1572. static void compact_nodes(void)
  1573. {
  1574. int nid;
  1575. /* Flush pending updates to the LRU lists */
  1576. lru_add_drain_all();
  1577. for_each_online_node(nid)
  1578. compact_node(nid);
  1579. }
  1580. /* The written value is actually unused, all memory is compacted */
  1581. int sysctl_compact_memory;
  1582. /*
  1583. * This is the entry point for compacting all nodes via
  1584. * /proc/sys/vm/compact_memory
  1585. */
  1586. int sysctl_compaction_handler(struct ctl_table *table, int write,
  1587. void __user *buffer, size_t *length, loff_t *ppos)
  1588. {
  1589. if (write)
  1590. compact_nodes();
  1591. return 0;
  1592. }
  1593. int sysctl_extfrag_handler(struct ctl_table *table, int write,
  1594. void __user *buffer, size_t *length, loff_t *ppos)
  1595. {
  1596. proc_dointvec_minmax(table, write, buffer, length, ppos);
  1597. return 0;
  1598. }
  1599. #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
  1600. static ssize_t sysfs_compact_node(struct device *dev,
  1601. struct device_attribute *attr,
  1602. const char *buf, size_t count)
  1603. {
  1604. int nid = dev->id;
  1605. if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
  1606. /* Flush pending updates to the LRU lists */
  1607. lru_add_drain_all();
  1608. compact_node(nid);
  1609. }
  1610. return count;
  1611. }
  1612. static DEVICE_ATTR(compact, 0200, NULL, sysfs_compact_node);
  1613. int compaction_register_node(struct node *node)
  1614. {
  1615. return device_create_file(&node->dev, &dev_attr_compact);
  1616. }
  1617. void compaction_unregister_node(struct node *node)
  1618. {
  1619. return device_remove_file(&node->dev, &dev_attr_compact);
  1620. }
  1621. #endif /* CONFIG_SYSFS && CONFIG_NUMA */
  1622. static inline bool kcompactd_work_requested(pg_data_t *pgdat)
  1623. {
  1624. return pgdat->kcompactd_max_order > 0 || kthread_should_stop();
  1625. }
  1626. static bool kcompactd_node_suitable(pg_data_t *pgdat)
  1627. {
  1628. int zoneid;
  1629. struct zone *zone;
  1630. enum zone_type classzone_idx = pgdat->kcompactd_classzone_idx;
  1631. for (zoneid = 0; zoneid <= classzone_idx; zoneid++) {
  1632. zone = &pgdat->node_zones[zoneid];
  1633. if (!populated_zone(zone))
  1634. continue;
  1635. if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
  1636. classzone_idx) == COMPACT_CONTINUE)
  1637. return true;
  1638. }
  1639. return false;
  1640. }
  1641. static void kcompactd_do_work(pg_data_t *pgdat)
  1642. {
  1643. /*
  1644. * With no special task, compact all zones so that a page of requested
  1645. * order is allocatable.
  1646. */
  1647. int zoneid;
  1648. struct zone *zone;
  1649. struct compact_control cc = {
  1650. .order = pgdat->kcompactd_max_order,
  1651. .total_migrate_scanned = 0,
  1652. .total_free_scanned = 0,
  1653. .classzone_idx = pgdat->kcompactd_classzone_idx,
  1654. .mode = MIGRATE_SYNC_LIGHT,
  1655. .ignore_skip_hint = false,
  1656. .gfp_mask = GFP_KERNEL,
  1657. };
  1658. trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
  1659. cc.classzone_idx);
  1660. count_compact_event(KCOMPACTD_WAKE);
  1661. for (zoneid = 0; zoneid <= cc.classzone_idx; zoneid++) {
  1662. int status;
  1663. zone = &pgdat->node_zones[zoneid];
  1664. if (!populated_zone(zone))
  1665. continue;
  1666. if (compaction_deferred(zone, cc.order))
  1667. continue;
  1668. if (compaction_suitable(zone, cc.order, 0, zoneid) !=
  1669. COMPACT_CONTINUE)
  1670. continue;
  1671. cc.nr_freepages = 0;
  1672. cc.nr_migratepages = 0;
  1673. cc.total_migrate_scanned = 0;
  1674. cc.total_free_scanned = 0;
  1675. cc.zone = zone;
  1676. INIT_LIST_HEAD(&cc.freepages);
  1677. INIT_LIST_HEAD(&cc.migratepages);
  1678. if (kthread_should_stop())
  1679. return;
  1680. status = compact_zone(zone, &cc);
  1681. if (status == COMPACT_SUCCESS) {
  1682. compaction_defer_reset(zone, cc.order, false);
  1683. } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
  1684. /*
  1685. * Buddy pages may become stranded on pcps that could
  1686. * otherwise coalesce on the zone's free area for
  1687. * order >= cc.order. This is ratelimited by the
  1688. * upcoming deferral.
  1689. */
  1690. drain_all_pages(zone);
  1691. /*
  1692. * We use sync migration mode here, so we defer like
  1693. * sync direct compaction does.
  1694. */
  1695. defer_compaction(zone, cc.order);
  1696. }
  1697. count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
  1698. cc.total_migrate_scanned);
  1699. count_compact_events(KCOMPACTD_FREE_SCANNED,
  1700. cc.total_free_scanned);
  1701. VM_BUG_ON(!list_empty(&cc.freepages));
  1702. VM_BUG_ON(!list_empty(&cc.migratepages));
  1703. }
  1704. /*
  1705. * Regardless of success, we are done until woken up next. But remember
  1706. * the requested order/classzone_idx in case it was higher/tighter than
  1707. * our current ones
  1708. */
  1709. if (pgdat->kcompactd_max_order <= cc.order)
  1710. pgdat->kcompactd_max_order = 0;
  1711. if (pgdat->kcompactd_classzone_idx >= cc.classzone_idx)
  1712. pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
  1713. }
  1714. void wakeup_kcompactd(pg_data_t *pgdat, int order, int classzone_idx)
  1715. {
  1716. if (!order)
  1717. return;
  1718. if (pgdat->kcompactd_max_order < order)
  1719. pgdat->kcompactd_max_order = order;
  1720. if (pgdat->kcompactd_classzone_idx > classzone_idx)
  1721. pgdat->kcompactd_classzone_idx = classzone_idx;
  1722. /*
  1723. * Pairs with implicit barrier in wait_event_freezable()
  1724. * such that wakeups are not missed.
  1725. */
  1726. if (!wq_has_sleeper(&pgdat->kcompactd_wait))
  1727. return;
  1728. if (!kcompactd_node_suitable(pgdat))
  1729. return;
  1730. trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
  1731. classzone_idx);
  1732. wake_up_interruptible(&pgdat->kcompactd_wait);
  1733. }
  1734. /*
  1735. * The background compaction daemon, started as a kernel thread
  1736. * from the init process.
  1737. */
  1738. static int kcompactd(void *p)
  1739. {
  1740. pg_data_t *pgdat = (pg_data_t*)p;
  1741. struct task_struct *tsk = current;
  1742. const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
  1743. if (!cpumask_empty(cpumask))
  1744. set_cpus_allowed_ptr(tsk, cpumask);
  1745. set_freezable();
  1746. pgdat->kcompactd_max_order = 0;
  1747. pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
  1748. while (!kthread_should_stop()) {
  1749. unsigned long pflags;
  1750. trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
  1751. wait_event_freezable(pgdat->kcompactd_wait,
  1752. kcompactd_work_requested(pgdat));
  1753. psi_memstall_enter(&pflags);
  1754. kcompactd_do_work(pgdat);
  1755. psi_memstall_leave(&pflags);
  1756. }
  1757. return 0;
  1758. }
  1759. /*
  1760. * This kcompactd start function will be called by init and node-hot-add.
  1761. * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
  1762. */
  1763. int kcompactd_run(int nid)
  1764. {
  1765. pg_data_t *pgdat = NODE_DATA(nid);
  1766. int ret = 0;
  1767. if (pgdat->kcompactd)
  1768. return 0;
  1769. pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
  1770. if (IS_ERR(pgdat->kcompactd)) {
  1771. pr_err("Failed to start kcompactd on node %d\n", nid);
  1772. ret = PTR_ERR(pgdat->kcompactd);
  1773. pgdat->kcompactd = NULL;
  1774. }
  1775. return ret;
  1776. }
  1777. /*
  1778. * Called by memory hotplug when all memory in a node is offlined. Caller must
  1779. * hold mem_hotplug_begin/end().
  1780. */
  1781. void kcompactd_stop(int nid)
  1782. {
  1783. struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
  1784. if (kcompactd) {
  1785. kthread_stop(kcompactd);
  1786. NODE_DATA(nid)->kcompactd = NULL;
  1787. }
  1788. }
  1789. /*
  1790. * It's optimal to keep kcompactd on the same CPUs as their memory, but
  1791. * not required for correctness. So if the last cpu in a node goes
  1792. * away, we get changed to run anywhere: as the first one comes back,
  1793. * restore their cpu bindings.
  1794. */
  1795. static int kcompactd_cpu_online(unsigned int cpu)
  1796. {
  1797. int nid;
  1798. for_each_node_state(nid, N_MEMORY) {
  1799. pg_data_t *pgdat = NODE_DATA(nid);
  1800. const struct cpumask *mask;
  1801. mask = cpumask_of_node(pgdat->node_id);
  1802. if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
  1803. /* One of our CPUs online: restore mask */
  1804. set_cpus_allowed_ptr(pgdat->kcompactd, mask);
  1805. }
  1806. return 0;
  1807. }
  1808. static int __init kcompactd_init(void)
  1809. {
  1810. int nid;
  1811. int ret;
  1812. ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
  1813. "mm/compaction:online",
  1814. kcompactd_cpu_online, NULL);
  1815. if (ret < 0) {
  1816. pr_err("kcompactd: failed to register hotplug callbacks.\n");
  1817. return ret;
  1818. }
  1819. for_each_node_state(nid, N_MEMORY)
  1820. kcompactd_run(nid);
  1821. return 0;
  1822. }
  1823. subsys_initcall(kcompactd_init)
  1824. #endif /* CONFIG_COMPACTION */