migrate.c 73 KB

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