compaction.c 92 KB

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