compaction.c 93 KB

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