compaction.c 85 KB

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