migrate.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Memory Migration functionality - linux/mm/migrate.c
  4. *
  5. * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
  6. *
  7. * Page migration was first developed in the context of the memory hotplug
  8. * project. The main authors of the migration code are:
  9. *
  10. * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
  11. * Hirokazu Takahashi <taka@valinux.co.jp>
  12. * Dave Hansen <haveblue@us.ibm.com>
  13. * Christoph Lameter
  14. */
  15. #include <linux/migrate.h>
  16. #include <linux/export.h>
  17. #include <linux/swap.h>
  18. #include <linux/swapops.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/buffer_head.h>
  21. #include <linux/mm_inline.h>
  22. #include <linux/ksm.h>
  23. #include <linux/rmap.h>
  24. #include <linux/topology.h>
  25. #include <linux/cpu.h>
  26. #include <linux/cpuset.h>
  27. #include <linux/writeback.h>
  28. #include <linux/mempolicy.h>
  29. #include <linux/vmalloc.h>
  30. #include <linux/security.h>
  31. #include <linux/backing-dev.h>
  32. #include <linux/compaction.h>
  33. #include <linux/syscalls.h>
  34. #include <linux/compat.h>
  35. #include <linux/hugetlb.h>
  36. #include <linux/gfp.h>
  37. #include <linux/pfn_t.h>
  38. #include <linux/page_idle.h>
  39. #include <linux/page_owner.h>
  40. #include <linux/sched/mm.h>
  41. #include <linux/ptrace.h>
  42. #include <linux/memory.h>
  43. #include <linux/sched/sysctl.h>
  44. #include <linux/memory-tiers.h>
  45. #include <linux/pagewalk.h>
  46. #include <asm/tlbflush.h>
  47. #include <trace/events/migrate.h>
  48. #include "internal.h"
  49. bool isolate_movable_page(struct page *page, isolate_mode_t mode)
  50. {
  51. struct folio *folio = folio_get_nontail_page(page);
  52. const struct movable_operations *mops;
  53. /*
  54. * Avoid burning cycles with pages that are yet under __free_pages(),
  55. * or just got freed under us.
  56. *
  57. * In case we 'win' a race for a movable page being freed under us and
  58. * raise its refcount preventing __free_pages() from doing its job
  59. * the put_page() at the end of this block will take care of
  60. * release this page, thus avoiding a nasty leakage.
  61. */
  62. if (!folio)
  63. goto out;
  64. if (unlikely(folio_test_slab(folio)))
  65. goto out_putfolio;
  66. /* Pairs with smp_wmb() in slab freeing, e.g. SLUB's __free_slab() */
  67. smp_rmb();
  68. /*
  69. * Check movable flag before taking the page lock because
  70. * we use non-atomic bitops on newly allocated page flags so
  71. * unconditionally grabbing the lock ruins page's owner side.
  72. */
  73. if (unlikely(!__folio_test_movable(folio)))
  74. goto out_putfolio;
  75. /* Pairs with smp_wmb() in slab allocation, e.g. SLUB's alloc_slab_page() */
  76. smp_rmb();
  77. if (unlikely(folio_test_slab(folio)))
  78. goto out_putfolio;
  79. /*
  80. * As movable pages are not isolated from LRU lists, concurrent
  81. * compaction threads can race against page migration functions
  82. * as well as race against the releasing a page.
  83. *
  84. * In order to avoid having an already isolated movable page
  85. * being (wrongly) re-isolated while it is under migration,
  86. * or to avoid attempting to isolate pages being released,
  87. * lets be sure we have the page lock
  88. * before proceeding with the movable page isolation steps.
  89. */
  90. if (unlikely(!folio_trylock(folio)))
  91. goto out_putfolio;
  92. if (!folio_test_movable(folio) || folio_test_isolated(folio))
  93. goto out_no_isolated;
  94. mops = folio_movable_ops(folio);
  95. VM_BUG_ON_FOLIO(!mops, folio);
  96. if (!mops->isolate_page(&folio->page, mode))
  97. goto out_no_isolated;
  98. /* Driver shouldn't use the isolated flag */
  99. WARN_ON_ONCE(folio_test_isolated(folio));
  100. folio_set_isolated(folio);
  101. folio_unlock(folio);
  102. return true;
  103. out_no_isolated:
  104. folio_unlock(folio);
  105. out_putfolio:
  106. folio_put(folio);
  107. out:
  108. return false;
  109. }
  110. static void putback_movable_folio(struct folio *folio)
  111. {
  112. const struct movable_operations *mops = folio_movable_ops(folio);
  113. mops->putback_page(&folio->page);
  114. folio_clear_isolated(folio);
  115. }
  116. /*
  117. * Put previously isolated pages back onto the appropriate lists
  118. * from where they were once taken off for compaction/migration.
  119. *
  120. * This function shall be used whenever the isolated pageset has been
  121. * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range()
  122. * and isolate_hugetlb().
  123. */
  124. void putback_movable_pages(struct list_head *l)
  125. {
  126. struct folio *folio;
  127. struct folio *folio2;
  128. list_for_each_entry_safe(folio, folio2, l, lru) {
  129. if (unlikely(folio_test_hugetlb(folio))) {
  130. folio_putback_active_hugetlb(folio);
  131. continue;
  132. }
  133. list_del(&folio->lru);
  134. /*
  135. * We isolated non-lru movable folio so here we can use
  136. * __folio_test_movable because LRU folio's mapping cannot
  137. * have PAGE_MAPPING_MOVABLE.
  138. */
  139. if (unlikely(__folio_test_movable(folio))) {
  140. VM_BUG_ON_FOLIO(!folio_test_isolated(folio), folio);
  141. folio_lock(folio);
  142. if (folio_test_movable(folio))
  143. putback_movable_folio(folio);
  144. else
  145. folio_clear_isolated(folio);
  146. folio_unlock(folio);
  147. folio_put(folio);
  148. } else {
  149. node_stat_mod_folio(folio, NR_ISOLATED_ANON +
  150. folio_is_file_lru(folio), -folio_nr_pages(folio));
  151. folio_putback_lru(folio);
  152. }
  153. }
  154. }
  155. /* Must be called with an elevated refcount on the non-hugetlb folio */
  156. bool isolate_folio_to_list(struct folio *folio, struct list_head *list)
  157. {
  158. bool isolated, lru;
  159. if (folio_test_hugetlb(folio))
  160. return isolate_hugetlb(folio, list);
  161. lru = !__folio_test_movable(folio);
  162. if (lru)
  163. isolated = folio_isolate_lru(folio);
  164. else
  165. isolated = isolate_movable_page(&folio->page,
  166. ISOLATE_UNEVICTABLE);
  167. if (!isolated)
  168. return false;
  169. list_add(&folio->lru, list);
  170. if (lru)
  171. node_stat_add_folio(folio, NR_ISOLATED_ANON +
  172. folio_is_file_lru(folio));
  173. return true;
  174. }
  175. static bool try_to_map_unused_to_zeropage(struct page_vma_mapped_walk *pvmw,
  176. struct folio *folio, pte_t old_pte, unsigned long idx)
  177. {
  178. struct page *page = folio_page(folio, idx);
  179. pte_t newpte;
  180. if (PageCompound(page) || PageHWPoison(page))
  181. return false;
  182. VM_BUG_ON_PAGE(!PageAnon(page), page);
  183. VM_BUG_ON_PAGE(!PageLocked(page), page);
  184. VM_BUG_ON_PAGE(pte_present(old_pte), page);
  185. if (folio_test_mlocked(folio) || (pvmw->vma->vm_flags & VM_LOCKED) ||
  186. mm_forbids_zeropage(pvmw->vma->vm_mm))
  187. return false;
  188. /*
  189. * The pmd entry mapping the old thp was flushed and the pte mapping
  190. * this subpage has been non present. If the subpage is only zero-filled
  191. * then map it to the shared zeropage.
  192. */
  193. if (!pages_identical(page, ZERO_PAGE(0)))
  194. return false;
  195. newpte = pte_mkspecial(pfn_pte(my_zero_pfn(pvmw->address),
  196. pvmw->vma->vm_page_prot));
  197. if (pte_swp_soft_dirty(old_pte))
  198. newpte = pte_mksoft_dirty(newpte);
  199. if (pte_swp_uffd_wp(old_pte))
  200. newpte = pte_mkuffd_wp(newpte);
  201. set_pte_at(pvmw->vma->vm_mm, pvmw->address, pvmw->pte, newpte);
  202. dec_mm_counter(pvmw->vma->vm_mm, mm_counter(folio));
  203. return true;
  204. }
  205. struct rmap_walk_arg {
  206. struct folio *folio;
  207. bool map_unused_to_zeropage;
  208. };
  209. /*
  210. * Restore a potential migration pte to a working pte entry
  211. */
  212. static bool remove_migration_pte(struct folio *folio,
  213. struct vm_area_struct *vma, unsigned long addr, void *arg)
  214. {
  215. struct rmap_walk_arg *rmap_walk_arg = arg;
  216. DEFINE_FOLIO_VMA_WALK(pvmw, rmap_walk_arg->folio, vma, addr, PVMW_SYNC | PVMW_MIGRATION);
  217. while (page_vma_mapped_walk(&pvmw)) {
  218. rmap_t rmap_flags = RMAP_NONE;
  219. pte_t old_pte;
  220. pte_t pte;
  221. swp_entry_t entry;
  222. struct page *new;
  223. unsigned long idx = 0;
  224. /* pgoff is invalid for ksm pages, but they are never large */
  225. if (folio_test_large(folio) && !folio_test_hugetlb(folio))
  226. idx = linear_page_index(vma, pvmw.address) - pvmw.pgoff;
  227. new = folio_page(folio, idx);
  228. #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
  229. /* PMD-mapped THP migration entry */
  230. if (!pvmw.pte) {
  231. VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
  232. !folio_test_pmd_mappable(folio), folio);
  233. remove_migration_pmd(&pvmw, new);
  234. continue;
  235. }
  236. #endif
  237. old_pte = ptep_get(pvmw.pte);
  238. if (rmap_walk_arg->map_unused_to_zeropage &&
  239. try_to_map_unused_to_zeropage(&pvmw, folio, old_pte, idx))
  240. continue;
  241. folio_get(folio);
  242. pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
  243. entry = pte_to_swp_entry(old_pte);
  244. if (!is_migration_entry_young(entry))
  245. pte = pte_mkold(pte);
  246. if (folio_test_dirty(folio) && is_migration_entry_dirty(entry))
  247. pte = pte_mkdirty(pte);
  248. if (pte_swp_soft_dirty(old_pte))
  249. pte = pte_mksoft_dirty(pte);
  250. else
  251. pte = pte_clear_soft_dirty(pte);
  252. if (is_writable_migration_entry(entry))
  253. pte = pte_mkwrite(pte, vma);
  254. else if (pte_swp_uffd_wp(old_pte))
  255. pte = pte_mkuffd_wp(pte);
  256. if (folio_test_anon(folio) && !is_readable_migration_entry(entry))
  257. rmap_flags |= RMAP_EXCLUSIVE;
  258. if (unlikely(is_device_private_page(new))) {
  259. if (pte_write(pte))
  260. entry = make_writable_device_private_entry(
  261. page_to_pfn(new));
  262. else
  263. entry = make_readable_device_private_entry(
  264. page_to_pfn(new));
  265. pte = swp_entry_to_pte(entry);
  266. if (pte_swp_soft_dirty(old_pte))
  267. pte = pte_swp_mksoft_dirty(pte);
  268. if (pte_swp_uffd_wp(old_pte))
  269. pte = pte_swp_mkuffd_wp(pte);
  270. }
  271. #ifdef CONFIG_HUGETLB_PAGE
  272. if (folio_test_hugetlb(folio)) {
  273. struct hstate *h = hstate_vma(vma);
  274. unsigned int shift = huge_page_shift(h);
  275. unsigned long psize = huge_page_size(h);
  276. pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
  277. if (folio_test_anon(folio))
  278. hugetlb_add_anon_rmap(folio, vma, pvmw.address,
  279. rmap_flags);
  280. else
  281. hugetlb_add_file_rmap(folio);
  282. set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte,
  283. psize);
  284. } else
  285. #endif
  286. {
  287. if (folio_test_anon(folio))
  288. folio_add_anon_rmap_pte(folio, new, vma,
  289. pvmw.address, rmap_flags);
  290. else
  291. folio_add_file_rmap_pte(folio, new, vma);
  292. set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte);
  293. }
  294. if (vma->vm_flags & VM_LOCKED)
  295. mlock_drain_local();
  296. trace_remove_migration_pte(pvmw.address, pte_val(pte),
  297. compound_order(new));
  298. /* No need to invalidate - it was non-present before */
  299. update_mmu_cache(vma, pvmw.address, pvmw.pte);
  300. }
  301. return true;
  302. }
  303. /*
  304. * Get rid of all migration entries and replace them by
  305. * references to the indicated page.
  306. */
  307. void remove_migration_ptes(struct folio *src, struct folio *dst, int flags)
  308. {
  309. struct rmap_walk_arg rmap_walk_arg = {
  310. .folio = src,
  311. .map_unused_to_zeropage = flags & RMP_USE_SHARED_ZEROPAGE,
  312. };
  313. struct rmap_walk_control rwc = {
  314. .rmap_one = remove_migration_pte,
  315. .arg = &rmap_walk_arg,
  316. };
  317. VM_BUG_ON_FOLIO((flags & RMP_USE_SHARED_ZEROPAGE) && (src != dst), src);
  318. if (flags & RMP_LOCKED)
  319. rmap_walk_locked(dst, &rwc);
  320. else
  321. rmap_walk(dst, &rwc);
  322. }
  323. /*
  324. * Something used the pte of a page under migration. We need to
  325. * get to the page and wait until migration is finished.
  326. * When we return from this function the fault will be retried.
  327. */
  328. void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
  329. unsigned long address)
  330. {
  331. spinlock_t *ptl;
  332. pte_t *ptep;
  333. pte_t pte;
  334. swp_entry_t entry;
  335. ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
  336. if (!ptep)
  337. return;
  338. pte = ptep_get(ptep);
  339. pte_unmap(ptep);
  340. if (!is_swap_pte(pte))
  341. goto out;
  342. entry = pte_to_swp_entry(pte);
  343. if (!is_migration_entry(entry))
  344. goto out;
  345. migration_entry_wait_on_locked(entry, ptl);
  346. return;
  347. out:
  348. spin_unlock(ptl);
  349. }
  350. #ifdef CONFIG_HUGETLB_PAGE
  351. /*
  352. * The vma read lock must be held upon entry. Holding that lock prevents either
  353. * the pte or the ptl from being freed.
  354. *
  355. * This function will release the vma lock before returning.
  356. */
  357. void migration_entry_wait_huge(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
  358. {
  359. spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), vma->vm_mm, ptep);
  360. pte_t pte;
  361. hugetlb_vma_assert_locked(vma);
  362. spin_lock(ptl);
  363. pte = huge_ptep_get(vma->vm_mm, addr, ptep);
  364. if (unlikely(!is_hugetlb_entry_migration(pte))) {
  365. spin_unlock(ptl);
  366. hugetlb_vma_unlock_read(vma);
  367. } else {
  368. /*
  369. * If migration entry existed, safe to release vma lock
  370. * here because the pgtable page won't be freed without the
  371. * pgtable lock released. See comment right above pgtable
  372. * lock release in migration_entry_wait_on_locked().
  373. */
  374. hugetlb_vma_unlock_read(vma);
  375. migration_entry_wait_on_locked(pte_to_swp_entry(pte), ptl);
  376. }
  377. }
  378. #endif
  379. #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
  380. void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd)
  381. {
  382. spinlock_t *ptl;
  383. ptl = pmd_lock(mm, pmd);
  384. if (!is_pmd_migration_entry(*pmd))
  385. goto unlock;
  386. migration_entry_wait_on_locked(pmd_to_swp_entry(*pmd), ptl);
  387. return;
  388. unlock:
  389. spin_unlock(ptl);
  390. }
  391. #endif
  392. /*
  393. * Replace the folio in the mapping.
  394. *
  395. * The number of remaining references must be:
  396. * 1 for anonymous folios without a mapping
  397. * 2 for folios with a mapping
  398. * 3 for folios with a mapping and PagePrivate/PagePrivate2 set.
  399. */
  400. static int __folio_migrate_mapping(struct address_space *mapping,
  401. struct folio *newfolio, struct folio *folio, int expected_count)
  402. {
  403. XA_STATE(xas, &mapping->i_pages, folio_index(folio));
  404. struct zone *oldzone, *newzone;
  405. int dirty;
  406. long nr = folio_nr_pages(folio);
  407. long entries, i;
  408. if (!mapping) {
  409. /* Take off deferred split queue while frozen and memcg set */
  410. if (folio_test_large(folio) &&
  411. folio_test_large_rmappable(folio)) {
  412. if (!folio_ref_freeze(folio, expected_count))
  413. return -EAGAIN;
  414. folio_unqueue_deferred_split(folio);
  415. folio_ref_unfreeze(folio, expected_count);
  416. }
  417. /* No turning back from here */
  418. newfolio->index = folio->index;
  419. newfolio->mapping = folio->mapping;
  420. if (folio_test_anon(folio) && folio_test_large(folio))
  421. mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
  422. if (folio_test_swapbacked(folio))
  423. __folio_set_swapbacked(newfolio);
  424. return MIGRATEPAGE_SUCCESS;
  425. }
  426. oldzone = folio_zone(folio);
  427. newzone = folio_zone(newfolio);
  428. xas_lock_irq(&xas);
  429. if (!folio_ref_freeze(folio, expected_count)) {
  430. xas_unlock_irq(&xas);
  431. return -EAGAIN;
  432. }
  433. /* Take off deferred split queue while frozen and memcg set */
  434. folio_unqueue_deferred_split(folio);
  435. /*
  436. * Now we know that no one else is looking at the folio:
  437. * no turning back from here.
  438. */
  439. newfolio->index = folio->index;
  440. newfolio->mapping = folio->mapping;
  441. if (folio_test_anon(folio) && folio_test_large(folio))
  442. mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
  443. folio_ref_add(newfolio, nr); /* add cache reference */
  444. if (folio_test_swapbacked(folio))
  445. __folio_set_swapbacked(newfolio);
  446. if (folio_test_swapcache(folio)) {
  447. folio_set_swapcache(newfolio);
  448. newfolio->private = folio_get_private(folio);
  449. entries = nr;
  450. } else {
  451. entries = 1;
  452. }
  453. /* Move dirty while folio refs frozen and newfolio not yet exposed */
  454. dirty = folio_test_dirty(folio);
  455. if (dirty) {
  456. folio_clear_dirty(folio);
  457. folio_set_dirty(newfolio);
  458. }
  459. /* Swap cache still stores N entries instead of a high-order entry */
  460. for (i = 0; i < entries; i++) {
  461. xas_store(&xas, newfolio);
  462. xas_next(&xas);
  463. }
  464. /*
  465. * Drop cache reference from old folio by unfreezing
  466. * to one less reference.
  467. * We know this isn't the last reference.
  468. */
  469. folio_ref_unfreeze(folio, expected_count - nr);
  470. xas_unlock(&xas);
  471. /* Leave irq disabled to prevent preemption while updating stats */
  472. /*
  473. * If moved to a different zone then also account
  474. * the folio for that zone. Other VM counters will be
  475. * taken care of when we establish references to the
  476. * new folio and drop references to the old folio.
  477. *
  478. * Note that anonymous folios are accounted for
  479. * via NR_FILE_PAGES and NR_ANON_MAPPED if they
  480. * are mapped to swap space.
  481. */
  482. if (newzone != oldzone) {
  483. struct lruvec *old_lruvec, *new_lruvec;
  484. struct mem_cgroup *memcg;
  485. memcg = folio_memcg(folio);
  486. old_lruvec = mem_cgroup_lruvec(memcg, oldzone->zone_pgdat);
  487. new_lruvec = mem_cgroup_lruvec(memcg, newzone->zone_pgdat);
  488. __mod_lruvec_state(old_lruvec, NR_FILE_PAGES, -nr);
  489. __mod_lruvec_state(new_lruvec, NR_FILE_PAGES, nr);
  490. if (folio_test_swapbacked(folio) && !folio_test_swapcache(folio)) {
  491. __mod_lruvec_state(old_lruvec, NR_SHMEM, -nr);
  492. __mod_lruvec_state(new_lruvec, NR_SHMEM, nr);
  493. if (folio_test_pmd_mappable(folio)) {
  494. __mod_lruvec_state(old_lruvec, NR_SHMEM_THPS, -nr);
  495. __mod_lruvec_state(new_lruvec, NR_SHMEM_THPS, nr);
  496. }
  497. }
  498. #ifdef CONFIG_SWAP
  499. if (folio_test_swapcache(folio)) {
  500. __mod_lruvec_state(old_lruvec, NR_SWAPCACHE, -nr);
  501. __mod_lruvec_state(new_lruvec, NR_SWAPCACHE, nr);
  502. }
  503. #endif
  504. if (dirty && mapping_can_writeback(mapping)) {
  505. __mod_lruvec_state(old_lruvec, NR_FILE_DIRTY, -nr);
  506. __mod_zone_page_state(oldzone, NR_ZONE_WRITE_PENDING, -nr);
  507. __mod_lruvec_state(new_lruvec, NR_FILE_DIRTY, nr);
  508. __mod_zone_page_state(newzone, NR_ZONE_WRITE_PENDING, nr);
  509. }
  510. }
  511. local_irq_enable();
  512. return MIGRATEPAGE_SUCCESS;
  513. }
  514. int folio_migrate_mapping(struct address_space *mapping,
  515. struct folio *newfolio, struct folio *folio, int extra_count)
  516. {
  517. int expected_count = folio_expected_ref_count(folio) + extra_count + 1;
  518. if (folio_ref_count(folio) != expected_count)
  519. return -EAGAIN;
  520. return __folio_migrate_mapping(mapping, newfolio, folio, expected_count);
  521. }
  522. EXPORT_SYMBOL(folio_migrate_mapping);
  523. /*
  524. * The expected number of remaining references is the same as that
  525. * of folio_migrate_mapping().
  526. */
  527. int migrate_huge_page_move_mapping(struct address_space *mapping,
  528. struct folio *dst, struct folio *src)
  529. {
  530. XA_STATE(xas, &mapping->i_pages, folio_index(src));
  531. int rc, expected_count = folio_expected_ref_count(src) + 1;
  532. if (folio_ref_count(src) != expected_count)
  533. return -EAGAIN;
  534. rc = folio_mc_copy(dst, src);
  535. if (unlikely(rc))
  536. return rc;
  537. xas_lock_irq(&xas);
  538. if (!folio_ref_freeze(src, expected_count)) {
  539. xas_unlock_irq(&xas);
  540. return -EAGAIN;
  541. }
  542. dst->index = src->index;
  543. dst->mapping = src->mapping;
  544. folio_ref_add(dst, folio_nr_pages(dst));
  545. xas_store(&xas, dst);
  546. folio_ref_unfreeze(src, expected_count - folio_nr_pages(src));
  547. xas_unlock_irq(&xas);
  548. return MIGRATEPAGE_SUCCESS;
  549. }
  550. /*
  551. * Copy the flags and some other ancillary information
  552. */
  553. void folio_migrate_flags(struct folio *newfolio, struct folio *folio)
  554. {
  555. int cpupid;
  556. if (folio_test_referenced(folio))
  557. folio_set_referenced(newfolio);
  558. if (folio_test_uptodate(folio))
  559. folio_mark_uptodate(newfolio);
  560. if (folio_test_clear_active(folio)) {
  561. VM_BUG_ON_FOLIO(folio_test_unevictable(folio), folio);
  562. folio_set_active(newfolio);
  563. } else if (folio_test_clear_unevictable(folio))
  564. folio_set_unevictable(newfolio);
  565. if (folio_test_workingset(folio))
  566. folio_set_workingset(newfolio);
  567. if (folio_test_checked(folio))
  568. folio_set_checked(newfolio);
  569. /*
  570. * PG_anon_exclusive (-> PG_mappedtodisk) is always migrated via
  571. * migration entries. We can still have PG_anon_exclusive set on an
  572. * effectively unmapped and unreferenced first sub-pages of an
  573. * anonymous THP: we can simply copy it here via PG_mappedtodisk.
  574. */
  575. if (folio_test_mappedtodisk(folio))
  576. folio_set_mappedtodisk(newfolio);
  577. /* Move dirty on pages not done by folio_migrate_mapping() */
  578. if (folio_test_dirty(folio))
  579. folio_set_dirty(newfolio);
  580. if (folio_test_young(folio))
  581. folio_set_young(newfolio);
  582. if (folio_test_idle(folio))
  583. folio_set_idle(newfolio);
  584. /*
  585. * Copy NUMA information to the new page, to prevent over-eager
  586. * future migrations of this same page.
  587. */
  588. cpupid = folio_xchg_last_cpupid(folio, -1);
  589. /*
  590. * For memory tiering mode, when migrate between slow and fast
  591. * memory node, reset cpupid, because that is used to record
  592. * page access time in slow memory node.
  593. */
  594. if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) {
  595. bool f_toptier = node_is_toptier(folio_nid(folio));
  596. bool t_toptier = node_is_toptier(folio_nid(newfolio));
  597. if (f_toptier != t_toptier)
  598. cpupid = -1;
  599. }
  600. folio_xchg_last_cpupid(newfolio, cpupid);
  601. folio_migrate_ksm(newfolio, folio);
  602. /*
  603. * Please do not reorder this without considering how mm/ksm.c's
  604. * ksm_get_folio() depends upon ksm_migrate_page() and the
  605. * swapcache flag.
  606. */
  607. if (folio_test_swapcache(folio))
  608. folio_clear_swapcache(folio);
  609. folio_clear_private(folio);
  610. /* page->private contains hugetlb specific flags */
  611. if (!folio_test_hugetlb(folio))
  612. folio->private = NULL;
  613. /*
  614. * If any waiters have accumulated on the new page then
  615. * wake them up.
  616. */
  617. if (folio_test_writeback(newfolio))
  618. folio_end_writeback(newfolio);
  619. /*
  620. * PG_readahead shares the same bit with PG_reclaim. The above
  621. * end_page_writeback() may clear PG_readahead mistakenly, so set the
  622. * bit after that.
  623. */
  624. if (folio_test_readahead(folio))
  625. folio_set_readahead(newfolio);
  626. folio_copy_owner(newfolio, folio);
  627. pgalloc_tag_copy(newfolio, folio);
  628. mem_cgroup_migrate(folio, newfolio);
  629. }
  630. EXPORT_SYMBOL(folio_migrate_flags);
  631. /************************************************************
  632. * Migration functions
  633. ***********************************************************/
  634. static int __migrate_folio(struct address_space *mapping, struct folio *dst,
  635. struct folio *src, void *src_private,
  636. enum migrate_mode mode)
  637. {
  638. int rc, expected_count = folio_expected_ref_count(src) + 1;
  639. /* Check whether src does not have extra refs before we do more work */
  640. if (folio_ref_count(src) != expected_count)
  641. return -EAGAIN;
  642. rc = folio_mc_copy(dst, src);
  643. if (unlikely(rc))
  644. return rc;
  645. rc = __folio_migrate_mapping(mapping, dst, src, expected_count);
  646. if (rc != MIGRATEPAGE_SUCCESS)
  647. return rc;
  648. if (src_private)
  649. folio_attach_private(dst, folio_detach_private(src));
  650. folio_migrate_flags(dst, src);
  651. return MIGRATEPAGE_SUCCESS;
  652. }
  653. /**
  654. * migrate_folio() - Simple folio migration.
  655. * @mapping: The address_space containing the folio.
  656. * @dst: The folio to migrate the data to.
  657. * @src: The folio containing the current data.
  658. * @mode: How to migrate the page.
  659. *
  660. * Common logic to directly migrate a single LRU folio suitable for
  661. * folios that do not use PagePrivate/PagePrivate2.
  662. *
  663. * Folios are locked upon entry and exit.
  664. */
  665. int migrate_folio(struct address_space *mapping, struct folio *dst,
  666. struct folio *src, enum migrate_mode mode)
  667. {
  668. BUG_ON(folio_test_writeback(src)); /* Writeback must be complete */
  669. return __migrate_folio(mapping, dst, src, NULL, mode);
  670. }
  671. EXPORT_SYMBOL(migrate_folio);
  672. #ifdef CONFIG_BUFFER_HEAD
  673. /* Returns true if all buffers are successfully locked */
  674. static bool buffer_migrate_lock_buffers(struct buffer_head *head,
  675. enum migrate_mode mode)
  676. {
  677. struct buffer_head *bh = head;
  678. struct buffer_head *failed_bh;
  679. do {
  680. if (!trylock_buffer(bh)) {
  681. if (mode == MIGRATE_ASYNC)
  682. goto unlock;
  683. if (mode == MIGRATE_SYNC_LIGHT && !buffer_uptodate(bh))
  684. goto unlock;
  685. lock_buffer(bh);
  686. }
  687. bh = bh->b_this_page;
  688. } while (bh != head);
  689. return true;
  690. unlock:
  691. /* We failed to lock the buffer and cannot stall. */
  692. failed_bh = bh;
  693. bh = head;
  694. while (bh != failed_bh) {
  695. unlock_buffer(bh);
  696. bh = bh->b_this_page;
  697. }
  698. return false;
  699. }
  700. static int __buffer_migrate_folio(struct address_space *mapping,
  701. struct folio *dst, struct folio *src, enum migrate_mode mode,
  702. bool check_refs)
  703. {
  704. struct buffer_head *bh, *head;
  705. int rc;
  706. int expected_count;
  707. head = folio_buffers(src);
  708. if (!head)
  709. return migrate_folio(mapping, dst, src, mode);
  710. /* Check whether page does not have extra refs before we do more work */
  711. expected_count = folio_expected_ref_count(src) + 1;
  712. if (folio_ref_count(src) != expected_count)
  713. return -EAGAIN;
  714. if (!buffer_migrate_lock_buffers(head, mode))
  715. return -EAGAIN;
  716. if (check_refs) {
  717. bool busy;
  718. bool invalidated = false;
  719. recheck_buffers:
  720. busy = false;
  721. spin_lock(&mapping->i_private_lock);
  722. bh = head;
  723. do {
  724. if (atomic_read(&bh->b_count)) {
  725. busy = true;
  726. break;
  727. }
  728. bh = bh->b_this_page;
  729. } while (bh != head);
  730. if (busy) {
  731. if (invalidated) {
  732. rc = -EAGAIN;
  733. goto unlock_buffers;
  734. }
  735. spin_unlock(&mapping->i_private_lock);
  736. invalidate_bh_lrus();
  737. invalidated = true;
  738. goto recheck_buffers;
  739. }
  740. }
  741. rc = filemap_migrate_folio(mapping, dst, src, mode);
  742. if (rc != MIGRATEPAGE_SUCCESS)
  743. goto unlock_buffers;
  744. bh = head;
  745. do {
  746. folio_set_bh(bh, dst, bh_offset(bh));
  747. bh = bh->b_this_page;
  748. } while (bh != head);
  749. unlock_buffers:
  750. if (check_refs)
  751. spin_unlock(&mapping->i_private_lock);
  752. bh = head;
  753. do {
  754. unlock_buffer(bh);
  755. bh = bh->b_this_page;
  756. } while (bh != head);
  757. return rc;
  758. }
  759. /**
  760. * buffer_migrate_folio() - Migration function for folios with buffers.
  761. * @mapping: The address space containing @src.
  762. * @dst: The folio to migrate to.
  763. * @src: The folio to migrate from.
  764. * @mode: How to migrate the folio.
  765. *
  766. * This function can only be used if the underlying filesystem guarantees
  767. * that no other references to @src exist. For example attached buffer
  768. * heads are accessed only under the folio lock. If your filesystem cannot
  769. * provide this guarantee, buffer_migrate_folio_norefs() may be more
  770. * appropriate.
  771. *
  772. * Return: 0 on success or a negative errno on failure.
  773. */
  774. int buffer_migrate_folio(struct address_space *mapping,
  775. struct folio *dst, struct folio *src, enum migrate_mode mode)
  776. {
  777. return __buffer_migrate_folio(mapping, dst, src, mode, false);
  778. }
  779. EXPORT_SYMBOL(buffer_migrate_folio);
  780. /**
  781. * buffer_migrate_folio_norefs() - Migration function for folios with buffers.
  782. * @mapping: The address space containing @src.
  783. * @dst: The folio to migrate to.
  784. * @src: The folio to migrate from.
  785. * @mode: How to migrate the folio.
  786. *
  787. * Like buffer_migrate_folio() except that this variant is more careful
  788. * and checks that there are also no buffer head references. This function
  789. * is the right one for mappings where buffer heads are directly looked
  790. * up and referenced (such as block device mappings).
  791. *
  792. * Return: 0 on success or a negative errno on failure.
  793. */
  794. int buffer_migrate_folio_norefs(struct address_space *mapping,
  795. struct folio *dst, struct folio *src, enum migrate_mode mode)
  796. {
  797. return __buffer_migrate_folio(mapping, dst, src, mode, true);
  798. }
  799. EXPORT_SYMBOL_GPL(buffer_migrate_folio_norefs);
  800. #endif /* CONFIG_BUFFER_HEAD */
  801. int filemap_migrate_folio(struct address_space *mapping,
  802. struct folio *dst, struct folio *src, enum migrate_mode mode)
  803. {
  804. return __migrate_folio(mapping, dst, src, folio_get_private(src), mode);
  805. }
  806. EXPORT_SYMBOL_GPL(filemap_migrate_folio);
  807. /*
  808. * Writeback a folio to clean the dirty state
  809. */
  810. static int writeout(struct address_space *mapping, struct folio *folio)
  811. {
  812. struct writeback_control wbc = {
  813. .sync_mode = WB_SYNC_NONE,
  814. .nr_to_write = 1,
  815. .range_start = 0,
  816. .range_end = LLONG_MAX,
  817. .for_reclaim = 1
  818. };
  819. int rc;
  820. if (!mapping->a_ops->writepage)
  821. /* No write method for the address space */
  822. return -EINVAL;
  823. if (!folio_clear_dirty_for_io(folio))
  824. /* Someone else already triggered a write */
  825. return -EAGAIN;
  826. /*
  827. * A dirty folio may imply that the underlying filesystem has
  828. * the folio on some queue. So the folio must be clean for
  829. * migration. Writeout may mean we lose the lock and the
  830. * folio state is no longer what we checked for earlier.
  831. * At this point we know that the migration attempt cannot
  832. * be successful.
  833. */
  834. remove_migration_ptes(folio, folio, 0);
  835. rc = mapping->a_ops->writepage(&folio->page, &wbc);
  836. if (rc != AOP_WRITEPAGE_ACTIVATE)
  837. /* unlocked. Relock */
  838. folio_lock(folio);
  839. return (rc < 0) ? -EIO : -EAGAIN;
  840. }
  841. /*
  842. * Default handling if a filesystem does not provide a migration function.
  843. */
  844. static int fallback_migrate_folio(struct address_space *mapping,
  845. struct folio *dst, struct folio *src, enum migrate_mode mode)
  846. {
  847. if (folio_test_dirty(src)) {
  848. /* Only writeback folios in full synchronous migration */
  849. switch (mode) {
  850. case MIGRATE_SYNC:
  851. break;
  852. default:
  853. return -EBUSY;
  854. }
  855. return writeout(mapping, src);
  856. }
  857. /*
  858. * Buffers may be managed in a filesystem specific way.
  859. * We must have no buffers or drop them.
  860. */
  861. if (!filemap_release_folio(src, GFP_KERNEL))
  862. return mode == MIGRATE_SYNC ? -EAGAIN : -EBUSY;
  863. return migrate_folio(mapping, dst, src, mode);
  864. }
  865. /*
  866. * Move a page to a newly allocated page
  867. * The page is locked and all ptes have been successfully removed.
  868. *
  869. * The new page will have replaced the old page if this function
  870. * is successful.
  871. *
  872. * Return value:
  873. * < 0 - error code
  874. * MIGRATEPAGE_SUCCESS - success
  875. */
  876. static int move_to_new_folio(struct folio *dst, struct folio *src,
  877. enum migrate_mode mode)
  878. {
  879. int rc = -EAGAIN;
  880. bool is_lru = !__folio_test_movable(src);
  881. VM_BUG_ON_FOLIO(!folio_test_locked(src), src);
  882. VM_BUG_ON_FOLIO(!folio_test_locked(dst), dst);
  883. if (likely(is_lru)) {
  884. struct address_space *mapping = folio_mapping(src);
  885. if (!mapping)
  886. rc = migrate_folio(mapping, dst, src, mode);
  887. else if (mapping_inaccessible(mapping))
  888. rc = -EOPNOTSUPP;
  889. else if (mapping->a_ops->migrate_folio)
  890. /*
  891. * Most folios have a mapping and most filesystems
  892. * provide a migrate_folio callback. Anonymous folios
  893. * are part of swap space which also has its own
  894. * migrate_folio callback. This is the most common path
  895. * for page migration.
  896. */
  897. rc = mapping->a_ops->migrate_folio(mapping, dst, src,
  898. mode);
  899. else
  900. rc = fallback_migrate_folio(mapping, dst, src, mode);
  901. } else {
  902. const struct movable_operations *mops;
  903. /*
  904. * In case of non-lru page, it could be released after
  905. * isolation step. In that case, we shouldn't try migration.
  906. */
  907. VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
  908. if (!folio_test_movable(src)) {
  909. rc = MIGRATEPAGE_SUCCESS;
  910. folio_clear_isolated(src);
  911. goto out;
  912. }
  913. mops = folio_movable_ops(src);
  914. rc = mops->migrate_page(&dst->page, &src->page, mode);
  915. WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
  916. !folio_test_isolated(src));
  917. }
  918. /*
  919. * When successful, old pagecache src->mapping must be cleared before
  920. * src is freed; but stats require that PageAnon be left as PageAnon.
  921. */
  922. if (rc == MIGRATEPAGE_SUCCESS) {
  923. if (__folio_test_movable(src)) {
  924. VM_BUG_ON_FOLIO(!folio_test_isolated(src), src);
  925. /*
  926. * We clear PG_movable under page_lock so any compactor
  927. * cannot try to migrate this page.
  928. */
  929. folio_clear_isolated(src);
  930. }
  931. /*
  932. * Anonymous and movable src->mapping will be cleared by
  933. * free_pages_prepare so don't reset it here for keeping
  934. * the type to work PageAnon, for example.
  935. */
  936. if (!folio_mapping_flags(src))
  937. src->mapping = NULL;
  938. if (likely(!folio_is_zone_device(dst)))
  939. flush_dcache_folio(dst);
  940. }
  941. out:
  942. return rc;
  943. }
  944. /*
  945. * To record some information during migration, we use unused private
  946. * field of struct folio of the newly allocated destination folio.
  947. * This is safe because nobody is using it except us.
  948. */
  949. enum {
  950. PAGE_WAS_MAPPED = BIT(0),
  951. PAGE_WAS_MLOCKED = BIT(1),
  952. PAGE_OLD_STATES = PAGE_WAS_MAPPED | PAGE_WAS_MLOCKED,
  953. };
  954. static void __migrate_folio_record(struct folio *dst,
  955. int old_page_state,
  956. struct anon_vma *anon_vma)
  957. {
  958. dst->private = (void *)anon_vma + old_page_state;
  959. }
  960. static void __migrate_folio_extract(struct folio *dst,
  961. int *old_page_state,
  962. struct anon_vma **anon_vmap)
  963. {
  964. unsigned long private = (unsigned long)dst->private;
  965. *anon_vmap = (struct anon_vma *)(private & ~PAGE_OLD_STATES);
  966. *old_page_state = private & PAGE_OLD_STATES;
  967. dst->private = NULL;
  968. }
  969. /* Restore the source folio to the original state upon failure */
  970. static void migrate_folio_undo_src(struct folio *src,
  971. int page_was_mapped,
  972. struct anon_vma *anon_vma,
  973. bool locked,
  974. struct list_head *ret)
  975. {
  976. if (page_was_mapped)
  977. remove_migration_ptes(src, src, 0);
  978. /* Drop an anon_vma reference if we took one */
  979. if (anon_vma)
  980. put_anon_vma(anon_vma);
  981. if (locked)
  982. folio_unlock(src);
  983. if (ret)
  984. list_move_tail(&src->lru, ret);
  985. }
  986. /* Restore the destination folio to the original state upon failure */
  987. static void migrate_folio_undo_dst(struct folio *dst, bool locked,
  988. free_folio_t put_new_folio, unsigned long private)
  989. {
  990. if (locked)
  991. folio_unlock(dst);
  992. if (put_new_folio)
  993. put_new_folio(dst, private);
  994. else
  995. folio_put(dst);
  996. }
  997. /* Cleanup src folio upon migration success */
  998. static void migrate_folio_done(struct folio *src,
  999. enum migrate_reason reason)
  1000. {
  1001. /*
  1002. * Compaction can migrate also non-LRU pages which are
  1003. * not accounted to NR_ISOLATED_*. They can be recognized
  1004. * as __folio_test_movable
  1005. */
  1006. if (likely(!__folio_test_movable(src)) && reason != MR_DEMOTION)
  1007. mod_node_page_state(folio_pgdat(src), NR_ISOLATED_ANON +
  1008. folio_is_file_lru(src), -folio_nr_pages(src));
  1009. if (reason != MR_MEMORY_FAILURE)
  1010. /* We release the page in page_handle_poison. */
  1011. folio_put(src);
  1012. }
  1013. /* Obtain the lock on page, remove all ptes. */
  1014. static int migrate_folio_unmap(new_folio_t get_new_folio,
  1015. free_folio_t put_new_folio, unsigned long private,
  1016. struct folio *src, struct folio **dstp, enum migrate_mode mode,
  1017. enum migrate_reason reason, struct list_head *ret)
  1018. {
  1019. struct folio *dst;
  1020. int rc = -EAGAIN;
  1021. int old_page_state = 0;
  1022. struct anon_vma *anon_vma = NULL;
  1023. bool is_lru = data_race(!__folio_test_movable(src));
  1024. bool locked = false;
  1025. bool dst_locked = false;
  1026. if (folio_ref_count(src) == 1) {
  1027. /* Folio was freed from under us. So we are done. */
  1028. folio_clear_active(src);
  1029. folio_clear_unevictable(src);
  1030. /* free_pages_prepare() will clear PG_isolated. */
  1031. list_del(&src->lru);
  1032. migrate_folio_done(src, reason);
  1033. return MIGRATEPAGE_SUCCESS;
  1034. }
  1035. dst = get_new_folio(src, private);
  1036. if (!dst)
  1037. return -ENOMEM;
  1038. *dstp = dst;
  1039. dst->private = NULL;
  1040. if (!folio_trylock(src)) {
  1041. if (mode == MIGRATE_ASYNC)
  1042. goto out;
  1043. /*
  1044. * It's not safe for direct compaction to call lock_page.
  1045. * For example, during page readahead pages are added locked
  1046. * to the LRU. Later, when the IO completes the pages are
  1047. * marked uptodate and unlocked. However, the queueing
  1048. * could be merging multiple pages for one bio (e.g.
  1049. * mpage_readahead). If an allocation happens for the
  1050. * second or third page, the process can end up locking
  1051. * the same page twice and deadlocking. Rather than
  1052. * trying to be clever about what pages can be locked,
  1053. * avoid the use of lock_page for direct compaction
  1054. * altogether.
  1055. */
  1056. if (current->flags & PF_MEMALLOC)
  1057. goto out;
  1058. /*
  1059. * In "light" mode, we can wait for transient locks (eg
  1060. * inserting a page into the page table), but it's not
  1061. * worth waiting for I/O.
  1062. */
  1063. if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
  1064. goto out;
  1065. folio_lock(src);
  1066. }
  1067. locked = true;
  1068. if (folio_test_mlocked(src))
  1069. old_page_state |= PAGE_WAS_MLOCKED;
  1070. if (folio_test_writeback(src)) {
  1071. /*
  1072. * Only in the case of a full synchronous migration is it
  1073. * necessary to wait for PageWriteback. In the async case,
  1074. * the retry loop is too short and in the sync-light case,
  1075. * the overhead of stalling is too much
  1076. */
  1077. switch (mode) {
  1078. case MIGRATE_SYNC:
  1079. break;
  1080. default:
  1081. rc = -EBUSY;
  1082. goto out;
  1083. }
  1084. folio_wait_writeback(src);
  1085. }
  1086. /*
  1087. * By try_to_migrate(), src->mapcount goes down to 0 here. In this case,
  1088. * we cannot notice that anon_vma is freed while we migrate a page.
  1089. * This get_anon_vma() delays freeing anon_vma pointer until the end
  1090. * of migration. File cache pages are no problem because of page_lock()
  1091. * File Caches may use write_page() or lock_page() in migration, then,
  1092. * just care Anon page here.
  1093. *
  1094. * Only folio_get_anon_vma() understands the subtleties of
  1095. * getting a hold on an anon_vma from outside one of its mms.
  1096. * But if we cannot get anon_vma, then we won't need it anyway,
  1097. * because that implies that the anon page is no longer mapped
  1098. * (and cannot be remapped so long as we hold the page lock).
  1099. */
  1100. if (folio_test_anon(src) && !folio_test_ksm(src))
  1101. anon_vma = folio_get_anon_vma(src);
  1102. /*
  1103. * Block others from accessing the new page when we get around to
  1104. * establishing additional references. We are usually the only one
  1105. * holding a reference to dst at this point. We used to have a BUG
  1106. * here if folio_trylock(dst) fails, but would like to allow for
  1107. * cases where there might be a race with the previous use of dst.
  1108. * This is much like races on refcount of oldpage: just don't BUG().
  1109. */
  1110. if (unlikely(!folio_trylock(dst)))
  1111. goto out;
  1112. dst_locked = true;
  1113. if (unlikely(!is_lru)) {
  1114. __migrate_folio_record(dst, old_page_state, anon_vma);
  1115. return MIGRATEPAGE_UNMAP;
  1116. }
  1117. /*
  1118. * Corner case handling:
  1119. * 1. When a new swap-cache page is read into, it is added to the LRU
  1120. * and treated as swapcache but it has no rmap yet.
  1121. * Calling try_to_unmap() against a src->mapping==NULL page will
  1122. * trigger a BUG. So handle it here.
  1123. * 2. An orphaned page (see truncate_cleanup_page) might have
  1124. * fs-private metadata. The page can be picked up due to memory
  1125. * offlining. Everywhere else except page reclaim, the page is
  1126. * invisible to the vm, so the page can not be migrated. So try to
  1127. * free the metadata, so the page can be freed.
  1128. */
  1129. if (!src->mapping) {
  1130. if (folio_test_private(src)) {
  1131. try_to_free_buffers(src);
  1132. goto out;
  1133. }
  1134. } else if (folio_mapped(src)) {
  1135. /* Establish migration ptes */
  1136. VM_BUG_ON_FOLIO(folio_test_anon(src) &&
  1137. !folio_test_ksm(src) && !anon_vma, src);
  1138. try_to_migrate(src, mode == MIGRATE_ASYNC ? TTU_BATCH_FLUSH : 0);
  1139. old_page_state |= PAGE_WAS_MAPPED;
  1140. }
  1141. if (!folio_mapped(src)) {
  1142. __migrate_folio_record(dst, old_page_state, anon_vma);
  1143. return MIGRATEPAGE_UNMAP;
  1144. }
  1145. out:
  1146. /*
  1147. * A folio that has not been unmapped will be restored to
  1148. * right list unless we want to retry.
  1149. */
  1150. if (rc == -EAGAIN)
  1151. ret = NULL;
  1152. migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
  1153. anon_vma, locked, ret);
  1154. migrate_folio_undo_dst(dst, dst_locked, put_new_folio, private);
  1155. return rc;
  1156. }
  1157. /* Migrate the folio to the newly allocated folio in dst. */
  1158. static int migrate_folio_move(free_folio_t put_new_folio, unsigned long private,
  1159. struct folio *src, struct folio *dst,
  1160. enum migrate_mode mode, enum migrate_reason reason,
  1161. struct list_head *ret)
  1162. {
  1163. int rc;
  1164. int old_page_state = 0;
  1165. struct anon_vma *anon_vma = NULL;
  1166. bool is_lru = !__folio_test_movable(src);
  1167. struct list_head *prev;
  1168. __migrate_folio_extract(dst, &old_page_state, &anon_vma);
  1169. prev = dst->lru.prev;
  1170. list_del(&dst->lru);
  1171. rc = move_to_new_folio(dst, src, mode);
  1172. if (rc)
  1173. goto out;
  1174. if (unlikely(!is_lru))
  1175. goto out_unlock_both;
  1176. /*
  1177. * When successful, push dst to LRU immediately: so that if it
  1178. * turns out to be an mlocked page, remove_migration_ptes() will
  1179. * automatically build up the correct dst->mlock_count for it.
  1180. *
  1181. * We would like to do something similar for the old page, when
  1182. * unsuccessful, and other cases when a page has been temporarily
  1183. * isolated from the unevictable LRU: but this case is the easiest.
  1184. */
  1185. folio_add_lru(dst);
  1186. if (old_page_state & PAGE_WAS_MLOCKED)
  1187. lru_add_drain();
  1188. if (old_page_state & PAGE_WAS_MAPPED)
  1189. remove_migration_ptes(src, dst, 0);
  1190. out_unlock_both:
  1191. folio_unlock(dst);
  1192. set_page_owner_migrate_reason(&dst->page, reason);
  1193. /*
  1194. * If migration is successful, decrease refcount of dst,
  1195. * which will not free the page because new page owner increased
  1196. * refcounter.
  1197. */
  1198. folio_put(dst);
  1199. /*
  1200. * A folio that has been migrated has all references removed
  1201. * and will be freed.
  1202. */
  1203. list_del(&src->lru);
  1204. /* Drop an anon_vma reference if we took one */
  1205. if (anon_vma)
  1206. put_anon_vma(anon_vma);
  1207. folio_unlock(src);
  1208. migrate_folio_done(src, reason);
  1209. return rc;
  1210. out:
  1211. /*
  1212. * A folio that has not been migrated will be restored to
  1213. * right list unless we want to retry.
  1214. */
  1215. if (rc == -EAGAIN) {
  1216. list_add(&dst->lru, prev);
  1217. __migrate_folio_record(dst, old_page_state, anon_vma);
  1218. return rc;
  1219. }
  1220. migrate_folio_undo_src(src, old_page_state & PAGE_WAS_MAPPED,
  1221. anon_vma, true, ret);
  1222. migrate_folio_undo_dst(dst, true, put_new_folio, private);
  1223. return rc;
  1224. }
  1225. /*
  1226. * Counterpart of unmap_and_move_page() for hugepage migration.
  1227. *
  1228. * This function doesn't wait the completion of hugepage I/O
  1229. * because there is no race between I/O and migration for hugepage.
  1230. * Note that currently hugepage I/O occurs only in direct I/O
  1231. * where no lock is held and PG_writeback is irrelevant,
  1232. * and writeback status of all subpages are counted in the reference
  1233. * count of the head page (i.e. if all subpages of a 2MB hugepage are
  1234. * under direct I/O, the reference of the head page is 512 and a bit more.)
  1235. * This means that when we try to migrate hugepage whose subpages are
  1236. * doing direct I/O, some references remain after try_to_unmap() and
  1237. * hugepage migration fails without data corruption.
  1238. *
  1239. * There is also no race when direct I/O is issued on the page under migration,
  1240. * because then pte is replaced with migration swap entry and direct I/O code
  1241. * will wait in the page fault for migration to complete.
  1242. */
  1243. static int unmap_and_move_huge_page(new_folio_t get_new_folio,
  1244. free_folio_t put_new_folio, unsigned long private,
  1245. struct folio *src, int force, enum migrate_mode mode,
  1246. int reason, struct list_head *ret)
  1247. {
  1248. struct folio *dst;
  1249. int rc = -EAGAIN;
  1250. int page_was_mapped = 0;
  1251. struct anon_vma *anon_vma = NULL;
  1252. struct address_space *mapping = NULL;
  1253. if (folio_ref_count(src) == 1) {
  1254. /* page was freed from under us. So we are done. */
  1255. folio_putback_active_hugetlb(src);
  1256. return MIGRATEPAGE_SUCCESS;
  1257. }
  1258. dst = get_new_folio(src, private);
  1259. if (!dst)
  1260. return -ENOMEM;
  1261. if (!folio_trylock(src)) {
  1262. if (!force)
  1263. goto out;
  1264. switch (mode) {
  1265. case MIGRATE_SYNC:
  1266. break;
  1267. default:
  1268. goto out;
  1269. }
  1270. folio_lock(src);
  1271. }
  1272. /*
  1273. * Check for pages which are in the process of being freed. Without
  1274. * folio_mapping() set, hugetlbfs specific move page routine will not
  1275. * be called and we could leak usage counts for subpools.
  1276. */
  1277. if (hugetlb_folio_subpool(src) && !folio_mapping(src)) {
  1278. rc = -EBUSY;
  1279. goto out_unlock;
  1280. }
  1281. if (folio_test_anon(src))
  1282. anon_vma = folio_get_anon_vma(src);
  1283. if (unlikely(!folio_trylock(dst)))
  1284. goto put_anon;
  1285. if (folio_mapped(src)) {
  1286. enum ttu_flags ttu = 0;
  1287. if (!folio_test_anon(src)) {
  1288. /*
  1289. * In shared mappings, try_to_unmap could potentially
  1290. * call huge_pmd_unshare. Because of this, take
  1291. * semaphore in write mode here and set TTU_RMAP_LOCKED
  1292. * to let lower levels know we have taken the lock.
  1293. */
  1294. mapping = hugetlb_folio_mapping_lock_write(src);
  1295. if (unlikely(!mapping))
  1296. goto unlock_put_anon;
  1297. ttu = TTU_RMAP_LOCKED;
  1298. }
  1299. try_to_migrate(src, ttu);
  1300. page_was_mapped = 1;
  1301. if (ttu & TTU_RMAP_LOCKED)
  1302. i_mmap_unlock_write(mapping);
  1303. }
  1304. if (!folio_mapped(src))
  1305. rc = move_to_new_folio(dst, src, mode);
  1306. if (page_was_mapped)
  1307. remove_migration_ptes(src,
  1308. rc == MIGRATEPAGE_SUCCESS ? dst : src, 0);
  1309. unlock_put_anon:
  1310. folio_unlock(dst);
  1311. put_anon:
  1312. if (anon_vma)
  1313. put_anon_vma(anon_vma);
  1314. if (rc == MIGRATEPAGE_SUCCESS) {
  1315. move_hugetlb_state(src, dst, reason);
  1316. put_new_folio = NULL;
  1317. }
  1318. out_unlock:
  1319. folio_unlock(src);
  1320. out:
  1321. if (rc == MIGRATEPAGE_SUCCESS)
  1322. folio_putback_active_hugetlb(src);
  1323. else if (rc != -EAGAIN)
  1324. list_move_tail(&src->lru, ret);
  1325. /*
  1326. * If migration was not successful and there's a freeing callback, use
  1327. * it. Otherwise, put_page() will drop the reference grabbed during
  1328. * isolation.
  1329. */
  1330. if (put_new_folio)
  1331. put_new_folio(dst, private);
  1332. else
  1333. folio_putback_active_hugetlb(dst);
  1334. return rc;
  1335. }
  1336. static inline int try_split_folio(struct folio *folio, struct list_head *split_folios,
  1337. enum migrate_mode mode)
  1338. {
  1339. int rc;
  1340. if (mode == MIGRATE_ASYNC) {
  1341. if (!folio_trylock(folio))
  1342. return -EAGAIN;
  1343. } else {
  1344. folio_lock(folio);
  1345. }
  1346. rc = split_folio_to_list(folio, split_folios);
  1347. folio_unlock(folio);
  1348. if (!rc)
  1349. list_move_tail(&folio->lru, split_folios);
  1350. return rc;
  1351. }
  1352. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1353. #define NR_MAX_BATCHED_MIGRATION HPAGE_PMD_NR
  1354. #else
  1355. #define NR_MAX_BATCHED_MIGRATION 512
  1356. #endif
  1357. #define NR_MAX_MIGRATE_PAGES_RETRY 10
  1358. #define NR_MAX_MIGRATE_ASYNC_RETRY 3
  1359. #define NR_MAX_MIGRATE_SYNC_RETRY \
  1360. (NR_MAX_MIGRATE_PAGES_RETRY - NR_MAX_MIGRATE_ASYNC_RETRY)
  1361. struct migrate_pages_stats {
  1362. int nr_succeeded; /* Normal and large folios migrated successfully, in
  1363. units of base pages */
  1364. int nr_failed_pages; /* Normal and large folios failed to be migrated, in
  1365. units of base pages. Untried folios aren't counted */
  1366. int nr_thp_succeeded; /* THP migrated successfully */
  1367. int nr_thp_failed; /* THP failed to be migrated */
  1368. int nr_thp_split; /* THP split before migrating */
  1369. int nr_split; /* Large folio (include THP) split before migrating */
  1370. };
  1371. /*
  1372. * Returns the number of hugetlb folios that were not migrated, or an error code
  1373. * after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no hugetlb folios are movable
  1374. * any more because the list has become empty or no retryable hugetlb folios
  1375. * exist any more. It is caller's responsibility to call putback_movable_pages()
  1376. * only if ret != 0.
  1377. */
  1378. static int migrate_hugetlbs(struct list_head *from, new_folio_t get_new_folio,
  1379. free_folio_t put_new_folio, unsigned long private,
  1380. enum migrate_mode mode, int reason,
  1381. struct migrate_pages_stats *stats,
  1382. struct list_head *ret_folios)
  1383. {
  1384. int retry = 1;
  1385. int nr_failed = 0;
  1386. int nr_retry_pages = 0;
  1387. int pass = 0;
  1388. struct folio *folio, *folio2;
  1389. int rc, nr_pages;
  1390. for (pass = 0; pass < NR_MAX_MIGRATE_PAGES_RETRY && retry; pass++) {
  1391. retry = 0;
  1392. nr_retry_pages = 0;
  1393. list_for_each_entry_safe(folio, folio2, from, lru) {
  1394. if (!folio_test_hugetlb(folio))
  1395. continue;
  1396. nr_pages = folio_nr_pages(folio);
  1397. cond_resched();
  1398. /*
  1399. * Migratability of hugepages depends on architectures and
  1400. * their size. This check is necessary because some callers
  1401. * of hugepage migration like soft offline and memory
  1402. * hotremove don't walk through page tables or check whether
  1403. * the hugepage is pmd-based or not before kicking migration.
  1404. */
  1405. if (!hugepage_migration_supported(folio_hstate(folio))) {
  1406. nr_failed++;
  1407. stats->nr_failed_pages += nr_pages;
  1408. list_move_tail(&folio->lru, ret_folios);
  1409. continue;
  1410. }
  1411. rc = unmap_and_move_huge_page(get_new_folio,
  1412. put_new_folio, private,
  1413. folio, pass > 2, mode,
  1414. reason, ret_folios);
  1415. /*
  1416. * The rules are:
  1417. * Success: hugetlb folio will be put back
  1418. * -EAGAIN: stay on the from list
  1419. * -ENOMEM: stay on the from list
  1420. * Other errno: put on ret_folios list
  1421. */
  1422. switch(rc) {
  1423. case -ENOMEM:
  1424. /*
  1425. * When memory is low, don't bother to try to migrate
  1426. * other folios, just exit.
  1427. */
  1428. stats->nr_failed_pages += nr_pages + nr_retry_pages;
  1429. return -ENOMEM;
  1430. case -EAGAIN:
  1431. retry++;
  1432. nr_retry_pages += nr_pages;
  1433. break;
  1434. case MIGRATEPAGE_SUCCESS:
  1435. stats->nr_succeeded += nr_pages;
  1436. break;
  1437. default:
  1438. /*
  1439. * Permanent failure (-EBUSY, etc.):
  1440. * unlike -EAGAIN case, the failed folio is
  1441. * removed from migration folio list and not
  1442. * retried in the next outer loop.
  1443. */
  1444. nr_failed++;
  1445. stats->nr_failed_pages += nr_pages;
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. /*
  1451. * nr_failed is number of hugetlb folios failed to be migrated. After
  1452. * NR_MAX_MIGRATE_PAGES_RETRY attempts, give up and count retried hugetlb
  1453. * folios as failed.
  1454. */
  1455. nr_failed += retry;
  1456. stats->nr_failed_pages += nr_retry_pages;
  1457. return nr_failed;
  1458. }
  1459. /*
  1460. * migrate_pages_batch() first unmaps folios in the from list as many as
  1461. * possible, then move the unmapped folios.
  1462. *
  1463. * We only batch migration if mode == MIGRATE_ASYNC to avoid to wait a
  1464. * lock or bit when we have locked more than one folio. Which may cause
  1465. * deadlock (e.g., for loop device). So, if mode != MIGRATE_ASYNC, the
  1466. * length of the from list must be <= 1.
  1467. */
  1468. static int migrate_pages_batch(struct list_head *from,
  1469. new_folio_t get_new_folio, free_folio_t put_new_folio,
  1470. unsigned long private, enum migrate_mode mode, int reason,
  1471. struct list_head *ret_folios, struct list_head *split_folios,
  1472. struct migrate_pages_stats *stats, int nr_pass)
  1473. {
  1474. int retry = 1;
  1475. int thp_retry = 1;
  1476. int nr_failed = 0;
  1477. int nr_retry_pages = 0;
  1478. int pass = 0;
  1479. bool is_thp = false;
  1480. bool is_large = false;
  1481. struct folio *folio, *folio2, *dst = NULL, *dst2;
  1482. int rc, rc_saved = 0, nr_pages;
  1483. LIST_HEAD(unmap_folios);
  1484. LIST_HEAD(dst_folios);
  1485. bool nosplit = (reason == MR_NUMA_MISPLACED);
  1486. VM_WARN_ON_ONCE(mode != MIGRATE_ASYNC &&
  1487. !list_empty(from) && !list_is_singular(from));
  1488. for (pass = 0; pass < nr_pass && retry; pass++) {
  1489. retry = 0;
  1490. thp_retry = 0;
  1491. nr_retry_pages = 0;
  1492. list_for_each_entry_safe(folio, folio2, from, lru) {
  1493. is_large = folio_test_large(folio);
  1494. is_thp = is_large && folio_test_pmd_mappable(folio);
  1495. nr_pages = folio_nr_pages(folio);
  1496. cond_resched();
  1497. /*
  1498. * The rare folio on the deferred split list should
  1499. * be split now. It should not count as a failure:
  1500. * but increment nr_failed because, without doing so,
  1501. * migrate_pages() may report success with (split but
  1502. * unmigrated) pages still on its fromlist; whereas it
  1503. * always reports success when its fromlist is empty.
  1504. * stats->nr_thp_failed should be increased too,
  1505. * otherwise stats inconsistency will happen when
  1506. * migrate_pages_batch is called via migrate_pages()
  1507. * with MIGRATE_SYNC and MIGRATE_ASYNC.
  1508. *
  1509. * Only check it without removing it from the list.
  1510. * Since the folio can be on deferred_split_scan()
  1511. * local list and removing it can cause the local list
  1512. * corruption. Folio split process below can handle it
  1513. * with the help of folio_ref_freeze().
  1514. *
  1515. * nr_pages > 2 is needed to avoid checking order-1
  1516. * page cache folios. They exist, in contrast to
  1517. * non-existent order-1 anonymous folios, and do not
  1518. * use _deferred_list.
  1519. */
  1520. if (nr_pages > 2 &&
  1521. !list_empty(&folio->_deferred_list) &&
  1522. folio_test_partially_mapped(folio)) {
  1523. if (!try_split_folio(folio, split_folios, mode)) {
  1524. nr_failed++;
  1525. stats->nr_thp_failed += is_thp;
  1526. stats->nr_thp_split += is_thp;
  1527. stats->nr_split++;
  1528. continue;
  1529. }
  1530. }
  1531. /*
  1532. * Large folio migration might be unsupported or
  1533. * the allocation might be failed so we should retry
  1534. * on the same folio with the large folio split
  1535. * to normal folios.
  1536. *
  1537. * Split folios are put in split_folios, and
  1538. * we will migrate them after the rest of the
  1539. * list is processed.
  1540. */
  1541. if (!thp_migration_supported() && is_thp) {
  1542. nr_failed++;
  1543. stats->nr_thp_failed++;
  1544. if (!try_split_folio(folio, split_folios, mode)) {
  1545. stats->nr_thp_split++;
  1546. stats->nr_split++;
  1547. continue;
  1548. }
  1549. stats->nr_failed_pages += nr_pages;
  1550. list_move_tail(&folio->lru, ret_folios);
  1551. continue;
  1552. }
  1553. rc = migrate_folio_unmap(get_new_folio, put_new_folio,
  1554. private, folio, &dst, mode, reason,
  1555. ret_folios);
  1556. /*
  1557. * The rules are:
  1558. * Success: folio will be freed
  1559. * Unmap: folio will be put on unmap_folios list,
  1560. * dst folio put on dst_folios list
  1561. * -EAGAIN: stay on the from list
  1562. * -ENOMEM: stay on the from list
  1563. * Other errno: put on ret_folios list
  1564. */
  1565. switch(rc) {
  1566. case -ENOMEM:
  1567. /*
  1568. * When memory is low, don't bother to try to migrate
  1569. * other folios, move unmapped folios, then exit.
  1570. */
  1571. nr_failed++;
  1572. stats->nr_thp_failed += is_thp;
  1573. /* Large folio NUMA faulting doesn't split to retry. */
  1574. if (is_large && !nosplit) {
  1575. int ret = try_split_folio(folio, split_folios, mode);
  1576. if (!ret) {
  1577. stats->nr_thp_split += is_thp;
  1578. stats->nr_split++;
  1579. break;
  1580. } else if (reason == MR_LONGTERM_PIN &&
  1581. ret == -EAGAIN) {
  1582. /*
  1583. * Try again to split large folio to
  1584. * mitigate the failure of longterm pinning.
  1585. */
  1586. retry++;
  1587. thp_retry += is_thp;
  1588. nr_retry_pages += nr_pages;
  1589. /* Undo duplicated failure counting. */
  1590. nr_failed--;
  1591. stats->nr_thp_failed -= is_thp;
  1592. break;
  1593. }
  1594. }
  1595. stats->nr_failed_pages += nr_pages + nr_retry_pages;
  1596. /* nr_failed isn't updated for not used */
  1597. stats->nr_thp_failed += thp_retry;
  1598. rc_saved = rc;
  1599. if (list_empty(&unmap_folios))
  1600. goto out;
  1601. else
  1602. goto move;
  1603. case -EAGAIN:
  1604. retry++;
  1605. thp_retry += is_thp;
  1606. nr_retry_pages += nr_pages;
  1607. break;
  1608. case MIGRATEPAGE_SUCCESS:
  1609. stats->nr_succeeded += nr_pages;
  1610. stats->nr_thp_succeeded += is_thp;
  1611. break;
  1612. case MIGRATEPAGE_UNMAP:
  1613. list_move_tail(&folio->lru, &unmap_folios);
  1614. list_add_tail(&dst->lru, &dst_folios);
  1615. break;
  1616. default:
  1617. /*
  1618. * Permanent failure (-EBUSY, etc.):
  1619. * unlike -EAGAIN case, the failed folio is
  1620. * removed from migration folio list and not
  1621. * retried in the next outer loop.
  1622. */
  1623. nr_failed++;
  1624. stats->nr_thp_failed += is_thp;
  1625. stats->nr_failed_pages += nr_pages;
  1626. break;
  1627. }
  1628. }
  1629. }
  1630. nr_failed += retry;
  1631. stats->nr_thp_failed += thp_retry;
  1632. stats->nr_failed_pages += nr_retry_pages;
  1633. move:
  1634. /* Flush TLBs for all unmapped folios */
  1635. try_to_unmap_flush();
  1636. retry = 1;
  1637. for (pass = 0; pass < nr_pass && retry; pass++) {
  1638. retry = 0;
  1639. thp_retry = 0;
  1640. nr_retry_pages = 0;
  1641. dst = list_first_entry(&dst_folios, struct folio, lru);
  1642. dst2 = list_next_entry(dst, lru);
  1643. list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
  1644. is_thp = folio_test_large(folio) && folio_test_pmd_mappable(folio);
  1645. nr_pages = folio_nr_pages(folio);
  1646. cond_resched();
  1647. rc = migrate_folio_move(put_new_folio, private,
  1648. folio, dst, mode,
  1649. reason, ret_folios);
  1650. /*
  1651. * The rules are:
  1652. * Success: folio will be freed
  1653. * -EAGAIN: stay on the unmap_folios list
  1654. * Other errno: put on ret_folios list
  1655. */
  1656. switch(rc) {
  1657. case -EAGAIN:
  1658. retry++;
  1659. thp_retry += is_thp;
  1660. nr_retry_pages += nr_pages;
  1661. break;
  1662. case MIGRATEPAGE_SUCCESS:
  1663. stats->nr_succeeded += nr_pages;
  1664. stats->nr_thp_succeeded += is_thp;
  1665. break;
  1666. default:
  1667. nr_failed++;
  1668. stats->nr_thp_failed += is_thp;
  1669. stats->nr_failed_pages += nr_pages;
  1670. break;
  1671. }
  1672. dst = dst2;
  1673. dst2 = list_next_entry(dst, lru);
  1674. }
  1675. }
  1676. nr_failed += retry;
  1677. stats->nr_thp_failed += thp_retry;
  1678. stats->nr_failed_pages += nr_retry_pages;
  1679. rc = rc_saved ? : nr_failed;
  1680. out:
  1681. /* Cleanup remaining folios */
  1682. dst = list_first_entry(&dst_folios, struct folio, lru);
  1683. dst2 = list_next_entry(dst, lru);
  1684. list_for_each_entry_safe(folio, folio2, &unmap_folios, lru) {
  1685. int old_page_state = 0;
  1686. struct anon_vma *anon_vma = NULL;
  1687. __migrate_folio_extract(dst, &old_page_state, &anon_vma);
  1688. migrate_folio_undo_src(folio, old_page_state & PAGE_WAS_MAPPED,
  1689. anon_vma, true, ret_folios);
  1690. list_del(&dst->lru);
  1691. migrate_folio_undo_dst(dst, true, put_new_folio, private);
  1692. dst = dst2;
  1693. dst2 = list_next_entry(dst, lru);
  1694. }
  1695. return rc;
  1696. }
  1697. static int migrate_pages_sync(struct list_head *from, new_folio_t get_new_folio,
  1698. free_folio_t put_new_folio, unsigned long private,
  1699. enum migrate_mode mode, int reason,
  1700. struct list_head *ret_folios, struct list_head *split_folios,
  1701. struct migrate_pages_stats *stats)
  1702. {
  1703. int rc, nr_failed = 0;
  1704. LIST_HEAD(folios);
  1705. struct migrate_pages_stats astats;
  1706. memset(&astats, 0, sizeof(astats));
  1707. /* Try to migrate in batch with MIGRATE_ASYNC mode firstly */
  1708. rc = migrate_pages_batch(from, get_new_folio, put_new_folio, private, MIGRATE_ASYNC,
  1709. reason, &folios, split_folios, &astats,
  1710. NR_MAX_MIGRATE_ASYNC_RETRY);
  1711. stats->nr_succeeded += astats.nr_succeeded;
  1712. stats->nr_thp_succeeded += astats.nr_thp_succeeded;
  1713. stats->nr_thp_split += astats.nr_thp_split;
  1714. stats->nr_split += astats.nr_split;
  1715. if (rc < 0) {
  1716. stats->nr_failed_pages += astats.nr_failed_pages;
  1717. stats->nr_thp_failed += astats.nr_thp_failed;
  1718. list_splice_tail(&folios, ret_folios);
  1719. return rc;
  1720. }
  1721. stats->nr_thp_failed += astats.nr_thp_split;
  1722. /*
  1723. * Do not count rc, as pages will be retried below.
  1724. * Count nr_split only, since it includes nr_thp_split.
  1725. */
  1726. nr_failed += astats.nr_split;
  1727. /*
  1728. * Fall back to migrate all failed folios one by one synchronously. All
  1729. * failed folios except split THPs will be retried, so their failure
  1730. * isn't counted
  1731. */
  1732. list_splice_tail_init(&folios, from);
  1733. while (!list_empty(from)) {
  1734. list_move(from->next, &folios);
  1735. rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
  1736. private, mode, reason, ret_folios,
  1737. split_folios, stats, NR_MAX_MIGRATE_SYNC_RETRY);
  1738. list_splice_tail_init(&folios, ret_folios);
  1739. if (rc < 0)
  1740. return rc;
  1741. nr_failed += rc;
  1742. }
  1743. return nr_failed;
  1744. }
  1745. /*
  1746. * migrate_pages - migrate the folios specified in a list, to the free folios
  1747. * supplied as the target for the page migration
  1748. *
  1749. * @from: The list of folios to be migrated.
  1750. * @get_new_folio: The function used to allocate free folios to be used
  1751. * as the target of the folio migration.
  1752. * @put_new_folio: The function used to free target folios if migration
  1753. * fails, or NULL if no special handling is necessary.
  1754. * @private: Private data to be passed on to get_new_folio()
  1755. * @mode: The migration mode that specifies the constraints for
  1756. * folio migration, if any.
  1757. * @reason: The reason for folio migration.
  1758. * @ret_succeeded: Set to the number of folios migrated successfully if
  1759. * the caller passes a non-NULL pointer.
  1760. *
  1761. * The function returns after NR_MAX_MIGRATE_PAGES_RETRY attempts or if no folios
  1762. * are movable any more because the list has become empty or no retryable folios
  1763. * exist any more. It is caller's responsibility to call putback_movable_pages()
  1764. * only if ret != 0.
  1765. *
  1766. * Returns the number of {normal folio, large folio, hugetlb} that were not
  1767. * migrated, or an error code. The number of large folio splits will be
  1768. * considered as the number of non-migrated large folio, no matter how many
  1769. * split folios of the large folio are migrated successfully.
  1770. */
  1771. int migrate_pages(struct list_head *from, new_folio_t get_new_folio,
  1772. free_folio_t put_new_folio, unsigned long private,
  1773. enum migrate_mode mode, int reason, unsigned int *ret_succeeded)
  1774. {
  1775. int rc, rc_gather;
  1776. int nr_pages;
  1777. struct folio *folio, *folio2;
  1778. LIST_HEAD(folios);
  1779. LIST_HEAD(ret_folios);
  1780. LIST_HEAD(split_folios);
  1781. struct migrate_pages_stats stats;
  1782. trace_mm_migrate_pages_start(mode, reason);
  1783. memset(&stats, 0, sizeof(stats));
  1784. rc_gather = migrate_hugetlbs(from, get_new_folio, put_new_folio, private,
  1785. mode, reason, &stats, &ret_folios);
  1786. if (rc_gather < 0)
  1787. goto out;
  1788. again:
  1789. nr_pages = 0;
  1790. list_for_each_entry_safe(folio, folio2, from, lru) {
  1791. /* Retried hugetlb folios will be kept in list */
  1792. if (folio_test_hugetlb(folio)) {
  1793. list_move_tail(&folio->lru, &ret_folios);
  1794. continue;
  1795. }
  1796. nr_pages += folio_nr_pages(folio);
  1797. if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
  1798. break;
  1799. }
  1800. if (nr_pages >= NR_MAX_BATCHED_MIGRATION)
  1801. list_cut_before(&folios, from, &folio2->lru);
  1802. else
  1803. list_splice_init(from, &folios);
  1804. if (mode == MIGRATE_ASYNC)
  1805. rc = migrate_pages_batch(&folios, get_new_folio, put_new_folio,
  1806. private, mode, reason, &ret_folios,
  1807. &split_folios, &stats,
  1808. NR_MAX_MIGRATE_PAGES_RETRY);
  1809. else
  1810. rc = migrate_pages_sync(&folios, get_new_folio, put_new_folio,
  1811. private, mode, reason, &ret_folios,
  1812. &split_folios, &stats);
  1813. list_splice_tail_init(&folios, &ret_folios);
  1814. if (rc < 0) {
  1815. rc_gather = rc;
  1816. list_splice_tail(&split_folios, &ret_folios);
  1817. goto out;
  1818. }
  1819. if (!list_empty(&split_folios)) {
  1820. /*
  1821. * Failure isn't counted since all split folios of a large folio
  1822. * is counted as 1 failure already. And, we only try to migrate
  1823. * with minimal effort, force MIGRATE_ASYNC mode and retry once.
  1824. */
  1825. migrate_pages_batch(&split_folios, get_new_folio,
  1826. put_new_folio, private, MIGRATE_ASYNC, reason,
  1827. &ret_folios, NULL, &stats, 1);
  1828. list_splice_tail_init(&split_folios, &ret_folios);
  1829. }
  1830. rc_gather += rc;
  1831. if (!list_empty(from))
  1832. goto again;
  1833. out:
  1834. /*
  1835. * Put the permanent failure folio back to migration list, they
  1836. * will be put back to the right list by the caller.
  1837. */
  1838. list_splice(&ret_folios, from);
  1839. /*
  1840. * Return 0 in case all split folios of fail-to-migrate large folios
  1841. * are migrated successfully.
  1842. */
  1843. if (list_empty(from))
  1844. rc_gather = 0;
  1845. count_vm_events(PGMIGRATE_SUCCESS, stats.nr_succeeded);
  1846. count_vm_events(PGMIGRATE_FAIL, stats.nr_failed_pages);
  1847. count_vm_events(THP_MIGRATION_SUCCESS, stats.nr_thp_succeeded);
  1848. count_vm_events(THP_MIGRATION_FAIL, stats.nr_thp_failed);
  1849. count_vm_events(THP_MIGRATION_SPLIT, stats.nr_thp_split);
  1850. trace_mm_migrate_pages(stats.nr_succeeded, stats.nr_failed_pages,
  1851. stats.nr_thp_succeeded, stats.nr_thp_failed,
  1852. stats.nr_thp_split, stats.nr_split, mode,
  1853. reason);
  1854. if (ret_succeeded)
  1855. *ret_succeeded = stats.nr_succeeded;
  1856. return rc_gather;
  1857. }
  1858. struct folio *alloc_migration_target(struct folio *src, unsigned long private)
  1859. {
  1860. struct migration_target_control *mtc;
  1861. gfp_t gfp_mask;
  1862. unsigned int order = 0;
  1863. int nid;
  1864. int zidx;
  1865. mtc = (struct migration_target_control *)private;
  1866. gfp_mask = mtc->gfp_mask;
  1867. nid = mtc->nid;
  1868. if (nid == NUMA_NO_NODE)
  1869. nid = folio_nid(src);
  1870. if (folio_test_hugetlb(src)) {
  1871. struct hstate *h = folio_hstate(src);
  1872. gfp_mask = htlb_modify_alloc_mask(h, gfp_mask);
  1873. return alloc_hugetlb_folio_nodemask(h, nid,
  1874. mtc->nmask, gfp_mask,
  1875. htlb_allow_alloc_fallback(mtc->reason));
  1876. }
  1877. if (folio_test_large(src)) {
  1878. /*
  1879. * clear __GFP_RECLAIM to make the migration callback
  1880. * consistent with regular THP allocations.
  1881. */
  1882. gfp_mask &= ~__GFP_RECLAIM;
  1883. gfp_mask |= GFP_TRANSHUGE;
  1884. order = folio_order(src);
  1885. }
  1886. zidx = zone_idx(folio_zone(src));
  1887. if (is_highmem_idx(zidx) || zidx == ZONE_MOVABLE)
  1888. gfp_mask |= __GFP_HIGHMEM;
  1889. return __folio_alloc(gfp_mask, order, nid, mtc->nmask);
  1890. }
  1891. #ifdef CONFIG_NUMA
  1892. static int store_status(int __user *status, int start, int value, int nr)
  1893. {
  1894. while (nr-- > 0) {
  1895. if (put_user(value, status + start))
  1896. return -EFAULT;
  1897. start++;
  1898. }
  1899. return 0;
  1900. }
  1901. static int do_move_pages_to_node(struct list_head *pagelist, int node)
  1902. {
  1903. int err;
  1904. struct migration_target_control mtc = {
  1905. .nid = node,
  1906. .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
  1907. .reason = MR_SYSCALL,
  1908. };
  1909. err = migrate_pages(pagelist, alloc_migration_target, NULL,
  1910. (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
  1911. if (err)
  1912. putback_movable_pages(pagelist);
  1913. return err;
  1914. }
  1915. static int __add_folio_for_migration(struct folio *folio, int node,
  1916. struct list_head *pagelist, bool migrate_all)
  1917. {
  1918. if (is_zero_folio(folio) || is_huge_zero_folio(folio))
  1919. return -EFAULT;
  1920. if (folio_is_zone_device(folio))
  1921. return -ENOENT;
  1922. if (folio_nid(folio) == node)
  1923. return 0;
  1924. if (folio_likely_mapped_shared(folio) && !migrate_all)
  1925. return -EACCES;
  1926. if (folio_test_hugetlb(folio)) {
  1927. if (isolate_hugetlb(folio, pagelist))
  1928. return 1;
  1929. } else if (folio_isolate_lru(folio)) {
  1930. list_add_tail(&folio->lru, pagelist);
  1931. node_stat_mod_folio(folio,
  1932. NR_ISOLATED_ANON + folio_is_file_lru(folio),
  1933. folio_nr_pages(folio));
  1934. return 1;
  1935. }
  1936. return -EBUSY;
  1937. }
  1938. /*
  1939. * Resolves the given address to a struct folio, isolates it from the LRU and
  1940. * puts it to the given pagelist.
  1941. * Returns:
  1942. * errno - if the folio cannot be found/isolated
  1943. * 0 - when it doesn't have to be migrated because it is already on the
  1944. * target node
  1945. * 1 - when it has been queued
  1946. */
  1947. static int add_folio_for_migration(struct mm_struct *mm, const void __user *p,
  1948. int node, struct list_head *pagelist, bool migrate_all)
  1949. {
  1950. struct vm_area_struct *vma;
  1951. struct folio_walk fw;
  1952. struct folio *folio;
  1953. unsigned long addr;
  1954. int err = -EFAULT;
  1955. mmap_read_lock(mm);
  1956. addr = (unsigned long)untagged_addr_remote(mm, p);
  1957. vma = vma_lookup(mm, addr);
  1958. if (vma && vma_migratable(vma)) {
  1959. folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
  1960. if (folio) {
  1961. err = __add_folio_for_migration(folio, node, pagelist,
  1962. migrate_all);
  1963. folio_walk_end(&fw, vma);
  1964. } else {
  1965. err = -ENOENT;
  1966. }
  1967. }
  1968. mmap_read_unlock(mm);
  1969. return err;
  1970. }
  1971. static int move_pages_and_store_status(int node,
  1972. struct list_head *pagelist, int __user *status,
  1973. int start, int i, unsigned long nr_pages)
  1974. {
  1975. int err;
  1976. if (list_empty(pagelist))
  1977. return 0;
  1978. err = do_move_pages_to_node(pagelist, node);
  1979. if (err) {
  1980. /*
  1981. * Positive err means the number of failed
  1982. * pages to migrate. Since we are going to
  1983. * abort and return the number of non-migrated
  1984. * pages, so need to include the rest of the
  1985. * nr_pages that have not been attempted as
  1986. * well.
  1987. */
  1988. if (err > 0)
  1989. err += nr_pages - i;
  1990. return err;
  1991. }
  1992. return store_status(status, start, node, i - start);
  1993. }
  1994. /*
  1995. * Migrate an array of page address onto an array of nodes and fill
  1996. * the corresponding array of status.
  1997. */
  1998. static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
  1999. unsigned long nr_pages,
  2000. const void __user * __user *pages,
  2001. const int __user *nodes,
  2002. int __user *status, int flags)
  2003. {
  2004. compat_uptr_t __user *compat_pages = (void __user *)pages;
  2005. int current_node = NUMA_NO_NODE;
  2006. LIST_HEAD(pagelist);
  2007. int start, i;
  2008. int err = 0, err1;
  2009. lru_cache_disable();
  2010. for (i = start = 0; i < nr_pages; i++) {
  2011. const void __user *p;
  2012. int node;
  2013. err = -EFAULT;
  2014. if (in_compat_syscall()) {
  2015. compat_uptr_t cp;
  2016. if (get_user(cp, compat_pages + i))
  2017. goto out_flush;
  2018. p = compat_ptr(cp);
  2019. } else {
  2020. if (get_user(p, pages + i))
  2021. goto out_flush;
  2022. }
  2023. if (get_user(node, nodes + i))
  2024. goto out_flush;
  2025. err = -ENODEV;
  2026. if (node < 0 || node >= MAX_NUMNODES)
  2027. goto out_flush;
  2028. if (!node_state(node, N_MEMORY))
  2029. goto out_flush;
  2030. err = -EACCES;
  2031. if (!node_isset(node, task_nodes))
  2032. goto out_flush;
  2033. if (current_node == NUMA_NO_NODE) {
  2034. current_node = node;
  2035. start = i;
  2036. } else if (node != current_node) {
  2037. err = move_pages_and_store_status(current_node,
  2038. &pagelist, status, start, i, nr_pages);
  2039. if (err)
  2040. goto out;
  2041. start = i;
  2042. current_node = node;
  2043. }
  2044. /*
  2045. * Errors in the page lookup or isolation are not fatal and we simply
  2046. * report them via status
  2047. */
  2048. err = add_folio_for_migration(mm, p, current_node, &pagelist,
  2049. flags & MPOL_MF_MOVE_ALL);
  2050. if (err > 0) {
  2051. /* The page is successfully queued for migration */
  2052. continue;
  2053. }
  2054. /*
  2055. * The move_pages() man page does not have an -EEXIST choice, so
  2056. * use -EFAULT instead.
  2057. */
  2058. if (err == -EEXIST)
  2059. err = -EFAULT;
  2060. /*
  2061. * If the page is already on the target node (!err), store the
  2062. * node, otherwise, store the err.
  2063. */
  2064. err = store_status(status, i, err ? : current_node, 1);
  2065. if (err)
  2066. goto out_flush;
  2067. err = move_pages_and_store_status(current_node, &pagelist,
  2068. status, start, i, nr_pages);
  2069. if (err) {
  2070. /* We have accounted for page i */
  2071. if (err > 0)
  2072. err--;
  2073. goto out;
  2074. }
  2075. current_node = NUMA_NO_NODE;
  2076. }
  2077. out_flush:
  2078. /* Make sure we do not overwrite the existing error */
  2079. err1 = move_pages_and_store_status(current_node, &pagelist,
  2080. status, start, i, nr_pages);
  2081. if (err >= 0)
  2082. err = err1;
  2083. out:
  2084. lru_cache_enable();
  2085. return err;
  2086. }
  2087. /*
  2088. * Determine the nodes of an array of pages and store it in an array of status.
  2089. */
  2090. static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
  2091. const void __user **pages, int *status)
  2092. {
  2093. unsigned long i;
  2094. mmap_read_lock(mm);
  2095. for (i = 0; i < nr_pages; i++) {
  2096. unsigned long addr = (unsigned long)(*pages);
  2097. struct vm_area_struct *vma;
  2098. struct folio_walk fw;
  2099. struct folio *folio;
  2100. int err = -EFAULT;
  2101. vma = vma_lookup(mm, addr);
  2102. if (!vma)
  2103. goto set_status;
  2104. folio = folio_walk_start(&fw, vma, addr, FW_ZEROPAGE);
  2105. if (folio) {
  2106. if (is_zero_folio(folio) || is_huge_zero_folio(folio))
  2107. err = -EFAULT;
  2108. else if (folio_is_zone_device(folio))
  2109. err = -ENOENT;
  2110. else
  2111. err = folio_nid(folio);
  2112. folio_walk_end(&fw, vma);
  2113. } else {
  2114. err = -ENOENT;
  2115. }
  2116. set_status:
  2117. *status = err;
  2118. pages++;
  2119. status++;
  2120. }
  2121. mmap_read_unlock(mm);
  2122. }
  2123. static int get_compat_pages_array(const void __user *chunk_pages[],
  2124. const void __user * __user *pages,
  2125. unsigned long chunk_nr)
  2126. {
  2127. compat_uptr_t __user *pages32 = (compat_uptr_t __user *)pages;
  2128. compat_uptr_t p;
  2129. int i;
  2130. for (i = 0; i < chunk_nr; i++) {
  2131. if (get_user(p, pages32 + i))
  2132. return -EFAULT;
  2133. chunk_pages[i] = compat_ptr(p);
  2134. }
  2135. return 0;
  2136. }
  2137. /*
  2138. * Determine the nodes of a user array of pages and store it in
  2139. * a user array of status.
  2140. */
  2141. static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
  2142. const void __user * __user *pages,
  2143. int __user *status)
  2144. {
  2145. #define DO_PAGES_STAT_CHUNK_NR 16UL
  2146. const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
  2147. int chunk_status[DO_PAGES_STAT_CHUNK_NR];
  2148. while (nr_pages) {
  2149. unsigned long chunk_nr = min(nr_pages, DO_PAGES_STAT_CHUNK_NR);
  2150. if (in_compat_syscall()) {
  2151. if (get_compat_pages_array(chunk_pages, pages,
  2152. chunk_nr))
  2153. break;
  2154. } else {
  2155. if (copy_from_user(chunk_pages, pages,
  2156. chunk_nr * sizeof(*chunk_pages)))
  2157. break;
  2158. }
  2159. do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
  2160. if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
  2161. break;
  2162. pages += chunk_nr;
  2163. status += chunk_nr;
  2164. nr_pages -= chunk_nr;
  2165. }
  2166. return nr_pages ? -EFAULT : 0;
  2167. }
  2168. static struct mm_struct *find_mm_struct(pid_t pid, nodemask_t *mem_nodes)
  2169. {
  2170. struct task_struct *task;
  2171. struct mm_struct *mm;
  2172. /*
  2173. * There is no need to check if current process has the right to modify
  2174. * the specified process when they are same.
  2175. */
  2176. if (!pid) {
  2177. mmget(current->mm);
  2178. *mem_nodes = cpuset_mems_allowed(current);
  2179. return current->mm;
  2180. }
  2181. task = find_get_task_by_vpid(pid);
  2182. if (!task) {
  2183. return ERR_PTR(-ESRCH);
  2184. }
  2185. /*
  2186. * Check if this process has the right to modify the specified
  2187. * process. Use the regular "ptrace_may_access()" checks.
  2188. */
  2189. if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
  2190. mm = ERR_PTR(-EPERM);
  2191. goto out;
  2192. }
  2193. mm = ERR_PTR(security_task_movememory(task));
  2194. if (IS_ERR(mm))
  2195. goto out;
  2196. *mem_nodes = cpuset_mems_allowed(task);
  2197. mm = get_task_mm(task);
  2198. out:
  2199. put_task_struct(task);
  2200. if (!mm)
  2201. mm = ERR_PTR(-EINVAL);
  2202. return mm;
  2203. }
  2204. /*
  2205. * Move a list of pages in the address space of the currently executing
  2206. * process.
  2207. */
  2208. static int kernel_move_pages(pid_t pid, unsigned long nr_pages,
  2209. const void __user * __user *pages,
  2210. const int __user *nodes,
  2211. int __user *status, int flags)
  2212. {
  2213. struct mm_struct *mm;
  2214. int err;
  2215. nodemask_t task_nodes;
  2216. /* Check flags */
  2217. if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
  2218. return -EINVAL;
  2219. if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
  2220. return -EPERM;
  2221. mm = find_mm_struct(pid, &task_nodes);
  2222. if (IS_ERR(mm))
  2223. return PTR_ERR(mm);
  2224. if (nodes)
  2225. err = do_pages_move(mm, task_nodes, nr_pages, pages,
  2226. nodes, status, flags);
  2227. else
  2228. err = do_pages_stat(mm, nr_pages, pages, status);
  2229. mmput(mm);
  2230. return err;
  2231. }
  2232. SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
  2233. const void __user * __user *, pages,
  2234. const int __user *, nodes,
  2235. int __user *, status, int, flags)
  2236. {
  2237. return kernel_move_pages(pid, nr_pages, pages, nodes, status, flags);
  2238. }
  2239. #ifdef CONFIG_NUMA_BALANCING
  2240. /*
  2241. * Returns true if this is a safe migration target node for misplaced NUMA
  2242. * pages. Currently it only checks the watermarks which is crude.
  2243. */
  2244. static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
  2245. unsigned long nr_migrate_pages)
  2246. {
  2247. int z;
  2248. for (z = pgdat->nr_zones - 1; z >= 0; z--) {
  2249. struct zone *zone = pgdat->node_zones + z;
  2250. if (!managed_zone(zone))
  2251. continue;
  2252. /* Avoid waking kswapd by allocating pages_to_migrate pages. */
  2253. if (!zone_watermark_ok(zone, 0,
  2254. high_wmark_pages(zone) +
  2255. nr_migrate_pages,
  2256. ZONE_MOVABLE, ALLOC_CMA))
  2257. continue;
  2258. return true;
  2259. }
  2260. return false;
  2261. }
  2262. static struct folio *alloc_misplaced_dst_folio(struct folio *src,
  2263. unsigned long data)
  2264. {
  2265. int nid = (int) data;
  2266. int order = folio_order(src);
  2267. gfp_t gfp = __GFP_THISNODE;
  2268. if (order > 0)
  2269. gfp |= GFP_TRANSHUGE_LIGHT;
  2270. else {
  2271. gfp |= GFP_HIGHUSER_MOVABLE | __GFP_NOMEMALLOC | __GFP_NORETRY |
  2272. __GFP_NOWARN;
  2273. gfp &= ~__GFP_RECLAIM;
  2274. }
  2275. return __folio_alloc_node(gfp, order, nid);
  2276. }
  2277. /*
  2278. * Prepare for calling migrate_misplaced_folio() by isolating the folio if
  2279. * permitted. Must be called with the PTL still held.
  2280. */
  2281. int migrate_misplaced_folio_prepare(struct folio *folio,
  2282. struct vm_area_struct *vma, int node)
  2283. {
  2284. int nr_pages = folio_nr_pages(folio);
  2285. pg_data_t *pgdat = NODE_DATA(node);
  2286. if (folio_is_file_lru(folio)) {
  2287. /*
  2288. * Do not migrate file folios that are mapped in multiple
  2289. * processes with execute permissions as they are probably
  2290. * shared libraries.
  2291. *
  2292. * See folio_likely_mapped_shared() on possible imprecision
  2293. * when we cannot easily detect if a folio is shared.
  2294. */
  2295. if ((vma->vm_flags & VM_EXEC) &&
  2296. folio_likely_mapped_shared(folio))
  2297. return -EACCES;
  2298. /*
  2299. * Do not migrate dirty folios as not all filesystems can move
  2300. * dirty folios in MIGRATE_ASYNC mode which is a waste of
  2301. * cycles.
  2302. */
  2303. if (folio_test_dirty(folio))
  2304. return -EAGAIN;
  2305. }
  2306. /* Avoid migrating to a node that is nearly full */
  2307. if (!migrate_balanced_pgdat(pgdat, nr_pages)) {
  2308. int z;
  2309. if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING))
  2310. return -EAGAIN;
  2311. for (z = pgdat->nr_zones - 1; z >= 0; z--) {
  2312. if (managed_zone(pgdat->node_zones + z))
  2313. break;
  2314. }
  2315. /*
  2316. * If there are no managed zones, it should not proceed
  2317. * further.
  2318. */
  2319. if (z < 0)
  2320. return -EAGAIN;
  2321. wakeup_kswapd(pgdat->node_zones + z, 0,
  2322. folio_order(folio), ZONE_MOVABLE);
  2323. return -EAGAIN;
  2324. }
  2325. if (!folio_isolate_lru(folio))
  2326. return -EAGAIN;
  2327. node_stat_mod_folio(folio, NR_ISOLATED_ANON + folio_is_file_lru(folio),
  2328. nr_pages);
  2329. return 0;
  2330. }
  2331. /*
  2332. * Attempt to migrate a misplaced folio to the specified destination
  2333. * node. Caller is expected to have isolated the folio by calling
  2334. * migrate_misplaced_folio_prepare(), which will result in an
  2335. * elevated reference count on the folio. This function will un-isolate the
  2336. * folio, dereferencing the folio before returning.
  2337. */
  2338. int migrate_misplaced_folio(struct folio *folio, struct vm_area_struct *vma,
  2339. int node)
  2340. {
  2341. pg_data_t *pgdat = NODE_DATA(node);
  2342. int nr_remaining;
  2343. unsigned int nr_succeeded;
  2344. LIST_HEAD(migratepages);
  2345. struct mem_cgroup *memcg = get_mem_cgroup_from_folio(folio);
  2346. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  2347. list_add(&folio->lru, &migratepages);
  2348. nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_folio,
  2349. NULL, node, MIGRATE_ASYNC,
  2350. MR_NUMA_MISPLACED, &nr_succeeded);
  2351. if (nr_remaining && !list_empty(&migratepages))
  2352. putback_movable_pages(&migratepages);
  2353. if (nr_succeeded) {
  2354. count_vm_numa_events(NUMA_PAGE_MIGRATE, nr_succeeded);
  2355. count_memcg_events(memcg, NUMA_PAGE_MIGRATE, nr_succeeded);
  2356. if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
  2357. && !node_is_toptier(folio_nid(folio))
  2358. && node_is_toptier(node))
  2359. mod_lruvec_state(lruvec, PGPROMOTE_SUCCESS, nr_succeeded);
  2360. }
  2361. mem_cgroup_put(memcg);
  2362. BUG_ON(!list_empty(&migratepages));
  2363. return nr_remaining ? -EAGAIN : 0;
  2364. }
  2365. #endif /* CONFIG_NUMA_BALANCING */
  2366. #endif /* CONFIG_NUMA */