compaction.c 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007
  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. /*
  48. * Fragmentation score check interval for proactive compaction purposes.
  49. */
  50. static const unsigned int HPAGE_FRAG_CHECK_INTERVAL_MSEC = 500;
  51. /*
  52. * Page order with-respect-to which proactive compaction
  53. * calculates external fragmentation, which is used as
  54. * the "fragmentation score" of a node/zone.
  55. */
  56. #if defined CONFIG_TRANSPARENT_HUGEPAGE
  57. #define COMPACTION_HPAGE_ORDER HPAGE_PMD_ORDER
  58. #elif defined CONFIG_HUGETLBFS
  59. #define COMPACTION_HPAGE_ORDER HUGETLB_PAGE_ORDER
  60. #else
  61. #define COMPACTION_HPAGE_ORDER (PMD_SHIFT - PAGE_SHIFT)
  62. #endif
  63. static unsigned long release_freepages(struct list_head *freelist)
  64. {
  65. struct page *page, *next;
  66. unsigned long high_pfn = 0;
  67. list_for_each_entry_safe(page, next, freelist, lru) {
  68. unsigned long pfn = page_to_pfn(page);
  69. list_del(&page->lru);
  70. __free_page(page);
  71. if (pfn > high_pfn)
  72. high_pfn = pfn;
  73. }
  74. return high_pfn;
  75. }
  76. static void split_map_pages(struct list_head *list)
  77. {
  78. unsigned int i, order, nr_pages;
  79. struct page *page, *next;
  80. LIST_HEAD(tmp_list);
  81. list_for_each_entry_safe(page, next, list, lru) {
  82. list_del(&page->lru);
  83. order = page_private(page);
  84. nr_pages = 1 << order;
  85. post_alloc_hook(page, order, __GFP_MOVABLE);
  86. if (order)
  87. split_page(page, order);
  88. for (i = 0; i < nr_pages; i++) {
  89. list_add(&page->lru, &tmp_list);
  90. page++;
  91. }
  92. }
  93. list_splice(&tmp_list, list);
  94. }
  95. #ifdef CONFIG_COMPACTION
  96. int PageMovable(struct page *page)
  97. {
  98. struct address_space *mapping;
  99. VM_BUG_ON_PAGE(!PageLocked(page), page);
  100. if (!__PageMovable(page))
  101. return 0;
  102. mapping = page_mapping(page);
  103. if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
  104. return 1;
  105. return 0;
  106. }
  107. EXPORT_SYMBOL(PageMovable);
  108. void __SetPageMovable(struct page *page, struct address_space *mapping)
  109. {
  110. VM_BUG_ON_PAGE(!PageLocked(page), page);
  111. VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
  112. page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
  113. }
  114. EXPORT_SYMBOL(__SetPageMovable);
  115. void __ClearPageMovable(struct page *page)
  116. {
  117. VM_BUG_ON_PAGE(!PageLocked(page), page);
  118. VM_BUG_ON_PAGE(!PageMovable(page), page);
  119. /*
  120. * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
  121. * flag so that VM can catch up released page by driver after isolation.
  122. * With it, VM migration doesn't try to put it back.
  123. */
  124. page->mapping = (void *)((unsigned long)page->mapping &
  125. PAGE_MAPPING_MOVABLE);
  126. }
  127. EXPORT_SYMBOL(__ClearPageMovable);
  128. /* Do not skip compaction more than 64 times */
  129. #define COMPACT_MAX_DEFER_SHIFT 6
  130. /*
  131. * Compaction is deferred when compaction fails to result in a page
  132. * allocation success. 1 << compact_defer_shift, compactions are skipped up
  133. * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
  134. */
  135. void defer_compaction(struct zone *zone, int order)
  136. {
  137. zone->compact_considered = 0;
  138. zone->compact_defer_shift++;
  139. if (order < zone->compact_order_failed)
  140. zone->compact_order_failed = order;
  141. if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
  142. zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
  143. trace_mm_compaction_defer_compaction(zone, order);
  144. }
  145. /* Returns true if compaction should be skipped this time */
  146. bool compaction_deferred(struct zone *zone, int order)
  147. {
  148. unsigned long defer_limit = 1UL << zone->compact_defer_shift;
  149. if (order < zone->compact_order_failed)
  150. return false;
  151. /* Avoid possible overflow */
  152. if (++zone->compact_considered >= defer_limit) {
  153. zone->compact_considered = defer_limit;
  154. return false;
  155. }
  156. trace_mm_compaction_deferred(zone, order);
  157. return true;
  158. }
  159. /*
  160. * Update defer tracking counters after successful compaction of given order,
  161. * which means an allocation either succeeded (alloc_success == true) or is
  162. * expected to succeed.
  163. */
  164. void compaction_defer_reset(struct zone *zone, int order,
  165. bool alloc_success)
  166. {
  167. if (alloc_success) {
  168. zone->compact_considered = 0;
  169. zone->compact_defer_shift = 0;
  170. }
  171. if (order >= zone->compact_order_failed)
  172. zone->compact_order_failed = order + 1;
  173. trace_mm_compaction_defer_reset(zone, order);
  174. }
  175. /* Returns true if restarting compaction after many failures */
  176. bool compaction_restarting(struct zone *zone, int order)
  177. {
  178. if (order < zone->compact_order_failed)
  179. return false;
  180. return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
  181. zone->compact_considered >= 1UL << zone->compact_defer_shift;
  182. }
  183. /* Returns true if the pageblock should be scanned for pages to isolate. */
  184. static inline bool isolation_suitable(struct compact_control *cc,
  185. struct page *page)
  186. {
  187. if (cc->ignore_skip_hint)
  188. return true;
  189. return !get_pageblock_skip(page);
  190. }
  191. static void reset_cached_positions(struct zone *zone)
  192. {
  193. zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
  194. zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
  195. zone->compact_cached_free_pfn =
  196. pageblock_start_pfn(zone_end_pfn(zone) - 1);
  197. }
  198. /*
  199. * Compound pages of >= pageblock_order should consistenly be skipped until
  200. * released. It is always pointless to compact pages of such order (if they are
  201. * migratable), and the pageblocks they occupy cannot contain any free pages.
  202. */
  203. static bool pageblock_skip_persistent(struct page *page)
  204. {
  205. if (!PageCompound(page))
  206. return false;
  207. page = compound_head(page);
  208. if (compound_order(page) >= pageblock_order)
  209. return true;
  210. return false;
  211. }
  212. static bool
  213. __reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
  214. bool check_target)
  215. {
  216. struct page *page = pfn_to_online_page(pfn);
  217. struct page *block_page;
  218. struct page *end_page;
  219. unsigned long block_pfn;
  220. if (!page)
  221. return false;
  222. if (zone != page_zone(page))
  223. return false;
  224. if (pageblock_skip_persistent(page))
  225. return false;
  226. /*
  227. * If skip is already cleared do no further checking once the
  228. * restart points have been set.
  229. */
  230. if (check_source && check_target && !get_pageblock_skip(page))
  231. return true;
  232. /*
  233. * If clearing skip for the target scanner, do not select a
  234. * non-movable pageblock as the starting point.
  235. */
  236. if (!check_source && check_target &&
  237. get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
  238. return false;
  239. /* Ensure the start of the pageblock or zone is online and valid */
  240. block_pfn = pageblock_start_pfn(pfn);
  241. block_pfn = max(block_pfn, zone->zone_start_pfn);
  242. block_page = pfn_to_online_page(block_pfn);
  243. if (block_page) {
  244. page = block_page;
  245. pfn = block_pfn;
  246. }
  247. /* Ensure the end of the pageblock or zone is online and valid */
  248. block_pfn = pageblock_end_pfn(pfn) - 1;
  249. block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
  250. end_page = pfn_to_online_page(block_pfn);
  251. if (!end_page)
  252. return false;
  253. /*
  254. * Only clear the hint if a sample indicates there is either a
  255. * free page or an LRU page in the block. One or other condition
  256. * is necessary for the block to be a migration source/target.
  257. */
  258. do {
  259. if (pfn_valid_within(pfn)) {
  260. if (check_source && PageLRU(page)) {
  261. clear_pageblock_skip(page);
  262. return true;
  263. }
  264. if (check_target && PageBuddy(page)) {
  265. clear_pageblock_skip(page);
  266. return true;
  267. }
  268. }
  269. page += (1 << PAGE_ALLOC_COSTLY_ORDER);
  270. pfn += (1 << PAGE_ALLOC_COSTLY_ORDER);
  271. } while (page <= end_page);
  272. return false;
  273. }
  274. /*
  275. * This function is called to clear all cached information on pageblocks that
  276. * should be skipped for page isolation when the migrate and free page scanner
  277. * meet.
  278. */
  279. static void __reset_isolation_suitable(struct zone *zone)
  280. {
  281. unsigned long migrate_pfn = zone->zone_start_pfn;
  282. unsigned long free_pfn = zone_end_pfn(zone) - 1;
  283. unsigned long reset_migrate = free_pfn;
  284. unsigned long reset_free = migrate_pfn;
  285. bool source_set = false;
  286. bool free_set = false;
  287. if (!zone->compact_blockskip_flush)
  288. return;
  289. zone->compact_blockskip_flush = false;
  290. /*
  291. * Walk the zone and update pageblock skip information. Source looks
  292. * for PageLRU while target looks for PageBuddy. When the scanner
  293. * is found, both PageBuddy and PageLRU are checked as the pageblock
  294. * is suitable as both source and target.
  295. */
  296. for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
  297. free_pfn -= pageblock_nr_pages) {
  298. cond_resched();
  299. /* Update the migrate PFN */
  300. if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
  301. migrate_pfn < reset_migrate) {
  302. source_set = true;
  303. reset_migrate = migrate_pfn;
  304. zone->compact_init_migrate_pfn = reset_migrate;
  305. zone->compact_cached_migrate_pfn[0] = reset_migrate;
  306. zone->compact_cached_migrate_pfn[1] = reset_migrate;
  307. }
  308. /* Update the free PFN */
  309. if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
  310. free_pfn > reset_free) {
  311. free_set = true;
  312. reset_free = free_pfn;
  313. zone->compact_init_free_pfn = reset_free;
  314. zone->compact_cached_free_pfn = reset_free;
  315. }
  316. }
  317. /* Leave no distance if no suitable block was reset */
  318. if (reset_migrate >= reset_free) {
  319. zone->compact_cached_migrate_pfn[0] = migrate_pfn;
  320. zone->compact_cached_migrate_pfn[1] = migrate_pfn;
  321. zone->compact_cached_free_pfn = free_pfn;
  322. }
  323. }
  324. void reset_isolation_suitable(pg_data_t *pgdat)
  325. {
  326. int zoneid;
  327. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  328. struct zone *zone = &pgdat->node_zones[zoneid];
  329. if (!populated_zone(zone))
  330. continue;
  331. /* Only flush if a full compaction finished recently */
  332. if (zone->compact_blockskip_flush)
  333. __reset_isolation_suitable(zone);
  334. }
  335. }
  336. /*
  337. * Sets the pageblock skip bit if it was clear. Note that this is a hint as
  338. * locks are not required for read/writers. Returns true if it was already set.
  339. */
  340. static bool test_and_set_skip(struct compact_control *cc, struct page *page,
  341. unsigned long pfn)
  342. {
  343. bool skip;
  344. /* Do no update if skip hint is being ignored */
  345. if (cc->ignore_skip_hint)
  346. return false;
  347. if (!IS_ALIGNED(pfn, pageblock_nr_pages))
  348. return false;
  349. skip = get_pageblock_skip(page);
  350. if (!skip && !cc->no_set_skip_hint)
  351. set_pageblock_skip(page);
  352. return skip;
  353. }
  354. static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
  355. {
  356. struct zone *zone = cc->zone;
  357. pfn = pageblock_end_pfn(pfn);
  358. /* Set for isolation rather than compaction */
  359. if (cc->no_set_skip_hint)
  360. return;
  361. if (pfn > zone->compact_cached_migrate_pfn[0])
  362. zone->compact_cached_migrate_pfn[0] = pfn;
  363. if (cc->mode != MIGRATE_ASYNC &&
  364. pfn > zone->compact_cached_migrate_pfn[1])
  365. zone->compact_cached_migrate_pfn[1] = pfn;
  366. }
  367. /*
  368. * If no pages were isolated then mark this pageblock to be skipped in the
  369. * future. The information is later cleared by __reset_isolation_suitable().
  370. */
  371. static void update_pageblock_skip(struct compact_control *cc,
  372. struct page *page, unsigned long pfn)
  373. {
  374. struct zone *zone = cc->zone;
  375. if (cc->no_set_skip_hint)
  376. return;
  377. if (!page)
  378. return;
  379. set_pageblock_skip(page);
  380. /* Update where async and sync compaction should restart */
  381. if (pfn < zone->compact_cached_free_pfn)
  382. zone->compact_cached_free_pfn = pfn;
  383. }
  384. #else
  385. static inline bool isolation_suitable(struct compact_control *cc,
  386. struct page *page)
  387. {
  388. return true;
  389. }
  390. static inline bool pageblock_skip_persistent(struct page *page)
  391. {
  392. return false;
  393. }
  394. static inline void update_pageblock_skip(struct compact_control *cc,
  395. struct page *page, unsigned long pfn)
  396. {
  397. }
  398. static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
  399. {
  400. }
  401. static bool test_and_set_skip(struct compact_control *cc, struct page *page,
  402. unsigned long pfn)
  403. {
  404. return false;
  405. }
  406. #endif /* CONFIG_COMPACTION */
  407. /*
  408. * Compaction requires the taking of some coarse locks that are potentially
  409. * very heavily contended. For async compaction, trylock and record if the
  410. * lock is contended. The lock will still be acquired but compaction will
  411. * abort when the current block is finished regardless of success rate.
  412. * Sync compaction acquires the lock.
  413. *
  414. * Always returns true which makes it easier to track lock state in callers.
  415. */
  416. static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
  417. struct compact_control *cc)
  418. __acquires(lock)
  419. {
  420. /* Track if the lock is contended in async mode */
  421. if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
  422. if (spin_trylock_irqsave(lock, *flags))
  423. return true;
  424. cc->contended = true;
  425. }
  426. spin_lock_irqsave(lock, *flags);
  427. return true;
  428. }
  429. /*
  430. * Compaction requires the taking of some coarse locks that are potentially
  431. * very heavily contended. The lock should be periodically unlocked to avoid
  432. * having disabled IRQs for a long time, even when there is nobody waiting on
  433. * the lock. It might also be that allowing the IRQs will result in
  434. * need_resched() becoming true. If scheduling is needed, async compaction
  435. * aborts. Sync compaction schedules.
  436. * Either compaction type will also abort if a fatal signal is pending.
  437. * In either case if the lock was locked, it is dropped and not regained.
  438. *
  439. * Returns true if compaction should abort due to fatal signal pending, or
  440. * async compaction due to need_resched()
  441. * Returns false when compaction can continue (sync compaction might have
  442. * scheduled)
  443. */
  444. static bool compact_unlock_should_abort(spinlock_t *lock,
  445. unsigned long flags, bool *locked, struct compact_control *cc)
  446. {
  447. if (*locked) {
  448. spin_unlock_irqrestore(lock, flags);
  449. *locked = false;
  450. }
  451. if (fatal_signal_pending(current)) {
  452. cc->contended = true;
  453. return true;
  454. }
  455. cond_resched();
  456. return false;
  457. }
  458. /*
  459. * Isolate free pages onto a private freelist. If @strict is true, will abort
  460. * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
  461. * (even though it may still end up isolating some pages).
  462. */
  463. static unsigned long isolate_freepages_block(struct compact_control *cc,
  464. unsigned long *start_pfn,
  465. unsigned long end_pfn,
  466. struct list_head *freelist,
  467. unsigned int stride,
  468. bool strict)
  469. {
  470. int nr_scanned = 0, total_isolated = 0;
  471. struct page *cursor;
  472. unsigned long flags = 0;
  473. bool locked = false;
  474. unsigned long blockpfn = *start_pfn;
  475. unsigned int order;
  476. /* Strict mode is for isolation, speed is secondary */
  477. if (strict)
  478. stride = 1;
  479. cursor = pfn_to_page(blockpfn);
  480. /* Isolate free pages. */
  481. for (; blockpfn < end_pfn; blockpfn += stride, cursor += stride) {
  482. int isolated;
  483. struct page *page = cursor;
  484. /*
  485. * Periodically drop the lock (if held) regardless of its
  486. * contention, to give chance to IRQs. Abort if fatal signal
  487. * pending or async compaction detects need_resched()
  488. */
  489. if (!(blockpfn % SWAP_CLUSTER_MAX)
  490. && compact_unlock_should_abort(&cc->zone->lock, flags,
  491. &locked, cc))
  492. break;
  493. nr_scanned++;
  494. if (!pfn_valid_within(blockpfn))
  495. goto isolate_fail;
  496. /*
  497. * For compound pages such as THP and hugetlbfs, we can save
  498. * potentially a lot of iterations if we skip them at once.
  499. * The check is racy, but we can consider only valid values
  500. * and the only danger is skipping too much.
  501. */
  502. if (PageCompound(page)) {
  503. const unsigned int order = compound_order(page);
  504. if (likely(order < MAX_ORDER)) {
  505. blockpfn += (1UL << order) - 1;
  506. cursor += (1UL << order) - 1;
  507. }
  508. goto isolate_fail;
  509. }
  510. if (!PageBuddy(page))
  511. goto isolate_fail;
  512. /*
  513. * If we already hold the lock, we can skip some rechecking.
  514. * Note that if we hold the lock now, checked_pageblock was
  515. * already set in some previous iteration (or strict is true),
  516. * so it is correct to skip the suitable migration target
  517. * recheck as well.
  518. */
  519. if (!locked) {
  520. locked = compact_lock_irqsave(&cc->zone->lock,
  521. &flags, cc);
  522. /* Recheck this is a buddy page under lock */
  523. if (!PageBuddy(page))
  524. goto isolate_fail;
  525. }
  526. /* Found a free page, will break it into order-0 pages */
  527. order = buddy_order(page);
  528. isolated = __isolate_free_page(page, order);
  529. if (!isolated)
  530. break;
  531. set_page_private(page, order);
  532. total_isolated += isolated;
  533. cc->nr_freepages += isolated;
  534. list_add_tail(&page->lru, freelist);
  535. if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
  536. blockpfn += isolated;
  537. break;
  538. }
  539. /* Advance to the end of split page */
  540. blockpfn += isolated - 1;
  541. cursor += isolated - 1;
  542. continue;
  543. isolate_fail:
  544. if (strict)
  545. break;
  546. else
  547. continue;
  548. }
  549. if (locked)
  550. spin_unlock_irqrestore(&cc->zone->lock, flags);
  551. /*
  552. * There is a tiny chance that we have read bogus compound_order(),
  553. * so be careful to not go outside of the pageblock.
  554. */
  555. if (unlikely(blockpfn > end_pfn))
  556. blockpfn = end_pfn;
  557. trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
  558. nr_scanned, total_isolated);
  559. /* Record how far we have got within the block */
  560. *start_pfn = blockpfn;
  561. /*
  562. * If strict isolation is requested by CMA then check that all the
  563. * pages requested were isolated. If there were any failures, 0 is
  564. * returned and CMA will fail.
  565. */
  566. if (strict && blockpfn < end_pfn)
  567. total_isolated = 0;
  568. cc->total_free_scanned += nr_scanned;
  569. if (total_isolated)
  570. count_compact_events(COMPACTISOLATED, total_isolated);
  571. return total_isolated;
  572. }
  573. /**
  574. * isolate_freepages_range() - isolate free pages.
  575. * @cc: Compaction control structure.
  576. * @start_pfn: The first PFN to start isolating.
  577. * @end_pfn: The one-past-last PFN.
  578. *
  579. * Non-free pages, invalid PFNs, or zone boundaries within the
  580. * [start_pfn, end_pfn) range are considered errors, cause function to
  581. * undo its actions and return zero.
  582. *
  583. * Otherwise, function returns one-past-the-last PFN of isolated page
  584. * (which may be greater then end_pfn if end fell in a middle of
  585. * a free page).
  586. */
  587. unsigned long
  588. isolate_freepages_range(struct compact_control *cc,
  589. unsigned long start_pfn, unsigned long end_pfn)
  590. {
  591. unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
  592. LIST_HEAD(freelist);
  593. pfn = start_pfn;
  594. block_start_pfn = pageblock_start_pfn(pfn);
  595. if (block_start_pfn < cc->zone->zone_start_pfn)
  596. block_start_pfn = cc->zone->zone_start_pfn;
  597. block_end_pfn = pageblock_end_pfn(pfn);
  598. for (; pfn < end_pfn; pfn += isolated,
  599. block_start_pfn = block_end_pfn,
  600. block_end_pfn += pageblock_nr_pages) {
  601. /* Protect pfn from changing by isolate_freepages_block */
  602. unsigned long isolate_start_pfn = pfn;
  603. block_end_pfn = min(block_end_pfn, end_pfn);
  604. /*
  605. * pfn could pass the block_end_pfn if isolated freepage
  606. * is more than pageblock order. In this case, we adjust
  607. * scanning range to right one.
  608. */
  609. if (pfn >= block_end_pfn) {
  610. block_start_pfn = pageblock_start_pfn(pfn);
  611. block_end_pfn = pageblock_end_pfn(pfn);
  612. block_end_pfn = min(block_end_pfn, end_pfn);
  613. }
  614. if (!pageblock_pfn_to_page(block_start_pfn,
  615. block_end_pfn, cc->zone))
  616. break;
  617. isolated = isolate_freepages_block(cc, &isolate_start_pfn,
  618. block_end_pfn, &freelist, 0, true);
  619. /*
  620. * In strict mode, isolate_freepages_block() returns 0 if
  621. * there are any holes in the block (ie. invalid PFNs or
  622. * non-free pages).
  623. */
  624. if (!isolated)
  625. break;
  626. /*
  627. * If we managed to isolate pages, it is always (1 << n) *
  628. * pageblock_nr_pages for some non-negative n. (Max order
  629. * page may span two pageblocks).
  630. */
  631. }
  632. /* __isolate_free_page() does not map the pages */
  633. split_map_pages(&freelist);
  634. if (pfn < end_pfn) {
  635. /* Loop terminated early, cleanup. */
  636. release_freepages(&freelist);
  637. return 0;
  638. }
  639. /* We don't use freelists for anything. */
  640. return pfn;
  641. }
  642. #ifdef CONFIG_COMPACTION
  643. unsigned long isolate_and_split_free_page(struct page *page,
  644. struct list_head *list)
  645. {
  646. unsigned long isolated;
  647. unsigned int order;
  648. if (!PageBuddy(page))
  649. return 0;
  650. order = buddy_order(page);
  651. isolated = __isolate_free_page(page, order);
  652. if (!isolated)
  653. return 0;
  654. set_page_private(page, order);
  655. list_add(&page->lru, list);
  656. split_map_pages(list);
  657. return isolated;
  658. }
  659. EXPORT_SYMBOL_GPL(isolate_and_split_free_page);
  660. #endif
  661. /* Similar to reclaim, but different enough that they don't share logic */
  662. static bool too_many_isolated(pg_data_t *pgdat)
  663. {
  664. unsigned long active, inactive, isolated;
  665. inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
  666. node_page_state(pgdat, NR_INACTIVE_ANON);
  667. active = node_page_state(pgdat, NR_ACTIVE_FILE) +
  668. node_page_state(pgdat, NR_ACTIVE_ANON);
  669. isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
  670. node_page_state(pgdat, NR_ISOLATED_ANON);
  671. return isolated > (inactive + active) / 2;
  672. }
  673. /**
  674. * isolate_migratepages_block() - isolate all migrate-able pages within
  675. * a single pageblock
  676. * @cc: Compaction control structure.
  677. * @low_pfn: The first PFN to isolate
  678. * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
  679. * @isolate_mode: Isolation mode to be used.
  680. *
  681. * Isolate all pages that can be migrated from the range specified by
  682. * [low_pfn, end_pfn). The range is expected to be within same pageblock.
  683. * Returns zero if there is a fatal signal pending, otherwise PFN of the
  684. * first page that was not scanned (which may be both less, equal to or more
  685. * than end_pfn).
  686. *
  687. * The pages are isolated on cc->migratepages list (not required to be empty),
  688. * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
  689. * is neither read nor updated.
  690. */
  691. static unsigned long
  692. isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
  693. unsigned long end_pfn, isolate_mode_t isolate_mode)
  694. {
  695. pg_data_t *pgdat = cc->zone->zone_pgdat;
  696. unsigned long nr_scanned = 0, nr_isolated = 0;
  697. struct lruvec *lruvec;
  698. unsigned long flags = 0;
  699. bool locked = false;
  700. struct page *page = NULL, *valid_page = NULL;
  701. unsigned long start_pfn = low_pfn;
  702. bool skip_on_failure = false;
  703. unsigned long next_skip_pfn = 0;
  704. bool skip_updated = false;
  705. /*
  706. * Ensure that there are not too many pages isolated from the LRU
  707. * list by either parallel reclaimers or compaction. If there are,
  708. * delay for some time until fewer pages are isolated
  709. */
  710. while (unlikely(too_many_isolated(pgdat))) {
  711. /* stop isolation if there are still pages not migrated */
  712. if (cc->nr_migratepages)
  713. return 0;
  714. /* async migration should just abort */
  715. if (cc->mode == MIGRATE_ASYNC)
  716. return 0;
  717. congestion_wait(BLK_RW_ASYNC, HZ/10);
  718. if (fatal_signal_pending(current))
  719. return 0;
  720. }
  721. cond_resched();
  722. if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
  723. skip_on_failure = true;
  724. next_skip_pfn = block_end_pfn(low_pfn, cc->order);
  725. }
  726. /* Time to isolate some pages for migration */
  727. for (; low_pfn < end_pfn; low_pfn++) {
  728. if (skip_on_failure && low_pfn >= next_skip_pfn) {
  729. /*
  730. * We have isolated all migration candidates in the
  731. * previous order-aligned block, and did not skip it due
  732. * to failure. We should migrate the pages now and
  733. * hopefully succeed compaction.
  734. */
  735. if (nr_isolated)
  736. break;
  737. /*
  738. * We failed to isolate in the previous order-aligned
  739. * block. Set the new boundary to the end of the
  740. * current block. Note we can't simply increase
  741. * next_skip_pfn by 1 << order, as low_pfn might have
  742. * been incremented by a higher number due to skipping
  743. * a compound or a high-order buddy page in the
  744. * previous loop iteration.
  745. */
  746. next_skip_pfn = block_end_pfn(low_pfn, cc->order);
  747. }
  748. /*
  749. * Periodically drop the lock (if held) regardless of its
  750. * contention, to give chance to IRQs. Abort completely if
  751. * a fatal signal is pending.
  752. */
  753. if (!(low_pfn % SWAP_CLUSTER_MAX)
  754. && compact_unlock_should_abort(&pgdat->lru_lock,
  755. flags, &locked, cc)) {
  756. low_pfn = 0;
  757. goto fatal_pending;
  758. }
  759. if (!pfn_valid_within(low_pfn))
  760. goto isolate_fail;
  761. nr_scanned++;
  762. page = pfn_to_page(low_pfn);
  763. /*
  764. * Check if the pageblock has already been marked skipped.
  765. * Only the aligned PFN is checked as the caller isolates
  766. * COMPACT_CLUSTER_MAX at a time so the second call must
  767. * not falsely conclude that the block should be skipped.
  768. */
  769. if (!valid_page && IS_ALIGNED(low_pfn, pageblock_nr_pages)) {
  770. if (!cc->ignore_skip_hint && get_pageblock_skip(page)) {
  771. low_pfn = end_pfn;
  772. goto isolate_abort;
  773. }
  774. valid_page = page;
  775. }
  776. /*
  777. * Skip if free. We read page order here without zone lock
  778. * which is generally unsafe, but the race window is small and
  779. * the worst thing that can happen is that we skip some
  780. * potential isolation targets.
  781. */
  782. if (PageBuddy(page)) {
  783. unsigned long freepage_order = buddy_order_unsafe(page);
  784. /*
  785. * Without lock, we cannot be sure that what we got is
  786. * a valid page order. Consider only values in the
  787. * valid order range to prevent low_pfn overflow.
  788. */
  789. if (freepage_order > 0 && freepage_order < MAX_ORDER)
  790. low_pfn += (1UL << freepage_order) - 1;
  791. continue;
  792. }
  793. /*
  794. * Regardless of being on LRU, compound pages such as THP and
  795. * hugetlbfs are not to be compacted unless we are attempting
  796. * an allocation much larger than the huge page size (eg CMA).
  797. * We can potentially save a lot of iterations if we skip them
  798. * at once. The check is racy, but we can consider only valid
  799. * values and the only danger is skipping too much.
  800. */
  801. if (PageCompound(page) && !cc->alloc_contig) {
  802. const unsigned int order = compound_order(page);
  803. if (likely(order < MAX_ORDER))
  804. low_pfn += (1UL << order) - 1;
  805. goto isolate_fail;
  806. }
  807. /*
  808. * Check may be lockless but that's ok as we recheck later.
  809. * It's possible to migrate LRU and non-lru movable pages.
  810. * Skip any other type of page
  811. */
  812. if (!PageLRU(page)) {
  813. /*
  814. * __PageMovable can return false positive so we need
  815. * to verify it under page_lock.
  816. */
  817. if (unlikely(__PageMovable(page)) &&
  818. !PageIsolated(page)) {
  819. if (locked) {
  820. spin_unlock_irqrestore(&pgdat->lru_lock,
  821. flags);
  822. locked = false;
  823. }
  824. if (!isolate_movable_page(page, isolate_mode))
  825. goto isolate_success;
  826. }
  827. goto isolate_fail;
  828. }
  829. /*
  830. * Migration will fail if an anonymous page is pinned in memory,
  831. * so avoid taking lru_lock and isolating it unnecessarily in an
  832. * admittedly racy check.
  833. */
  834. if (!page_mapping(page) &&
  835. page_count(page) > page_mapcount(page))
  836. goto isolate_fail;
  837. /*
  838. * Only allow to migrate anonymous pages in GFP_NOFS context
  839. * because those do not depend on fs locks.
  840. */
  841. if (!(cc->gfp_mask & __GFP_FS) && page_mapping(page))
  842. goto isolate_fail;
  843. /* If we already hold the lock, we can skip some rechecking */
  844. if (!locked) {
  845. locked = compact_lock_irqsave(&pgdat->lru_lock,
  846. &flags, cc);
  847. /* Try get exclusive access under lock */
  848. if (!skip_updated) {
  849. skip_updated = true;
  850. if (test_and_set_skip(cc, page, low_pfn))
  851. goto isolate_abort;
  852. }
  853. /* Recheck PageLRU and PageCompound under lock */
  854. if (!PageLRU(page))
  855. goto isolate_fail;
  856. /*
  857. * Page become compound since the non-locked check,
  858. * and it's on LRU. It can only be a THP so the order
  859. * is safe to read and it's 0 for tail pages.
  860. */
  861. if (unlikely(PageCompound(page) && !cc->alloc_contig)) {
  862. low_pfn += compound_nr(page) - 1;
  863. goto isolate_fail;
  864. }
  865. }
  866. lruvec = mem_cgroup_page_lruvec(page, pgdat);
  867. /* Try isolate the page */
  868. if (__isolate_lru_page(page, isolate_mode) != 0)
  869. goto isolate_fail;
  870. /* The whole page is taken off the LRU; skip the tail pages. */
  871. if (PageCompound(page))
  872. low_pfn += compound_nr(page) - 1;
  873. /* Successfully isolated */
  874. del_page_from_lru_list(page, lruvec, page_lru(page));
  875. mod_node_page_state(page_pgdat(page),
  876. NR_ISOLATED_ANON + page_is_file_lru(page),
  877. thp_nr_pages(page));
  878. isolate_success:
  879. list_add(&page->lru, &cc->migratepages);
  880. cc->nr_migratepages += compound_nr(page);
  881. nr_isolated += compound_nr(page);
  882. /*
  883. * Avoid isolating too much unless this block is being
  884. * rescanned (e.g. dirty/writeback pages, parallel allocation)
  885. * or a lock is contended. For contention, isolate quickly to
  886. * potentially remove one source of contention.
  887. */
  888. if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX &&
  889. !cc->rescan && !cc->contended) {
  890. ++low_pfn;
  891. break;
  892. }
  893. continue;
  894. isolate_fail:
  895. if (!skip_on_failure)
  896. continue;
  897. /*
  898. * We have isolated some pages, but then failed. Release them
  899. * instead of migrating, as we cannot form the cc->order buddy
  900. * page anyway.
  901. */
  902. if (nr_isolated) {
  903. if (locked) {
  904. spin_unlock_irqrestore(&pgdat->lru_lock, flags);
  905. locked = false;
  906. }
  907. putback_movable_pages(&cc->migratepages);
  908. cc->nr_migratepages = 0;
  909. nr_isolated = 0;
  910. }
  911. if (low_pfn < next_skip_pfn) {
  912. low_pfn = next_skip_pfn - 1;
  913. /*
  914. * The check near the loop beginning would have updated
  915. * next_skip_pfn too, but this is a bit simpler.
  916. */
  917. next_skip_pfn += 1UL << cc->order;
  918. }
  919. }
  920. /*
  921. * The PageBuddy() check could have potentially brought us outside
  922. * the range to be scanned.
  923. */
  924. if (unlikely(low_pfn > end_pfn))
  925. low_pfn = end_pfn;
  926. isolate_abort:
  927. if (locked)
  928. spin_unlock_irqrestore(&pgdat->lru_lock, flags);
  929. /*
  930. * Updated the cached scanner pfn once the pageblock has been scanned
  931. * Pages will either be migrated in which case there is no point
  932. * scanning in the near future or migration failed in which case the
  933. * failure reason may persist. The block is marked for skipping if
  934. * there were no pages isolated in the block or if the block is
  935. * rescanned twice in a row.
  936. */
  937. if (low_pfn == end_pfn && (!nr_isolated || cc->rescan)) {
  938. if (valid_page && !skip_updated)
  939. set_pageblock_skip(valid_page);
  940. update_cached_migrate(cc, low_pfn);
  941. }
  942. trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
  943. nr_scanned, nr_isolated);
  944. fatal_pending:
  945. cc->total_migrate_scanned += nr_scanned;
  946. if (nr_isolated)
  947. count_compact_events(COMPACTISOLATED, nr_isolated);
  948. return low_pfn;
  949. }
  950. /**
  951. * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
  952. * @cc: Compaction control structure.
  953. * @start_pfn: The first PFN to start isolating.
  954. * @end_pfn: The one-past-last PFN.
  955. *
  956. * Returns zero if isolation fails fatally due to e.g. pending signal.
  957. * Otherwise, function returns one-past-the-last PFN of isolated page
  958. * (which may be greater than end_pfn if end fell in a middle of a THP page).
  959. */
  960. unsigned long
  961. isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
  962. unsigned long end_pfn)
  963. {
  964. unsigned long pfn, block_start_pfn, block_end_pfn;
  965. /* Scan block by block. First and last block may be incomplete */
  966. pfn = start_pfn;
  967. block_start_pfn = pageblock_start_pfn(pfn);
  968. if (block_start_pfn < cc->zone->zone_start_pfn)
  969. block_start_pfn = cc->zone->zone_start_pfn;
  970. block_end_pfn = pageblock_end_pfn(pfn);
  971. for (; pfn < end_pfn; pfn = block_end_pfn,
  972. block_start_pfn = block_end_pfn,
  973. block_end_pfn += pageblock_nr_pages) {
  974. block_end_pfn = min(block_end_pfn, end_pfn);
  975. if (!pageblock_pfn_to_page(block_start_pfn,
  976. block_end_pfn, cc->zone))
  977. continue;
  978. pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
  979. ISOLATE_UNEVICTABLE);
  980. if (!pfn)
  981. break;
  982. if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX)
  983. break;
  984. }
  985. return pfn;
  986. }
  987. #endif /* CONFIG_COMPACTION || CONFIG_CMA */
  988. #ifdef CONFIG_COMPACTION
  989. static bool suitable_migration_source(struct compact_control *cc,
  990. struct page *page)
  991. {
  992. int block_mt;
  993. if (pageblock_skip_persistent(page))
  994. return false;
  995. if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
  996. return true;
  997. block_mt = get_pageblock_migratetype(page);
  998. if (cc->migratetype == MIGRATE_MOVABLE)
  999. return is_migrate_movable(block_mt);
  1000. else
  1001. return block_mt == cc->migratetype;
  1002. }
  1003. /* Returns true if the page is within a block suitable for migration to */
  1004. static bool suitable_migration_target(struct compact_control *cc,
  1005. struct page *page)
  1006. {
  1007. /* If the page is a large free page, then disallow migration */
  1008. if (PageBuddy(page)) {
  1009. /*
  1010. * We are checking page_order without zone->lock taken. But
  1011. * the only small danger is that we skip a potentially suitable
  1012. * pageblock, so it's not worth to check order for valid range.
  1013. */
  1014. if (buddy_order_unsafe(page) >= pageblock_order)
  1015. return false;
  1016. }
  1017. if (cc->ignore_block_suitable)
  1018. return true;
  1019. /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
  1020. if (is_migrate_movable(get_pageblock_migratetype(page)))
  1021. return true;
  1022. /* Otherwise skip the block */
  1023. return false;
  1024. }
  1025. static inline unsigned int
  1026. freelist_scan_limit(struct compact_control *cc)
  1027. {
  1028. unsigned short shift = BITS_PER_LONG - 1;
  1029. return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
  1030. }
  1031. /*
  1032. * Test whether the free scanner has reached the same or lower pageblock than
  1033. * the migration scanner, and compaction should thus terminate.
  1034. */
  1035. static inline bool compact_scanners_met(struct compact_control *cc)
  1036. {
  1037. return (cc->free_pfn >> pageblock_order)
  1038. <= (cc->migrate_pfn >> pageblock_order);
  1039. }
  1040. /*
  1041. * Used when scanning for a suitable migration target which scans freelists
  1042. * in reverse. Reorders the list such as the unscanned pages are scanned
  1043. * first on the next iteration of the free scanner
  1044. */
  1045. static void
  1046. move_freelist_head(struct list_head *freelist, struct page *freepage)
  1047. {
  1048. LIST_HEAD(sublist);
  1049. if (!list_is_last(freelist, &freepage->lru)) {
  1050. list_cut_before(&sublist, freelist, &freepage->lru);
  1051. if (!list_empty(&sublist))
  1052. list_splice_tail(&sublist, freelist);
  1053. }
  1054. }
  1055. /*
  1056. * Similar to move_freelist_head except used by the migration scanner
  1057. * when scanning forward. It's possible for these list operations to
  1058. * move against each other if they search the free list exactly in
  1059. * lockstep.
  1060. */
  1061. static void
  1062. move_freelist_tail(struct list_head *freelist, struct page *freepage)
  1063. {
  1064. LIST_HEAD(sublist);
  1065. if (!list_is_first(freelist, &freepage->lru)) {
  1066. list_cut_position(&sublist, freelist, &freepage->lru);
  1067. if (!list_empty(&sublist))
  1068. list_splice_tail(&sublist, freelist);
  1069. }
  1070. }
  1071. static void
  1072. fast_isolate_around(struct compact_control *cc, unsigned long pfn, unsigned long nr_isolated)
  1073. {
  1074. unsigned long start_pfn, end_pfn;
  1075. struct page *page;
  1076. /* Do not search around if there are enough pages already */
  1077. if (cc->nr_freepages >= cc->nr_migratepages)
  1078. return;
  1079. /* Minimise scanning during async compaction */
  1080. if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
  1081. return;
  1082. /* Pageblock boundaries */
  1083. start_pfn = max(pageblock_start_pfn(pfn), cc->zone->zone_start_pfn);
  1084. end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone));
  1085. page = pageblock_pfn_to_page(start_pfn, end_pfn, cc->zone);
  1086. if (!page)
  1087. return;
  1088. /* Scan before */
  1089. if (start_pfn != pfn) {
  1090. isolate_freepages_block(cc, &start_pfn, pfn, &cc->freepages, 1, false);
  1091. if (cc->nr_freepages >= cc->nr_migratepages)
  1092. return;
  1093. }
  1094. /* Scan after */
  1095. start_pfn = pfn + nr_isolated;
  1096. if (start_pfn < end_pfn)
  1097. isolate_freepages_block(cc, &start_pfn, end_pfn, &cc->freepages, 1, false);
  1098. /* Skip this pageblock in the future as it's full or nearly full */
  1099. if (cc->nr_freepages < cc->nr_migratepages)
  1100. set_pageblock_skip(page);
  1101. }
  1102. /* Search orders in round-robin fashion */
  1103. static int next_search_order(struct compact_control *cc, int order)
  1104. {
  1105. order--;
  1106. if (order < 0)
  1107. order = cc->order - 1;
  1108. /* Search wrapped around? */
  1109. if (order == cc->search_order) {
  1110. cc->search_order--;
  1111. if (cc->search_order < 0)
  1112. cc->search_order = cc->order - 1;
  1113. return -1;
  1114. }
  1115. return order;
  1116. }
  1117. static unsigned long
  1118. fast_isolate_freepages(struct compact_control *cc)
  1119. {
  1120. unsigned int limit = min(1U, freelist_scan_limit(cc) >> 1);
  1121. unsigned int nr_scanned = 0;
  1122. unsigned long low_pfn, min_pfn, highest = 0;
  1123. unsigned long nr_isolated = 0;
  1124. unsigned long distance;
  1125. struct page *page = NULL;
  1126. bool scan_start = false;
  1127. int order;
  1128. /* Full compaction passes in a negative order */
  1129. if (cc->order <= 0)
  1130. return cc->free_pfn;
  1131. /*
  1132. * If starting the scan, use a deeper search and use the highest
  1133. * PFN found if a suitable one is not found.
  1134. */
  1135. if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
  1136. limit = pageblock_nr_pages >> 1;
  1137. scan_start = true;
  1138. }
  1139. /*
  1140. * Preferred point is in the top quarter of the scan space but take
  1141. * a pfn from the top half if the search is problematic.
  1142. */
  1143. distance = (cc->free_pfn - cc->migrate_pfn);
  1144. low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
  1145. min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
  1146. if (WARN_ON_ONCE(min_pfn > low_pfn))
  1147. low_pfn = min_pfn;
  1148. /*
  1149. * Search starts from the last successful isolation order or the next
  1150. * order to search after a previous failure
  1151. */
  1152. cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
  1153. for (order = cc->search_order;
  1154. !page && order >= 0;
  1155. order = next_search_order(cc, order)) {
  1156. struct free_area *area = &cc->zone->free_area[order];
  1157. struct list_head *freelist;
  1158. struct page *freepage;
  1159. unsigned long flags;
  1160. unsigned int order_scanned = 0;
  1161. unsigned long high_pfn = 0;
  1162. if (!area->nr_free)
  1163. continue;
  1164. spin_lock_irqsave(&cc->zone->lock, flags);
  1165. freelist = &area->free_list[MIGRATE_MOVABLE];
  1166. list_for_each_entry_reverse(freepage, freelist, lru) {
  1167. unsigned long pfn;
  1168. order_scanned++;
  1169. nr_scanned++;
  1170. pfn = page_to_pfn(freepage);
  1171. if (pfn >= highest)
  1172. highest = max(pageblock_start_pfn(pfn),
  1173. cc->zone->zone_start_pfn);
  1174. if (pfn >= low_pfn) {
  1175. cc->fast_search_fail = 0;
  1176. cc->search_order = order;
  1177. page = freepage;
  1178. break;
  1179. }
  1180. if (pfn >= min_pfn && pfn > high_pfn) {
  1181. high_pfn = pfn;
  1182. /* Shorten the scan if a candidate is found */
  1183. limit >>= 1;
  1184. }
  1185. if (order_scanned >= limit)
  1186. break;
  1187. }
  1188. /* Use a minimum pfn if a preferred one was not found */
  1189. if (!page && high_pfn) {
  1190. page = pfn_to_page(high_pfn);
  1191. /* Update freepage for the list reorder below */
  1192. freepage = page;
  1193. }
  1194. /* Reorder to so a future search skips recent pages */
  1195. move_freelist_head(freelist, freepage);
  1196. /* Isolate the page if available */
  1197. if (page) {
  1198. if (__isolate_free_page(page, order)) {
  1199. set_page_private(page, order);
  1200. nr_isolated = 1 << order;
  1201. cc->nr_freepages += nr_isolated;
  1202. list_add_tail(&page->lru, &cc->freepages);
  1203. count_compact_events(COMPACTISOLATED, nr_isolated);
  1204. } else {
  1205. /* If isolation fails, abort the search */
  1206. order = cc->search_order + 1;
  1207. page = NULL;
  1208. }
  1209. }
  1210. spin_unlock_irqrestore(&cc->zone->lock, flags);
  1211. /*
  1212. * Smaller scan on next order so the total scan ig related
  1213. * to freelist_scan_limit.
  1214. */
  1215. if (order_scanned >= limit)
  1216. limit = min(1U, limit >> 1);
  1217. }
  1218. if (!page) {
  1219. cc->fast_search_fail++;
  1220. if (scan_start) {
  1221. /*
  1222. * Use the highest PFN found above min. If one was
  1223. * not found, be pessimistic for direct compaction
  1224. * and use the min mark.
  1225. */
  1226. if (highest) {
  1227. page = pfn_to_page(highest);
  1228. cc->free_pfn = highest;
  1229. } else {
  1230. if (cc->direct_compaction && pfn_valid(min_pfn)) {
  1231. page = pageblock_pfn_to_page(min_pfn,
  1232. min(pageblock_end_pfn(min_pfn),
  1233. zone_end_pfn(cc->zone)),
  1234. cc->zone);
  1235. cc->free_pfn = min_pfn;
  1236. }
  1237. }
  1238. }
  1239. }
  1240. if (highest && highest >= cc->zone->compact_cached_free_pfn) {
  1241. highest -= pageblock_nr_pages;
  1242. cc->zone->compact_cached_free_pfn = highest;
  1243. }
  1244. cc->total_free_scanned += nr_scanned;
  1245. if (!page)
  1246. return cc->free_pfn;
  1247. low_pfn = page_to_pfn(page);
  1248. fast_isolate_around(cc, low_pfn, nr_isolated);
  1249. return low_pfn;
  1250. }
  1251. /*
  1252. * Based on information in the current compact_control, find blocks
  1253. * suitable for isolating free pages from and then isolate them.
  1254. */
  1255. static void isolate_freepages(struct compact_control *cc)
  1256. {
  1257. struct zone *zone = cc->zone;
  1258. struct page *page;
  1259. unsigned long block_start_pfn; /* start of current pageblock */
  1260. unsigned long isolate_start_pfn; /* exact pfn we start at */
  1261. unsigned long block_end_pfn; /* end of current pageblock */
  1262. unsigned long low_pfn; /* lowest pfn scanner is able to scan */
  1263. struct list_head *freelist = &cc->freepages;
  1264. unsigned int stride;
  1265. /* Try a small search of the free lists for a candidate */
  1266. isolate_start_pfn = fast_isolate_freepages(cc);
  1267. if (cc->nr_freepages)
  1268. goto splitmap;
  1269. /*
  1270. * Initialise the free scanner. The starting point is where we last
  1271. * successfully isolated from, zone-cached value, or the end of the
  1272. * zone when isolating for the first time. For looping we also need
  1273. * this pfn aligned down to the pageblock boundary, because we do
  1274. * block_start_pfn -= pageblock_nr_pages in the for loop.
  1275. * For ending point, take care when isolating in last pageblock of a
  1276. * zone which ends in the middle of a pageblock.
  1277. * The low boundary is the end of the pageblock the migration scanner
  1278. * is using.
  1279. */
  1280. isolate_start_pfn = cc->free_pfn;
  1281. block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
  1282. block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
  1283. zone_end_pfn(zone));
  1284. low_pfn = pageblock_end_pfn(cc->migrate_pfn);
  1285. stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
  1286. /*
  1287. * Isolate free pages until enough are available to migrate the
  1288. * pages on cc->migratepages. We stop searching if the migrate
  1289. * and free page scanners meet or enough free pages are isolated.
  1290. */
  1291. for (; block_start_pfn >= low_pfn;
  1292. block_end_pfn = block_start_pfn,
  1293. block_start_pfn -= pageblock_nr_pages,
  1294. isolate_start_pfn = block_start_pfn) {
  1295. unsigned long nr_isolated;
  1296. /*
  1297. * This can iterate a massively long zone without finding any
  1298. * suitable migration targets, so periodically check resched.
  1299. */
  1300. if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages)))
  1301. cond_resched();
  1302. page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
  1303. zone);
  1304. if (!page)
  1305. continue;
  1306. /* Check the block is suitable for migration */
  1307. if (!suitable_migration_target(cc, page))
  1308. continue;
  1309. /* If isolation recently failed, do not retry */
  1310. if (!isolation_suitable(cc, page))
  1311. continue;
  1312. /* Found a block suitable for isolating free pages from. */
  1313. nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
  1314. block_end_pfn, freelist, stride, false);
  1315. /* Update the skip hint if the full pageblock was scanned */
  1316. if (isolate_start_pfn == block_end_pfn)
  1317. update_pageblock_skip(cc, page, block_start_pfn);
  1318. /* Are enough freepages isolated? */
  1319. if (cc->nr_freepages >= cc->nr_migratepages) {
  1320. if (isolate_start_pfn >= block_end_pfn) {
  1321. /*
  1322. * Restart at previous pageblock if more
  1323. * freepages can be isolated next time.
  1324. */
  1325. isolate_start_pfn =
  1326. block_start_pfn - pageblock_nr_pages;
  1327. }
  1328. break;
  1329. } else if (isolate_start_pfn < block_end_pfn) {
  1330. /*
  1331. * If isolation failed early, do not continue
  1332. * needlessly.
  1333. */
  1334. break;
  1335. }
  1336. /* Adjust stride depending on isolation */
  1337. if (nr_isolated) {
  1338. stride = 1;
  1339. continue;
  1340. }
  1341. stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
  1342. }
  1343. /*
  1344. * Record where the free scanner will restart next time. Either we
  1345. * broke from the loop and set isolate_start_pfn based on the last
  1346. * call to isolate_freepages_block(), or we met the migration scanner
  1347. * and the loop terminated due to isolate_start_pfn < low_pfn
  1348. */
  1349. cc->free_pfn = isolate_start_pfn;
  1350. splitmap:
  1351. /* __isolate_free_page() does not map the pages */
  1352. split_map_pages(freelist);
  1353. }
  1354. /*
  1355. * This is a migrate-callback that "allocates" freepages by taking pages
  1356. * from the isolated freelists in the block we are migrating to.
  1357. */
  1358. static struct page *compaction_alloc(struct page *migratepage,
  1359. unsigned long data)
  1360. {
  1361. struct compact_control *cc = (struct compact_control *)data;
  1362. struct page *freepage;
  1363. if (list_empty(&cc->freepages)) {
  1364. isolate_freepages(cc);
  1365. if (list_empty(&cc->freepages))
  1366. return NULL;
  1367. }
  1368. freepage = list_entry(cc->freepages.next, struct page, lru);
  1369. list_del(&freepage->lru);
  1370. cc->nr_freepages--;
  1371. return freepage;
  1372. }
  1373. /*
  1374. * This is a migrate-callback that "frees" freepages back to the isolated
  1375. * freelist. All pages on the freelist are from the same zone, so there is no
  1376. * special handling needed for NUMA.
  1377. */
  1378. static void compaction_free(struct page *page, unsigned long data)
  1379. {
  1380. struct compact_control *cc = (struct compact_control *)data;
  1381. list_add(&page->lru, &cc->freepages);
  1382. cc->nr_freepages++;
  1383. }
  1384. /* possible outcome of isolate_migratepages */
  1385. typedef enum {
  1386. ISOLATE_ABORT, /* Abort compaction now */
  1387. ISOLATE_NONE, /* No pages isolated, continue scanning */
  1388. ISOLATE_SUCCESS, /* Pages isolated, migrate */
  1389. } isolate_migrate_t;
  1390. /*
  1391. * Allow userspace to control policy on scanning the unevictable LRU for
  1392. * compactable pages.
  1393. */
  1394. #ifdef CONFIG_PREEMPT_RT
  1395. int sysctl_compact_unevictable_allowed __read_mostly = 0;
  1396. #else
  1397. int sysctl_compact_unevictable_allowed __read_mostly = 1;
  1398. #endif
  1399. static inline void
  1400. update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
  1401. {
  1402. if (cc->fast_start_pfn == ULONG_MAX)
  1403. return;
  1404. if (!cc->fast_start_pfn)
  1405. cc->fast_start_pfn = pfn;
  1406. cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
  1407. }
  1408. static inline unsigned long
  1409. reinit_migrate_pfn(struct compact_control *cc)
  1410. {
  1411. if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
  1412. return cc->migrate_pfn;
  1413. cc->migrate_pfn = cc->fast_start_pfn;
  1414. cc->fast_start_pfn = ULONG_MAX;
  1415. return cc->migrate_pfn;
  1416. }
  1417. /*
  1418. * Briefly search the free lists for a migration source that already has
  1419. * some free pages to reduce the number of pages that need migration
  1420. * before a pageblock is free.
  1421. */
  1422. static unsigned long fast_find_migrateblock(struct compact_control *cc)
  1423. {
  1424. unsigned int limit = freelist_scan_limit(cc);
  1425. unsigned int nr_scanned = 0;
  1426. unsigned long distance;
  1427. unsigned long pfn = cc->migrate_pfn;
  1428. unsigned long high_pfn;
  1429. int order;
  1430. bool found_block = false;
  1431. /* Skip hints are relied on to avoid repeats on the fast search */
  1432. if (cc->ignore_skip_hint)
  1433. return pfn;
  1434. /*
  1435. * If the migrate_pfn is not at the start of a zone or the start
  1436. * of a pageblock then assume this is a continuation of a previous
  1437. * scan restarted due to COMPACT_CLUSTER_MAX.
  1438. */
  1439. if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
  1440. return pfn;
  1441. /*
  1442. * For smaller orders, just linearly scan as the number of pages
  1443. * to migrate should be relatively small and does not necessarily
  1444. * justify freeing up a large block for a small allocation.
  1445. */
  1446. if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
  1447. return pfn;
  1448. /*
  1449. * Only allow kcompactd and direct requests for movable pages to
  1450. * quickly clear out a MOVABLE pageblock for allocation. This
  1451. * reduces the risk that a large movable pageblock is freed for
  1452. * an unmovable/reclaimable small allocation.
  1453. */
  1454. if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
  1455. return pfn;
  1456. /*
  1457. * When starting the migration scanner, pick any pageblock within the
  1458. * first half of the search space. Otherwise try and pick a pageblock
  1459. * within the first eighth to reduce the chances that a migration
  1460. * target later becomes a source.
  1461. */
  1462. distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
  1463. if (cc->migrate_pfn != cc->zone->zone_start_pfn)
  1464. distance >>= 2;
  1465. high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
  1466. for (order = cc->order - 1;
  1467. order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit;
  1468. order--) {
  1469. struct free_area *area = &cc->zone->free_area[order];
  1470. struct list_head *freelist;
  1471. unsigned long flags;
  1472. struct page *freepage;
  1473. if (!area->nr_free)
  1474. continue;
  1475. spin_lock_irqsave(&cc->zone->lock, flags);
  1476. freelist = &area->free_list[MIGRATE_MOVABLE];
  1477. list_for_each_entry(freepage, freelist, lru) {
  1478. unsigned long free_pfn;
  1479. if (nr_scanned++ >= limit) {
  1480. move_freelist_tail(freelist, freepage);
  1481. break;
  1482. }
  1483. free_pfn = page_to_pfn(freepage);
  1484. if (free_pfn < high_pfn) {
  1485. /*
  1486. * Avoid if skipped recently. Ideally it would
  1487. * move to the tail but even safe iteration of
  1488. * the list assumes an entry is deleted, not
  1489. * reordered.
  1490. */
  1491. if (get_pageblock_skip(freepage))
  1492. continue;
  1493. /* Reorder to so a future search skips recent pages */
  1494. move_freelist_tail(freelist, freepage);
  1495. update_fast_start_pfn(cc, free_pfn);
  1496. pfn = pageblock_start_pfn(free_pfn);
  1497. cc->fast_search_fail = 0;
  1498. found_block = true;
  1499. set_pageblock_skip(freepage);
  1500. break;
  1501. }
  1502. }
  1503. spin_unlock_irqrestore(&cc->zone->lock, flags);
  1504. }
  1505. cc->total_migrate_scanned += nr_scanned;
  1506. /*
  1507. * If fast scanning failed then use a cached entry for a page block
  1508. * that had free pages as the basis for starting a linear scan.
  1509. */
  1510. if (!found_block) {
  1511. cc->fast_search_fail++;
  1512. pfn = reinit_migrate_pfn(cc);
  1513. }
  1514. return pfn;
  1515. }
  1516. /*
  1517. * Isolate all pages that can be migrated from the first suitable block,
  1518. * starting at the block pointed to by the migrate scanner pfn within
  1519. * compact_control.
  1520. */
  1521. static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
  1522. {
  1523. unsigned long block_start_pfn;
  1524. unsigned long block_end_pfn;
  1525. unsigned long low_pfn;
  1526. struct page *page;
  1527. const isolate_mode_t isolate_mode =
  1528. (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
  1529. (cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
  1530. bool fast_find_block;
  1531. /*
  1532. * Start at where we last stopped, or beginning of the zone as
  1533. * initialized by compact_zone(). The first failure will use
  1534. * the lowest PFN as the starting point for linear scanning.
  1535. */
  1536. low_pfn = fast_find_migrateblock(cc);
  1537. block_start_pfn = pageblock_start_pfn(low_pfn);
  1538. if (block_start_pfn < cc->zone->zone_start_pfn)
  1539. block_start_pfn = cc->zone->zone_start_pfn;
  1540. /*
  1541. * fast_find_migrateblock marks a pageblock skipped so to avoid
  1542. * the isolation_suitable check below, check whether the fast
  1543. * search was successful.
  1544. */
  1545. fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
  1546. /* Only scan within a pageblock boundary */
  1547. block_end_pfn = pageblock_end_pfn(low_pfn);
  1548. /*
  1549. * Iterate over whole pageblocks until we find the first suitable.
  1550. * Do not cross the free scanner.
  1551. */
  1552. for (; block_end_pfn <= cc->free_pfn;
  1553. fast_find_block = false,
  1554. low_pfn = block_end_pfn,
  1555. block_start_pfn = block_end_pfn,
  1556. block_end_pfn += pageblock_nr_pages) {
  1557. /*
  1558. * This can potentially iterate a massively long zone with
  1559. * many pageblocks unsuitable, so periodically check if we
  1560. * need to schedule.
  1561. */
  1562. if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages)))
  1563. cond_resched();
  1564. page = pageblock_pfn_to_page(block_start_pfn,
  1565. block_end_pfn, cc->zone);
  1566. if (!page)
  1567. continue;
  1568. /*
  1569. * If isolation recently failed, do not retry. Only check the
  1570. * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
  1571. * to be visited multiple times. Assume skip was checked
  1572. * before making it "skip" so other compaction instances do
  1573. * not scan the same block.
  1574. */
  1575. if (IS_ALIGNED(low_pfn, pageblock_nr_pages) &&
  1576. !fast_find_block && !isolation_suitable(cc, page))
  1577. continue;
  1578. /*
  1579. * For async compaction, also only scan in MOVABLE blocks
  1580. * without huge pages. Async compaction is optimistic to see
  1581. * if the minimum amount of work satisfies the allocation.
  1582. * The cached PFN is updated as it's possible that all
  1583. * remaining blocks between source and target are unsuitable
  1584. * and the compaction scanners fail to meet.
  1585. */
  1586. if (!suitable_migration_source(cc, page)) {
  1587. update_cached_migrate(cc, block_end_pfn);
  1588. continue;
  1589. }
  1590. /* Perform the isolation */
  1591. low_pfn = isolate_migratepages_block(cc, low_pfn,
  1592. block_end_pfn, isolate_mode);
  1593. if (!low_pfn)
  1594. return ISOLATE_ABORT;
  1595. /*
  1596. * Either we isolated something and proceed with migration. Or
  1597. * we failed and compact_zone should decide if we should
  1598. * continue or not.
  1599. */
  1600. break;
  1601. }
  1602. /* Record where migration scanner will be restarted. */
  1603. cc->migrate_pfn = low_pfn;
  1604. return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
  1605. }
  1606. /*
  1607. * order == -1 is expected when compacting via
  1608. * /proc/sys/vm/compact_memory
  1609. */
  1610. static inline bool is_via_compact_memory(int order)
  1611. {
  1612. return order == -1;
  1613. }
  1614. static bool kswapd_is_running(pg_data_t *pgdat)
  1615. {
  1616. return pgdat->kswapd && (pgdat->kswapd->state == TASK_RUNNING);
  1617. }
  1618. /*
  1619. * A zone's fragmentation score is the external fragmentation wrt to the
  1620. * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100].
  1621. */
  1622. static unsigned int fragmentation_score_zone(struct zone *zone)
  1623. {
  1624. return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
  1625. }
  1626. /*
  1627. * A weighted zone's fragmentation score is the external fragmentation
  1628. * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It
  1629. * returns a value in the range [0, 100].
  1630. *
  1631. * The scaling factor ensures that proactive compaction focuses on larger
  1632. * zones like ZONE_NORMAL, rather than smaller, specialized zones like
  1633. * ZONE_DMA32. For smaller zones, the score value remains close to zero,
  1634. * and thus never exceeds the high threshold for proactive compaction.
  1635. */
  1636. static unsigned int fragmentation_score_zone_weighted(struct zone *zone)
  1637. {
  1638. unsigned long score;
  1639. score = zone->present_pages * fragmentation_score_zone(zone);
  1640. return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
  1641. }
  1642. /*
  1643. * The per-node proactive (background) compaction process is started by its
  1644. * corresponding kcompactd thread when the node's fragmentation score
  1645. * exceeds the high threshold. The compaction process remains active till
  1646. * the node's score falls below the low threshold, or one of the back-off
  1647. * conditions is met.
  1648. */
  1649. static unsigned int fragmentation_score_node(pg_data_t *pgdat)
  1650. {
  1651. unsigned int score = 0;
  1652. int zoneid;
  1653. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  1654. struct zone *zone;
  1655. zone = &pgdat->node_zones[zoneid];
  1656. score += fragmentation_score_zone_weighted(zone);
  1657. }
  1658. return score;
  1659. }
  1660. static unsigned int fragmentation_score_wmark(pg_data_t *pgdat, bool low)
  1661. {
  1662. unsigned int wmark_low;
  1663. /*
  1664. * Cap the low watermak to avoid excessive compaction
  1665. * activity in case a user sets the proactivess tunable
  1666. * close to 100 (maximum).
  1667. */
  1668. wmark_low = max(100U - sysctl_compaction_proactiveness, 5U);
  1669. return low ? wmark_low : min(wmark_low + 10, 100U);
  1670. }
  1671. static bool should_proactive_compact_node(pg_data_t *pgdat)
  1672. {
  1673. int wmark_high;
  1674. if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
  1675. return false;
  1676. wmark_high = fragmentation_score_wmark(pgdat, false);
  1677. return fragmentation_score_node(pgdat) > wmark_high;
  1678. }
  1679. static enum compact_result __compact_finished(struct compact_control *cc)
  1680. {
  1681. unsigned int order;
  1682. const int migratetype = cc->migratetype;
  1683. int ret;
  1684. /* Compaction run completes if the migrate and free scanner meet */
  1685. if (compact_scanners_met(cc)) {
  1686. /* Let the next compaction start anew. */
  1687. reset_cached_positions(cc->zone);
  1688. /*
  1689. * Mark that the PG_migrate_skip information should be cleared
  1690. * by kswapd when it goes to sleep. kcompactd does not set the
  1691. * flag itself as the decision to be clear should be directly
  1692. * based on an allocation request.
  1693. */
  1694. if (cc->direct_compaction)
  1695. cc->zone->compact_blockskip_flush = true;
  1696. if (cc->whole_zone)
  1697. return COMPACT_COMPLETE;
  1698. else
  1699. return COMPACT_PARTIAL_SKIPPED;
  1700. }
  1701. if (cc->proactive_compaction) {
  1702. int score, wmark_low;
  1703. pg_data_t *pgdat;
  1704. pgdat = cc->zone->zone_pgdat;
  1705. if (kswapd_is_running(pgdat))
  1706. return COMPACT_PARTIAL_SKIPPED;
  1707. score = fragmentation_score_zone(cc->zone);
  1708. wmark_low = fragmentation_score_wmark(pgdat, true);
  1709. if (score > wmark_low)
  1710. ret = COMPACT_CONTINUE;
  1711. else
  1712. ret = COMPACT_SUCCESS;
  1713. goto out;
  1714. }
  1715. if (is_via_compact_memory(cc->order))
  1716. return COMPACT_CONTINUE;
  1717. /*
  1718. * Always finish scanning a pageblock to reduce the possibility of
  1719. * fallbacks in the future. This is particularly important when
  1720. * migration source is unmovable/reclaimable but it's not worth
  1721. * special casing.
  1722. */
  1723. if (!IS_ALIGNED(cc->migrate_pfn, pageblock_nr_pages))
  1724. return COMPACT_CONTINUE;
  1725. /* Direct compactor: Is a suitable page free? */
  1726. ret = COMPACT_NO_SUITABLE_PAGE;
  1727. for (order = cc->order; order < MAX_ORDER; order++) {
  1728. struct free_area *area = &cc->zone->free_area[order];
  1729. bool can_steal;
  1730. /* Job done if page is free of the right migratetype */
  1731. if (!free_area_empty(area, migratetype))
  1732. return COMPACT_SUCCESS;
  1733. #ifdef CONFIG_CMA
  1734. /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
  1735. if (migratetype == MIGRATE_MOVABLE &&
  1736. !free_area_empty(area, MIGRATE_CMA))
  1737. return COMPACT_SUCCESS;
  1738. #endif
  1739. /*
  1740. * Job done if allocation would steal freepages from
  1741. * other migratetype buddy lists.
  1742. */
  1743. if (find_suitable_fallback(area, order, migratetype,
  1744. true, &can_steal) != -1) {
  1745. /* movable pages are OK in any pageblock */
  1746. if (migratetype == MIGRATE_MOVABLE)
  1747. return COMPACT_SUCCESS;
  1748. /*
  1749. * We are stealing for a non-movable allocation. Make
  1750. * sure we finish compacting the current pageblock
  1751. * first so it is as free as possible and we won't
  1752. * have to steal another one soon. This only applies
  1753. * to sync compaction, as async compaction operates
  1754. * on pageblocks of the same migratetype.
  1755. */
  1756. if (cc->mode == MIGRATE_ASYNC ||
  1757. IS_ALIGNED(cc->migrate_pfn,
  1758. pageblock_nr_pages)) {
  1759. return COMPACT_SUCCESS;
  1760. }
  1761. ret = COMPACT_CONTINUE;
  1762. break;
  1763. }
  1764. }
  1765. out:
  1766. if (cc->contended || fatal_signal_pending(current))
  1767. ret = COMPACT_CONTENDED;
  1768. return ret;
  1769. }
  1770. static enum compact_result compact_finished(struct compact_control *cc)
  1771. {
  1772. int ret;
  1773. ret = __compact_finished(cc);
  1774. trace_mm_compaction_finished(cc->zone, cc->order, ret);
  1775. if (ret == COMPACT_NO_SUITABLE_PAGE)
  1776. ret = COMPACT_CONTINUE;
  1777. return ret;
  1778. }
  1779. /*
  1780. * compaction_suitable: Is this suitable to run compaction on this zone now?
  1781. * Returns
  1782. * COMPACT_SKIPPED - If there are too few free pages for compaction
  1783. * COMPACT_SUCCESS - If the allocation would succeed without compaction
  1784. * COMPACT_CONTINUE - If compaction should run now
  1785. */
  1786. static enum compact_result __compaction_suitable(struct zone *zone, int order,
  1787. unsigned int alloc_flags,
  1788. int highest_zoneidx,
  1789. unsigned long wmark_target)
  1790. {
  1791. unsigned long watermark;
  1792. if (is_via_compact_memory(order))
  1793. return COMPACT_CONTINUE;
  1794. watermark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
  1795. /*
  1796. * If watermarks for high-order allocation are already met, there
  1797. * should be no need for compaction at all.
  1798. */
  1799. if (zone_watermark_ok(zone, order, watermark, highest_zoneidx,
  1800. alloc_flags))
  1801. return COMPACT_SUCCESS;
  1802. /*
  1803. * Watermarks for order-0 must be met for compaction to be able to
  1804. * isolate free pages for migration targets. This means that the
  1805. * watermark and alloc_flags have to match, or be more pessimistic than
  1806. * the check in __isolate_free_page(). We don't use the direct
  1807. * compactor's alloc_flags, as they are not relevant for freepage
  1808. * isolation. We however do use the direct compactor's highest_zoneidx
  1809. * to skip over zones where lowmem reserves would prevent allocation
  1810. * even if compaction succeeds.
  1811. * For costly orders, we require low watermark instead of min for
  1812. * compaction to proceed to increase its chances.
  1813. * ALLOC_CMA is used, as pages in CMA pageblocks are considered
  1814. * suitable migration targets
  1815. */
  1816. watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
  1817. low_wmark_pages(zone) : min_wmark_pages(zone);
  1818. watermark += compact_gap(order);
  1819. if (!__zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
  1820. ALLOC_CMA, wmark_target))
  1821. return COMPACT_SKIPPED;
  1822. return COMPACT_CONTINUE;
  1823. }
  1824. enum compact_result compaction_suitable(struct zone *zone, int order,
  1825. unsigned int alloc_flags,
  1826. int highest_zoneidx)
  1827. {
  1828. enum compact_result ret;
  1829. int fragindex;
  1830. ret = __compaction_suitable(zone, order, alloc_flags, highest_zoneidx,
  1831. zone_page_state(zone, NR_FREE_PAGES));
  1832. /*
  1833. * fragmentation index determines if allocation failures are due to
  1834. * low memory or external fragmentation
  1835. *
  1836. * index of -1000 would imply allocations might succeed depending on
  1837. * watermarks, but we already failed the high-order watermark check
  1838. * index towards 0 implies failure is due to lack of memory
  1839. * index towards 1000 implies failure is due to fragmentation
  1840. *
  1841. * Only compact if a failure would be due to fragmentation. Also
  1842. * ignore fragindex for non-costly orders where the alternative to
  1843. * a successful reclaim/compaction is OOM. Fragindex and the
  1844. * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
  1845. * excessive compaction for costly orders, but it should not be at the
  1846. * expense of system stability.
  1847. */
  1848. if (ret == COMPACT_CONTINUE && (order > PAGE_ALLOC_COSTLY_ORDER)) {
  1849. fragindex = fragmentation_index(zone, order);
  1850. if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
  1851. ret = COMPACT_NOT_SUITABLE_ZONE;
  1852. }
  1853. trace_mm_compaction_suitable(zone, order, ret);
  1854. if (ret == COMPACT_NOT_SUITABLE_ZONE)
  1855. ret = COMPACT_SKIPPED;
  1856. return ret;
  1857. }
  1858. bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
  1859. int alloc_flags)
  1860. {
  1861. struct zone *zone;
  1862. struct zoneref *z;
  1863. /*
  1864. * Make sure at least one zone would pass __compaction_suitable if we continue
  1865. * retrying the reclaim.
  1866. */
  1867. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  1868. ac->highest_zoneidx, ac->nodemask) {
  1869. unsigned long available;
  1870. enum compact_result compact_result;
  1871. /*
  1872. * Do not consider all the reclaimable memory because we do not
  1873. * want to trash just for a single high order allocation which
  1874. * is even not guaranteed to appear even if __compaction_suitable
  1875. * is happy about the watermark check.
  1876. */
  1877. available = zone_reclaimable_pages(zone) / order;
  1878. available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  1879. compact_result = __compaction_suitable(zone, order, alloc_flags,
  1880. ac->highest_zoneidx, available);
  1881. if (compact_result != COMPACT_SKIPPED)
  1882. return true;
  1883. }
  1884. return false;
  1885. }
  1886. static enum compact_result
  1887. compact_zone(struct compact_control *cc, struct capture_control *capc)
  1888. {
  1889. enum compact_result ret;
  1890. unsigned long start_pfn = cc->zone->zone_start_pfn;
  1891. unsigned long end_pfn = zone_end_pfn(cc->zone);
  1892. unsigned long last_migrated_pfn;
  1893. const bool sync = cc->mode != MIGRATE_ASYNC;
  1894. bool update_cached;
  1895. /*
  1896. * These counters track activities during zone compaction. Initialize
  1897. * them before compacting a new zone.
  1898. */
  1899. cc->total_migrate_scanned = 0;
  1900. cc->total_free_scanned = 0;
  1901. cc->nr_migratepages = 0;
  1902. cc->nr_freepages = 0;
  1903. INIT_LIST_HEAD(&cc->freepages);
  1904. INIT_LIST_HEAD(&cc->migratepages);
  1905. cc->migratetype = gfp_migratetype(cc->gfp_mask);
  1906. ret = compaction_suitable(cc->zone, cc->order, cc->alloc_flags,
  1907. cc->highest_zoneidx);
  1908. /* Compaction is likely to fail */
  1909. if (ret == COMPACT_SUCCESS || ret == COMPACT_SKIPPED)
  1910. return ret;
  1911. /* huh, compaction_suitable is returning something unexpected */
  1912. VM_BUG_ON(ret != COMPACT_CONTINUE);
  1913. /*
  1914. * Clear pageblock skip if there were failures recently and compaction
  1915. * is about to be retried after being deferred.
  1916. */
  1917. if (compaction_restarting(cc->zone, cc->order))
  1918. __reset_isolation_suitable(cc->zone);
  1919. /*
  1920. * Setup to move all movable pages to the end of the zone. Used cached
  1921. * information on where the scanners should start (unless we explicitly
  1922. * want to compact the whole zone), but check that it is initialised
  1923. * by ensuring the values are within zone boundaries.
  1924. */
  1925. cc->fast_start_pfn = 0;
  1926. if (cc->whole_zone) {
  1927. cc->migrate_pfn = start_pfn;
  1928. cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
  1929. } else {
  1930. cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
  1931. cc->free_pfn = cc->zone->compact_cached_free_pfn;
  1932. if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
  1933. cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
  1934. cc->zone->compact_cached_free_pfn = cc->free_pfn;
  1935. }
  1936. if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
  1937. cc->migrate_pfn = start_pfn;
  1938. cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
  1939. cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
  1940. }
  1941. if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
  1942. cc->whole_zone = true;
  1943. }
  1944. last_migrated_pfn = 0;
  1945. /*
  1946. * Migrate has separate cached PFNs for ASYNC and SYNC* migration on
  1947. * the basis that some migrations will fail in ASYNC mode. However,
  1948. * if the cached PFNs match and pageblocks are skipped due to having
  1949. * no isolation candidates, then the sync state does not matter.
  1950. * Until a pageblock with isolation candidates is found, keep the
  1951. * cached PFNs in sync to avoid revisiting the same blocks.
  1952. */
  1953. update_cached = !sync &&
  1954. cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
  1955. trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
  1956. cc->free_pfn, end_pfn, sync);
  1957. /* lru_add_drain_all could be expensive with involving other CPUs */
  1958. lru_add_drain();
  1959. while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
  1960. int err;
  1961. unsigned long start_pfn = cc->migrate_pfn;
  1962. /*
  1963. * Avoid multiple rescans which can happen if a page cannot be
  1964. * isolated (dirty/writeback in async mode) or if the migrated
  1965. * pages are being allocated before the pageblock is cleared.
  1966. * The first rescan will capture the entire pageblock for
  1967. * migration. If it fails, it'll be marked skip and scanning
  1968. * will proceed as normal.
  1969. */
  1970. cc->rescan = false;
  1971. if (pageblock_start_pfn(last_migrated_pfn) ==
  1972. pageblock_start_pfn(start_pfn)) {
  1973. cc->rescan = true;
  1974. }
  1975. switch (isolate_migratepages(cc)) {
  1976. case ISOLATE_ABORT:
  1977. ret = COMPACT_CONTENDED;
  1978. putback_movable_pages(&cc->migratepages);
  1979. cc->nr_migratepages = 0;
  1980. goto out;
  1981. case ISOLATE_NONE:
  1982. if (update_cached) {
  1983. cc->zone->compact_cached_migrate_pfn[1] =
  1984. cc->zone->compact_cached_migrate_pfn[0];
  1985. }
  1986. /*
  1987. * We haven't isolated and migrated anything, but
  1988. * there might still be unflushed migrations from
  1989. * previous cc->order aligned block.
  1990. */
  1991. goto check_drain;
  1992. case ISOLATE_SUCCESS:
  1993. update_cached = false;
  1994. last_migrated_pfn = start_pfn;
  1995. ;
  1996. }
  1997. err = migrate_pages(&cc->migratepages, compaction_alloc,
  1998. compaction_free, (unsigned long)cc, cc->mode,
  1999. MR_COMPACTION);
  2000. trace_mm_compaction_migratepages(cc->nr_migratepages, err,
  2001. &cc->migratepages);
  2002. /* All pages were either migrated or will be released */
  2003. cc->nr_migratepages = 0;
  2004. if (err) {
  2005. putback_movable_pages(&cc->migratepages);
  2006. /*
  2007. * migrate_pages() may return -ENOMEM when scanners meet
  2008. * and we want compact_finished() to detect it
  2009. */
  2010. if (err == -ENOMEM && !compact_scanners_met(cc)) {
  2011. ret = COMPACT_CONTENDED;
  2012. goto out;
  2013. }
  2014. /*
  2015. * We failed to migrate at least one page in the current
  2016. * order-aligned block, so skip the rest of it.
  2017. */
  2018. if (cc->direct_compaction &&
  2019. (cc->mode == MIGRATE_ASYNC)) {
  2020. cc->migrate_pfn = block_end_pfn(
  2021. cc->migrate_pfn - 1, cc->order);
  2022. /* Draining pcplists is useless in this case */
  2023. last_migrated_pfn = 0;
  2024. }
  2025. }
  2026. check_drain:
  2027. /*
  2028. * Has the migration scanner moved away from the previous
  2029. * cc->order aligned block where we migrated from? If yes,
  2030. * flush the pages that were freed, so that they can merge and
  2031. * compact_finished() can detect immediately if allocation
  2032. * would succeed.
  2033. */
  2034. if (cc->order > 0 && last_migrated_pfn) {
  2035. unsigned long current_block_start =
  2036. block_start_pfn(cc->migrate_pfn, cc->order);
  2037. if (last_migrated_pfn < current_block_start) {
  2038. lru_add_drain_cpu_zone(cc->zone);
  2039. /* No more flushing until we migrate again */
  2040. last_migrated_pfn = 0;
  2041. }
  2042. }
  2043. /* Stop if a page has been captured */
  2044. if (capc && capc->page) {
  2045. ret = COMPACT_SUCCESS;
  2046. break;
  2047. }
  2048. }
  2049. out:
  2050. /*
  2051. * Release free pages and update where the free scanner should restart,
  2052. * so we don't leave any returned pages behind in the next attempt.
  2053. */
  2054. if (cc->nr_freepages > 0) {
  2055. unsigned long free_pfn = release_freepages(&cc->freepages);
  2056. cc->nr_freepages = 0;
  2057. VM_BUG_ON(free_pfn == 0);
  2058. /* The cached pfn is always the first in a pageblock */
  2059. free_pfn = pageblock_start_pfn(free_pfn);
  2060. /*
  2061. * Only go back, not forward. The cached pfn might have been
  2062. * already reset to zone end in compact_finished()
  2063. */
  2064. if (free_pfn > cc->zone->compact_cached_free_pfn)
  2065. cc->zone->compact_cached_free_pfn = free_pfn;
  2066. }
  2067. count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
  2068. count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
  2069. trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
  2070. cc->free_pfn, end_pfn, sync, ret);
  2071. return ret;
  2072. }
  2073. static enum compact_result compact_zone_order(struct zone *zone, int order,
  2074. gfp_t gfp_mask, enum compact_priority prio,
  2075. unsigned int alloc_flags, int highest_zoneidx,
  2076. struct page **capture)
  2077. {
  2078. enum compact_result ret;
  2079. struct compact_control cc = {
  2080. .order = order,
  2081. .search_order = order,
  2082. .gfp_mask = gfp_mask,
  2083. .zone = zone,
  2084. .mode = (prio == COMPACT_PRIO_ASYNC) ?
  2085. MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT,
  2086. .alloc_flags = alloc_flags,
  2087. .highest_zoneidx = highest_zoneidx,
  2088. .direct_compaction = true,
  2089. .whole_zone = (prio == MIN_COMPACT_PRIORITY),
  2090. .ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
  2091. .ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
  2092. };
  2093. struct capture_control capc = {
  2094. .cc = &cc,
  2095. .page = NULL,
  2096. };
  2097. /*
  2098. * Make sure the structs are really initialized before we expose the
  2099. * capture control, in case we are interrupted and the interrupt handler
  2100. * frees a page.
  2101. */
  2102. barrier();
  2103. WRITE_ONCE(current->capture_control, &capc);
  2104. ret = compact_zone(&cc, &capc);
  2105. VM_BUG_ON(!list_empty(&cc.freepages));
  2106. VM_BUG_ON(!list_empty(&cc.migratepages));
  2107. /*
  2108. * Make sure we hide capture control first before we read the captured
  2109. * page pointer, otherwise an interrupt could free and capture a page
  2110. * and we would leak it.
  2111. */
  2112. WRITE_ONCE(current->capture_control, NULL);
  2113. *capture = READ_ONCE(capc.page);
  2114. return ret;
  2115. }
  2116. int sysctl_extfrag_threshold = 500;
  2117. /**
  2118. * try_to_compact_pages - Direct compact to satisfy a high-order allocation
  2119. * @gfp_mask: The GFP mask of the current allocation
  2120. * @order: The order of the current allocation
  2121. * @alloc_flags: The allocation flags of the current allocation
  2122. * @ac: The context of current allocation
  2123. * @prio: Determines how hard direct compaction should try to succeed
  2124. * @capture: Pointer to free page created by compaction will be stored here
  2125. *
  2126. * This is the main entry point for direct page compaction.
  2127. */
  2128. enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
  2129. unsigned int alloc_flags, const struct alloc_context *ac,
  2130. enum compact_priority prio, struct page **capture)
  2131. {
  2132. int may_perform_io = gfp_mask & __GFP_IO;
  2133. struct zoneref *z;
  2134. struct zone *zone;
  2135. enum compact_result rc = COMPACT_SKIPPED;
  2136. /*
  2137. * Check if the GFP flags allow compaction - GFP_NOIO is really
  2138. * tricky context because the migration might require IO
  2139. */
  2140. if (!may_perform_io)
  2141. return COMPACT_SKIPPED;
  2142. trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
  2143. /* Compact each zone in the list */
  2144. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  2145. ac->highest_zoneidx, ac->nodemask) {
  2146. enum compact_result status;
  2147. if (prio > MIN_COMPACT_PRIORITY
  2148. && compaction_deferred(zone, order)) {
  2149. rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
  2150. continue;
  2151. }
  2152. status = compact_zone_order(zone, order, gfp_mask, prio,
  2153. alloc_flags, ac->highest_zoneidx, capture);
  2154. rc = max(status, rc);
  2155. /* The allocation should succeed, stop compacting */
  2156. if (status == COMPACT_SUCCESS) {
  2157. /*
  2158. * We think the allocation will succeed in this zone,
  2159. * but it is not certain, hence the false. The caller
  2160. * will repeat this with true if allocation indeed
  2161. * succeeds in this zone.
  2162. */
  2163. compaction_defer_reset(zone, order, false);
  2164. break;
  2165. }
  2166. if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
  2167. status == COMPACT_PARTIAL_SKIPPED))
  2168. /*
  2169. * We think that allocation won't succeed in this zone
  2170. * so we defer compaction there. If it ends up
  2171. * succeeding after all, it will be reset.
  2172. */
  2173. defer_compaction(zone, order);
  2174. /*
  2175. * We might have stopped compacting due to need_resched() in
  2176. * async compaction, or due to a fatal signal detected. In that
  2177. * case do not try further zones
  2178. */
  2179. if ((prio == COMPACT_PRIO_ASYNC && need_resched())
  2180. || fatal_signal_pending(current))
  2181. break;
  2182. }
  2183. return rc;
  2184. }
  2185. /*
  2186. * Compact all zones within a node till each zone's fragmentation score
  2187. * reaches within proactive compaction thresholds (as determined by the
  2188. * proactiveness tunable).
  2189. *
  2190. * It is possible that the function returns before reaching score targets
  2191. * due to various back-off conditions, such as, contention on per-node or
  2192. * per-zone locks.
  2193. */
  2194. static void proactive_compact_node(pg_data_t *pgdat)
  2195. {
  2196. int zoneid;
  2197. struct zone *zone;
  2198. struct compact_control cc = {
  2199. .order = -1,
  2200. .mode = MIGRATE_SYNC_LIGHT,
  2201. .ignore_skip_hint = true,
  2202. .whole_zone = true,
  2203. .gfp_mask = GFP_KERNEL,
  2204. .proactive_compaction = true,
  2205. };
  2206. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  2207. zone = &pgdat->node_zones[zoneid];
  2208. if (!populated_zone(zone))
  2209. continue;
  2210. cc.zone = zone;
  2211. compact_zone(&cc, NULL);
  2212. VM_BUG_ON(!list_empty(&cc.freepages));
  2213. VM_BUG_ON(!list_empty(&cc.migratepages));
  2214. }
  2215. }
  2216. /* Compact all zones within a node */
  2217. static void compact_node(int nid)
  2218. {
  2219. pg_data_t *pgdat = NODE_DATA(nid);
  2220. int zoneid;
  2221. struct zone *zone;
  2222. struct compact_control cc = {
  2223. .order = -1,
  2224. .mode = MIGRATE_SYNC,
  2225. .ignore_skip_hint = true,
  2226. .whole_zone = true,
  2227. .gfp_mask = GFP_KERNEL,
  2228. };
  2229. for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
  2230. zone = &pgdat->node_zones[zoneid];
  2231. if (!populated_zone(zone))
  2232. continue;
  2233. cc.zone = zone;
  2234. compact_zone(&cc, NULL);
  2235. VM_BUG_ON(!list_empty(&cc.freepages));
  2236. VM_BUG_ON(!list_empty(&cc.migratepages));
  2237. }
  2238. }
  2239. /* Compact all nodes in the system */
  2240. static void compact_nodes(void)
  2241. {
  2242. int nid;
  2243. /* Flush pending updates to the LRU lists */
  2244. lru_add_drain_all();
  2245. for_each_online_node(nid)
  2246. compact_node(nid);
  2247. }
  2248. /* The written value is actually unused, all memory is compacted */
  2249. int sysctl_compact_memory;
  2250. /*
  2251. * Tunable for proactive compaction. It determines how
  2252. * aggressively the kernel should compact memory in the
  2253. * background. It takes values in the range [0, 100].
  2254. */
  2255. unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
  2256. int compaction_proactiveness_sysctl_handler(struct ctl_table *table, int write,
  2257. void *buffer, size_t *length, loff_t *ppos)
  2258. {
  2259. int rc, nid;
  2260. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  2261. if (rc)
  2262. return rc;
  2263. if (write && sysctl_compaction_proactiveness) {
  2264. for_each_online_node(nid) {
  2265. pg_data_t *pgdat = NODE_DATA(nid);
  2266. if (pgdat->proactive_compact_trigger)
  2267. continue;
  2268. pgdat->proactive_compact_trigger = true;
  2269. wake_up_interruptible(&pgdat->kcompactd_wait);
  2270. }
  2271. }
  2272. return 0;
  2273. }
  2274. /*
  2275. * This is the entry point for compacting all nodes via
  2276. * /proc/sys/vm/compact_memory
  2277. */
  2278. int sysctl_compaction_handler(struct ctl_table *table, int write,
  2279. void *buffer, size_t *length, loff_t *ppos)
  2280. {
  2281. if (write)
  2282. compact_nodes();
  2283. return 0;
  2284. }
  2285. #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
  2286. static ssize_t sysfs_compact_node(struct device *dev,
  2287. struct device_attribute *attr,
  2288. const char *buf, size_t count)
  2289. {
  2290. int nid = dev->id;
  2291. if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
  2292. /* Flush pending updates to the LRU lists */
  2293. lru_add_drain_all();
  2294. compact_node(nid);
  2295. }
  2296. return count;
  2297. }
  2298. static DEVICE_ATTR(compact, 0200, NULL, sysfs_compact_node);
  2299. int compaction_register_node(struct node *node)
  2300. {
  2301. return device_create_file(&node->dev, &dev_attr_compact);
  2302. }
  2303. void compaction_unregister_node(struct node *node)
  2304. {
  2305. return device_remove_file(&node->dev, &dev_attr_compact);
  2306. }
  2307. #endif /* CONFIG_SYSFS && CONFIG_NUMA */
  2308. static inline bool kcompactd_work_requested(pg_data_t *pgdat)
  2309. {
  2310. return pgdat->kcompactd_max_order > 0 || kthread_should_stop() ||
  2311. pgdat->proactive_compact_trigger;
  2312. }
  2313. static bool kcompactd_node_suitable(pg_data_t *pgdat)
  2314. {
  2315. int zoneid;
  2316. struct zone *zone;
  2317. enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
  2318. for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
  2319. zone = &pgdat->node_zones[zoneid];
  2320. if (!populated_zone(zone))
  2321. continue;
  2322. if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
  2323. highest_zoneidx) == COMPACT_CONTINUE)
  2324. return true;
  2325. }
  2326. return false;
  2327. }
  2328. static void kcompactd_do_work(pg_data_t *pgdat)
  2329. {
  2330. /*
  2331. * With no special task, compact all zones so that a page of requested
  2332. * order is allocatable.
  2333. */
  2334. int zoneid;
  2335. struct zone *zone;
  2336. struct compact_control cc = {
  2337. .order = pgdat->kcompactd_max_order,
  2338. .search_order = pgdat->kcompactd_max_order,
  2339. .highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
  2340. .mode = MIGRATE_SYNC_LIGHT,
  2341. .ignore_skip_hint = false,
  2342. .gfp_mask = GFP_KERNEL,
  2343. };
  2344. trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
  2345. cc.highest_zoneidx);
  2346. count_compact_event(KCOMPACTD_WAKE);
  2347. for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
  2348. int status;
  2349. zone = &pgdat->node_zones[zoneid];
  2350. if (!populated_zone(zone))
  2351. continue;
  2352. if (compaction_deferred(zone, cc.order))
  2353. continue;
  2354. if (compaction_suitable(zone, cc.order, 0, zoneid) !=
  2355. COMPACT_CONTINUE)
  2356. continue;
  2357. if (kthread_should_stop())
  2358. return;
  2359. cc.zone = zone;
  2360. status = compact_zone(&cc, NULL);
  2361. if (status == COMPACT_SUCCESS) {
  2362. compaction_defer_reset(zone, cc.order, false);
  2363. } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
  2364. /*
  2365. * Buddy pages may become stranded on pcps that could
  2366. * otherwise coalesce on the zone's free area for
  2367. * order >= cc.order. This is ratelimited by the
  2368. * upcoming deferral.
  2369. */
  2370. drain_all_pages(zone);
  2371. /*
  2372. * We use sync migration mode here, so we defer like
  2373. * sync direct compaction does.
  2374. */
  2375. defer_compaction(zone, cc.order);
  2376. }
  2377. count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
  2378. cc.total_migrate_scanned);
  2379. count_compact_events(KCOMPACTD_FREE_SCANNED,
  2380. cc.total_free_scanned);
  2381. VM_BUG_ON(!list_empty(&cc.freepages));
  2382. VM_BUG_ON(!list_empty(&cc.migratepages));
  2383. }
  2384. /*
  2385. * Regardless of success, we are done until woken up next. But remember
  2386. * the requested order/highest_zoneidx in case it was higher/tighter
  2387. * than our current ones
  2388. */
  2389. if (pgdat->kcompactd_max_order <= cc.order)
  2390. pgdat->kcompactd_max_order = 0;
  2391. if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
  2392. pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
  2393. }
  2394. void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
  2395. {
  2396. if (!order)
  2397. return;
  2398. if (pgdat->kcompactd_max_order < order)
  2399. pgdat->kcompactd_max_order = order;
  2400. if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
  2401. pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
  2402. /*
  2403. * Pairs with implicit barrier in wait_event_freezable()
  2404. * such that wakeups are not missed.
  2405. */
  2406. if (!wq_has_sleeper(&pgdat->kcompactd_wait))
  2407. return;
  2408. if (!kcompactd_node_suitable(pgdat))
  2409. return;
  2410. trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
  2411. highest_zoneidx);
  2412. wake_up_interruptible(&pgdat->kcompactd_wait);
  2413. }
  2414. /*
  2415. * The background compaction daemon, started as a kernel thread
  2416. * from the init process.
  2417. */
  2418. static int kcompactd(void *p)
  2419. {
  2420. pg_data_t *pgdat = (pg_data_t*)p;
  2421. struct task_struct *tsk = current;
  2422. unsigned int proactive_defer = 0;
  2423. const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
  2424. if (!cpumask_empty(cpumask))
  2425. set_cpus_allowed_ptr(tsk, cpumask);
  2426. set_freezable();
  2427. pgdat->kcompactd_max_order = 0;
  2428. pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
  2429. while (!kthread_should_stop()) {
  2430. unsigned long pflags;
  2431. long timeout;
  2432. timeout = sysctl_compaction_proactiveness ?
  2433. msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC) :
  2434. MAX_SCHEDULE_TIMEOUT;
  2435. trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
  2436. if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
  2437. kcompactd_work_requested(pgdat), timeout) &&
  2438. !pgdat->proactive_compact_trigger) {
  2439. psi_memstall_enter(&pflags);
  2440. kcompactd_do_work(pgdat);
  2441. psi_memstall_leave(&pflags);
  2442. continue;
  2443. }
  2444. /* kcompactd wait timeout */
  2445. if (should_proactive_compact_node(pgdat)) {
  2446. unsigned int prev_score, score;
  2447. /*
  2448. * On wakeup of proactive compaction by sysctl
  2449. * write, ignore the accumulated defer score.
  2450. * Anyway, if the proactive compaction didn't
  2451. * make any progress for the new value, it will
  2452. * be further deferred by 2^COMPACT_MAX_DEFER_SHIFT
  2453. * times.
  2454. */
  2455. if (proactive_defer &&
  2456. !pgdat->proactive_compact_trigger) {
  2457. proactive_defer--;
  2458. continue;
  2459. }
  2460. prev_score = fragmentation_score_node(pgdat);
  2461. proactive_compact_node(pgdat);
  2462. score = fragmentation_score_node(pgdat);
  2463. /*
  2464. * Defer proactive compaction if the fragmentation
  2465. * score did not go down i.e. no progress made.
  2466. */
  2467. proactive_defer = score < prev_score ?
  2468. 0 : 1 << COMPACT_MAX_DEFER_SHIFT;
  2469. }
  2470. if (pgdat->proactive_compact_trigger)
  2471. pgdat->proactive_compact_trigger = false;
  2472. }
  2473. return 0;
  2474. }
  2475. /*
  2476. * This kcompactd start function will be called by init and node-hot-add.
  2477. * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
  2478. */
  2479. int kcompactd_run(int nid)
  2480. {
  2481. pg_data_t *pgdat = NODE_DATA(nid);
  2482. int ret = 0;
  2483. if (pgdat->kcompactd)
  2484. return 0;
  2485. pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
  2486. if (IS_ERR(pgdat->kcompactd)) {
  2487. pr_err("Failed to start kcompactd on node %d\n", nid);
  2488. ret = PTR_ERR(pgdat->kcompactd);
  2489. pgdat->kcompactd = NULL;
  2490. }
  2491. return ret;
  2492. }
  2493. /*
  2494. * Called by memory hotplug when all memory in a node is offlined. Caller must
  2495. * hold mem_hotplug_begin/end().
  2496. */
  2497. void kcompactd_stop(int nid)
  2498. {
  2499. struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
  2500. if (kcompactd) {
  2501. kthread_stop(kcompactd);
  2502. NODE_DATA(nid)->kcompactd = NULL;
  2503. }
  2504. }
  2505. /*
  2506. * It's optimal to keep kcompactd on the same CPUs as their memory, but
  2507. * not required for correctness. So if the last cpu in a node goes
  2508. * away, we get changed to run anywhere: as the first one comes back,
  2509. * restore their cpu bindings.
  2510. */
  2511. static int kcompactd_cpu_online(unsigned int cpu)
  2512. {
  2513. int nid;
  2514. for_each_node_state(nid, N_MEMORY) {
  2515. pg_data_t *pgdat = NODE_DATA(nid);
  2516. const struct cpumask *mask;
  2517. mask = cpumask_of_node(pgdat->node_id);
  2518. if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
  2519. /* One of our CPUs online: restore mask */
  2520. set_cpus_allowed_ptr(pgdat->kcompactd, mask);
  2521. }
  2522. return 0;
  2523. }
  2524. static int __init kcompactd_init(void)
  2525. {
  2526. int nid;
  2527. int ret;
  2528. ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
  2529. "mm/compaction:online",
  2530. kcompactd_cpu_online, NULL);
  2531. if (ret < 0) {
  2532. pr_err("kcompactd: failed to register hotplug callbacks.\n");
  2533. return ret;
  2534. }
  2535. for_each_node_state(nid, N_MEMORY)
  2536. kcompactd_run(nid);
  2537. return 0;
  2538. }
  2539. subsys_initcall(kcompactd_init)
  2540. #endif /* CONFIG_COMPACTION */