rmap.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * mm/rmap.c - physical to virtual reverse mappings
  4. *
  5. * Copyright 2001, Rik van Riel <riel@conectiva.com.br>
  6. *
  7. * Simple, low overhead reverse mapping scheme.
  8. * Please try to keep this thing as modular as possible.
  9. *
  10. * Provides methods for unmapping each kind of mapped page:
  11. * the anon methods track anonymous pages, and
  12. * the file methods track pages belonging to an inode.
  13. *
  14. * Original design by Rik van Riel <riel@conectiva.com.br> 2001
  15. * File methods by Dave McCracken <dmccr@us.ibm.com> 2003, 2004
  16. * Anonymous methods by Andrea Arcangeli <andrea@suse.de> 2004
  17. * Contributions by Hugh Dickins 2003, 2004
  18. */
  19. /*
  20. * Lock ordering in mm:
  21. *
  22. * inode->i_rwsem (while writing or truncating, not reading or faulting)
  23. * mm->mmap_lock
  24. * mapping->invalidate_lock (in filemap_fault)
  25. * folio_lock
  26. * hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share, see hugetlbfs below)
  27. * vma_start_write
  28. * mapping->i_mmap_rwsem
  29. * anon_vma->rwsem
  30. * mm->page_table_lock or pte_lock
  31. * swap_lock (in swap_duplicate, swap_info_get)
  32. * mmlist_lock (in mmput, drain_mmlist and others)
  33. * mapping->private_lock (in block_dirty_folio)
  34. * i_pages lock (widely used)
  35. * lruvec->lru_lock (in folio_lruvec_lock_irq)
  36. * inode->i_lock (in set_page_dirty's __mark_inode_dirty)
  37. * bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
  38. * sb_lock (within inode_lock in fs/fs-writeback.c)
  39. * i_pages lock (widely used, in set_page_dirty,
  40. * in arch-dependent flush_dcache_mmap_lock,
  41. * within bdi.wb->list_lock in __sync_single_inode)
  42. *
  43. * anon_vma->rwsem,mapping->i_mmap_rwsem (memory_failure, collect_procs_anon)
  44. * ->tasklist_lock
  45. * pte map lock
  46. *
  47. * hugetlbfs PageHuge() take locks in this order:
  48. * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
  49. * vma_lock (hugetlb specific lock for pmd_sharing)
  50. * mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
  51. * folio_lock
  52. */
  53. #include <linux/mm.h>
  54. #include <linux/sched/mm.h>
  55. #include <linux/sched/task.h>
  56. #include <linux/pagemap.h>
  57. #include <linux/swap.h>
  58. #include <linux/leafops.h>
  59. #include <linux/slab.h>
  60. #include <linux/init.h>
  61. #include <linux/ksm.h>
  62. #include <linux/rmap.h>
  63. #include <linux/rcupdate.h>
  64. #include <linux/export.h>
  65. #include <linux/memcontrol.h>
  66. #include <linux/mmu_notifier.h>
  67. #include <linux/migrate.h>
  68. #include <linux/hugetlb.h>
  69. #include <linux/huge_mm.h>
  70. #include <linux/backing-dev.h>
  71. #include <linux/page_idle.h>
  72. #include <linux/memremap.h>
  73. #include <linux/userfaultfd_k.h>
  74. #include <linux/mm_inline.h>
  75. #include <linux/oom.h>
  76. #include <asm/tlb.h>
  77. #define CREATE_TRACE_POINTS
  78. #include <trace/events/migrate.h>
  79. #include "internal.h"
  80. #include "swap.h"
  81. static struct kmem_cache *anon_vma_cachep;
  82. static struct kmem_cache *anon_vma_chain_cachep;
  83. static inline struct anon_vma *anon_vma_alloc(void)
  84. {
  85. struct anon_vma *anon_vma;
  86. anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
  87. if (anon_vma) {
  88. atomic_set(&anon_vma->refcount, 1);
  89. anon_vma->num_children = 0;
  90. anon_vma->num_active_vmas = 0;
  91. anon_vma->parent = anon_vma;
  92. /*
  93. * Initialise the anon_vma root to point to itself. If called
  94. * from fork, the root will be reset to the parents anon_vma.
  95. */
  96. anon_vma->root = anon_vma;
  97. }
  98. return anon_vma;
  99. }
  100. static inline void anon_vma_free(struct anon_vma *anon_vma)
  101. {
  102. VM_BUG_ON(atomic_read(&anon_vma->refcount));
  103. /*
  104. * Synchronize against folio_lock_anon_vma_read() such that
  105. * we can safely hold the lock without the anon_vma getting
  106. * freed.
  107. *
  108. * Relies on the full mb implied by the atomic_dec_and_test() from
  109. * put_anon_vma() against the acquire barrier implied by
  110. * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
  111. *
  112. * folio_lock_anon_vma_read() VS put_anon_vma()
  113. * down_read_trylock() atomic_dec_and_test()
  114. * LOCK MB
  115. * atomic_read() rwsem_is_locked()
  116. *
  117. * LOCK should suffice since the actual taking of the lock must
  118. * happen _before_ what follows.
  119. */
  120. might_sleep();
  121. if (rwsem_is_locked(&anon_vma->root->rwsem)) {
  122. anon_vma_lock_write(anon_vma);
  123. anon_vma_unlock_write(anon_vma);
  124. }
  125. kmem_cache_free(anon_vma_cachep, anon_vma);
  126. }
  127. static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
  128. {
  129. return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
  130. }
  131. static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
  132. {
  133. kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
  134. }
  135. static void anon_vma_chain_assign(struct vm_area_struct *vma,
  136. struct anon_vma_chain *avc,
  137. struct anon_vma *anon_vma)
  138. {
  139. avc->vma = vma;
  140. avc->anon_vma = anon_vma;
  141. list_add(&avc->same_vma, &vma->anon_vma_chain);
  142. }
  143. /**
  144. * __anon_vma_prepare - attach an anon_vma to a memory region
  145. * @vma: the memory region in question
  146. *
  147. * This makes sure the memory mapping described by 'vma' has
  148. * an 'anon_vma' attached to it, so that we can associate the
  149. * anonymous pages mapped into it with that anon_vma.
  150. *
  151. * The common case will be that we already have one, which
  152. * is handled inline by anon_vma_prepare(). But if
  153. * not we either need to find an adjacent mapping that we
  154. * can re-use the anon_vma from (very common when the only
  155. * reason for splitting a vma has been mprotect()), or we
  156. * allocate a new one.
  157. *
  158. * Anon-vma allocations are very subtle, because we may have
  159. * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
  160. * and that may actually touch the rwsem even in the newly
  161. * allocated vma (it depends on RCU to make sure that the
  162. * anon_vma isn't actually destroyed).
  163. *
  164. * As a result, we need to do proper anon_vma locking even
  165. * for the new allocation. At the same time, we do not want
  166. * to do any locking for the common case of already having
  167. * an anon_vma.
  168. */
  169. int __anon_vma_prepare(struct vm_area_struct *vma)
  170. {
  171. struct mm_struct *mm = vma->vm_mm;
  172. struct anon_vma *anon_vma, *allocated;
  173. struct anon_vma_chain *avc;
  174. mmap_assert_locked(mm);
  175. might_sleep();
  176. avc = anon_vma_chain_alloc(GFP_KERNEL);
  177. if (!avc)
  178. goto out_enomem;
  179. anon_vma = find_mergeable_anon_vma(vma);
  180. allocated = NULL;
  181. if (!anon_vma) {
  182. anon_vma = anon_vma_alloc();
  183. if (unlikely(!anon_vma))
  184. goto out_enomem_free_avc;
  185. anon_vma->num_children++; /* self-parent link for new root */
  186. allocated = anon_vma;
  187. }
  188. anon_vma_lock_write(anon_vma);
  189. /* page_table_lock to protect against threads */
  190. spin_lock(&mm->page_table_lock);
  191. if (likely(!vma->anon_vma)) {
  192. vma->anon_vma = anon_vma;
  193. anon_vma_chain_assign(vma, avc, anon_vma);
  194. anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
  195. anon_vma->num_active_vmas++;
  196. allocated = NULL;
  197. avc = NULL;
  198. }
  199. spin_unlock(&mm->page_table_lock);
  200. anon_vma_unlock_write(anon_vma);
  201. if (unlikely(allocated))
  202. put_anon_vma(allocated);
  203. if (unlikely(avc))
  204. anon_vma_chain_free(avc);
  205. return 0;
  206. out_enomem_free_avc:
  207. anon_vma_chain_free(avc);
  208. out_enomem:
  209. return -ENOMEM;
  210. }
  211. static void check_anon_vma_clone(struct vm_area_struct *dst,
  212. struct vm_area_struct *src,
  213. enum vma_operation operation)
  214. {
  215. /* The write lock must be held. */
  216. mmap_assert_write_locked(src->vm_mm);
  217. /* If not a fork then must be on same mm. */
  218. VM_WARN_ON_ONCE(operation != VMA_OP_FORK && dst->vm_mm != src->vm_mm);
  219. /* If we have anything to do src->anon_vma must be provided. */
  220. VM_WARN_ON_ONCE(!src->anon_vma && !list_empty(&src->anon_vma_chain));
  221. VM_WARN_ON_ONCE(!src->anon_vma && dst->anon_vma);
  222. /* We are establishing a new anon_vma_chain. */
  223. VM_WARN_ON_ONCE(!list_empty(&dst->anon_vma_chain));
  224. /*
  225. * On fork, dst->anon_vma is set NULL (temporarily). Otherwise, anon_vma
  226. * must be the same across dst and src.
  227. */
  228. VM_WARN_ON_ONCE(dst->anon_vma && dst->anon_vma != src->anon_vma);
  229. /*
  230. * Essentially equivalent to above - if not a no-op, we should expect
  231. * dst->anon_vma to be set for everything except a fork.
  232. */
  233. VM_WARN_ON_ONCE(operation != VMA_OP_FORK && src->anon_vma &&
  234. !dst->anon_vma);
  235. /* For the anon_vma to be compatible, it can only be singular. */
  236. VM_WARN_ON_ONCE(operation == VMA_OP_MERGE_UNFAULTED &&
  237. !list_is_singular(&src->anon_vma_chain));
  238. #ifdef CONFIG_PER_VMA_LOCK
  239. /* Only merging an unfaulted VMA leaves the destination attached. */
  240. VM_WARN_ON_ONCE(operation != VMA_OP_MERGE_UNFAULTED &&
  241. vma_is_attached(dst));
  242. #endif
  243. }
  244. static void maybe_reuse_anon_vma(struct vm_area_struct *dst,
  245. struct anon_vma *anon_vma)
  246. {
  247. /* If already populated, nothing to do.*/
  248. if (dst->anon_vma)
  249. return;
  250. /*
  251. * We reuse an anon_vma if any linking VMAs were unmapped and it has
  252. * only a single child at most.
  253. */
  254. if (anon_vma->num_active_vmas > 0)
  255. return;
  256. if (anon_vma->num_children > 1)
  257. return;
  258. dst->anon_vma = anon_vma;
  259. anon_vma->num_active_vmas++;
  260. }
  261. static void cleanup_partial_anon_vmas(struct vm_area_struct *vma);
  262. /**
  263. * anon_vma_clone - Establishes new anon_vma_chain objects in @dst linking to
  264. * all of the anon_vma objects contained within @src anon_vma_chain's.
  265. * @dst: The destination VMA with an empty anon_vma_chain.
  266. * @src: The source VMA we wish to duplicate.
  267. * @operation: The type of operation which resulted in the clone.
  268. *
  269. * This is the heart of the VMA side of the anon_vma implementation - we invoke
  270. * this function whenever we need to set up a new VMA's anon_vma state.
  271. *
  272. * This is invoked for:
  273. *
  274. * - VMA Merge, but only when @dst is unfaulted and @src is faulted - meaning we
  275. * clone @src into @dst.
  276. * - VMA split.
  277. * - VMA (m)remap.
  278. * - Fork of faulted VMA.
  279. *
  280. * In all cases other than fork this is simply a duplication. Fork additionally
  281. * adds a new active anon_vma.
  282. *
  283. * ONLY in the case of fork do we try to 'reuse' existing anon_vma's in an
  284. * anon_vma hierarchy, reusing anon_vma's which have no VMA associated with them
  285. * but do have a single child. This is to avoid waste of memory when repeatedly
  286. * forking.
  287. *
  288. * Returns: 0 on success, -ENOMEM on failure.
  289. */
  290. int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src,
  291. enum vma_operation operation)
  292. {
  293. struct anon_vma_chain *avc, *pavc;
  294. struct anon_vma *active_anon_vma = src->anon_vma;
  295. check_anon_vma_clone(dst, src, operation);
  296. if (!active_anon_vma)
  297. return 0;
  298. /*
  299. * Allocate AVCs. We don't need an anon_vma lock for this as we
  300. * are not updating the anon_vma rbtree nor are we changing
  301. * anon_vma statistics.
  302. *
  303. * Either src, dst have the same mm for which we hold an exclusive mmap
  304. * write lock, or we are forking and we hold it on src->vm_mm and dst is
  305. * not yet accessible to other threads so there's no possibliity of the
  306. * unlinked AVC's being observed yet.
  307. */
  308. list_for_each_entry(pavc, &src->anon_vma_chain, same_vma) {
  309. avc = anon_vma_chain_alloc(GFP_KERNEL);
  310. if (!avc)
  311. goto enomem_failure;
  312. anon_vma_chain_assign(dst, avc, pavc->anon_vma);
  313. }
  314. /*
  315. * Now link the anon_vma's back to the newly inserted AVCs.
  316. * Note that all anon_vma's share the same root.
  317. */
  318. anon_vma_lock_write(src->anon_vma);
  319. list_for_each_entry_reverse(avc, &dst->anon_vma_chain, same_vma) {
  320. struct anon_vma *anon_vma = avc->anon_vma;
  321. anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
  322. if (operation == VMA_OP_FORK)
  323. maybe_reuse_anon_vma(dst, anon_vma);
  324. }
  325. if (operation != VMA_OP_FORK)
  326. dst->anon_vma->num_active_vmas++;
  327. anon_vma_unlock_write(active_anon_vma);
  328. return 0;
  329. enomem_failure:
  330. cleanup_partial_anon_vmas(dst);
  331. return -ENOMEM;
  332. }
  333. /*
  334. * Attach vma to its own anon_vma, as well as to the anon_vmas that
  335. * the corresponding VMA in the parent process is attached to.
  336. * Returns 0 on success, non-zero on failure.
  337. */
  338. int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
  339. {
  340. struct anon_vma_chain *avc;
  341. struct anon_vma *anon_vma;
  342. int rc;
  343. /* Don't bother if the parent process has no anon_vma here. */
  344. if (!pvma->anon_vma)
  345. return 0;
  346. /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
  347. vma->anon_vma = NULL;
  348. anon_vma = anon_vma_alloc();
  349. if (!anon_vma)
  350. return -ENOMEM;
  351. avc = anon_vma_chain_alloc(GFP_KERNEL);
  352. if (!avc) {
  353. put_anon_vma(anon_vma);
  354. return -ENOMEM;
  355. }
  356. /*
  357. * First, attach the new VMA to the parent VMA's anon_vmas,
  358. * so rmap can find non-COWed pages in child processes.
  359. */
  360. rc = anon_vma_clone(vma, pvma, VMA_OP_FORK);
  361. /* An error arose or an existing anon_vma was reused, all done then. */
  362. if (rc || vma->anon_vma) {
  363. put_anon_vma(anon_vma);
  364. anon_vma_chain_free(avc);
  365. return rc;
  366. }
  367. /*
  368. * OK no reuse, so add our own anon_vma.
  369. *
  370. * Since it is not linked anywhere we can safely manipulate anon_vma
  371. * fields without a lock.
  372. */
  373. anon_vma->num_active_vmas = 1;
  374. /*
  375. * The root anon_vma's rwsem is the lock actually used when we
  376. * lock any of the anon_vmas in this anon_vma tree.
  377. */
  378. anon_vma->root = pvma->anon_vma->root;
  379. anon_vma->parent = pvma->anon_vma;
  380. /*
  381. * With refcounts, an anon_vma can stay around longer than the
  382. * process it belongs to. The root anon_vma needs to be pinned until
  383. * this anon_vma is freed, because the lock lives in the root.
  384. */
  385. get_anon_vma(anon_vma->root);
  386. /* Mark this anon_vma as the one where our new (COWed) pages go. */
  387. vma->anon_vma = anon_vma;
  388. anon_vma_chain_assign(vma, avc, anon_vma);
  389. /* Now let rmap see it. */
  390. anon_vma_lock_write(anon_vma);
  391. anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
  392. anon_vma->parent->num_children++;
  393. anon_vma_unlock_write(anon_vma);
  394. return 0;
  395. }
  396. /*
  397. * In the unfortunate case of anon_vma_clone() failing to allocate memory we
  398. * have to clean things up.
  399. *
  400. * Since we allocate anon_vma_chain's before we insert them into the interval
  401. * trees, we simply have to free up the AVC's and remove the entries from the
  402. * VMA's anon_vma_chain.
  403. */
  404. static void cleanup_partial_anon_vmas(struct vm_area_struct *vma)
  405. {
  406. struct anon_vma_chain *avc, *next;
  407. list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
  408. list_del(&avc->same_vma);
  409. anon_vma_chain_free(avc);
  410. }
  411. /*
  412. * The anon_vma assigned to this VMA is no longer valid, as we were not
  413. * able to correctly clone AVC state. Avoid inconsistent anon_vma tree
  414. * state by resetting.
  415. */
  416. vma->anon_vma = NULL;
  417. }
  418. /**
  419. * unlink_anon_vmas() - remove all links between a VMA and anon_vma's, freeing
  420. * anon_vma_chain objects.
  421. * @vma: The VMA whose links to anon_vma objects is to be severed.
  422. *
  423. * As part of the process anon_vma_chain's are freed,
  424. * anon_vma->num_children,num_active_vmas is updated as required and, if the
  425. * relevant anon_vma references no further VMAs, its reference count is
  426. * decremented.
  427. */
  428. void unlink_anon_vmas(struct vm_area_struct *vma)
  429. {
  430. struct anon_vma_chain *avc, *next;
  431. struct anon_vma *active_anon_vma = vma->anon_vma;
  432. /* Always hold mmap lock, read-lock on unmap possibly. */
  433. mmap_assert_locked(vma->vm_mm);
  434. /* Unfaulted is a no-op. */
  435. if (!active_anon_vma) {
  436. VM_WARN_ON_ONCE(!list_empty(&vma->anon_vma_chain));
  437. return;
  438. }
  439. anon_vma_lock_write(active_anon_vma);
  440. /*
  441. * Unlink each anon_vma chained to the VMA. This list is ordered
  442. * from newest to oldest, ensuring the root anon_vma gets freed last.
  443. */
  444. list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
  445. struct anon_vma *anon_vma = avc->anon_vma;
  446. anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
  447. /*
  448. * Leave empty anon_vmas on the list - we'll need
  449. * to free them outside the lock.
  450. */
  451. if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
  452. anon_vma->parent->num_children--;
  453. continue;
  454. }
  455. list_del(&avc->same_vma);
  456. anon_vma_chain_free(avc);
  457. }
  458. active_anon_vma->num_active_vmas--;
  459. /*
  460. * vma would still be needed after unlink, and anon_vma will be prepared
  461. * when handle fault.
  462. */
  463. vma->anon_vma = NULL;
  464. anon_vma_unlock_write(active_anon_vma);
  465. /*
  466. * Iterate the list once more, it now only contains empty and unlinked
  467. * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
  468. * needing to write-acquire the anon_vma->root->rwsem.
  469. */
  470. list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
  471. struct anon_vma *anon_vma = avc->anon_vma;
  472. VM_WARN_ON(anon_vma->num_children);
  473. VM_WARN_ON(anon_vma->num_active_vmas);
  474. put_anon_vma(anon_vma);
  475. list_del(&avc->same_vma);
  476. anon_vma_chain_free(avc);
  477. }
  478. }
  479. static void anon_vma_ctor(void *data)
  480. {
  481. struct anon_vma *anon_vma = data;
  482. init_rwsem(&anon_vma->rwsem);
  483. atomic_set(&anon_vma->refcount, 0);
  484. anon_vma->rb_root = RB_ROOT_CACHED;
  485. }
  486. void __init anon_vma_init(void)
  487. {
  488. anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
  489. 0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
  490. anon_vma_ctor);
  491. anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
  492. SLAB_PANIC|SLAB_ACCOUNT);
  493. }
  494. /*
  495. * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
  496. *
  497. * Since there is no serialization what so ever against folio_remove_rmap_*()
  498. * the best this function can do is return a refcount increased anon_vma
  499. * that might have been relevant to this page.
  500. *
  501. * The page might have been remapped to a different anon_vma or the anon_vma
  502. * returned may already be freed (and even reused).
  503. *
  504. * In case it was remapped to a different anon_vma, the new anon_vma will be a
  505. * child of the old anon_vma, and the anon_vma lifetime rules will therefore
  506. * ensure that any anon_vma obtained from the page will still be valid for as
  507. * long as we observe page_mapped() [ hence all those page_mapped() tests ].
  508. *
  509. * All users of this function must be very careful when walking the anon_vma
  510. * chain and verify that the page in question is indeed mapped in it
  511. * [ something equivalent to page_mapped_in_vma() ].
  512. *
  513. * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
  514. * folio_remove_rmap_*() that the anon_vma pointer from page->mapping is valid
  515. * if there is a mapcount, we can dereference the anon_vma after observing
  516. * those.
  517. *
  518. * NOTE: the caller should hold folio lock when calling this.
  519. */
  520. struct anon_vma *folio_get_anon_vma(const struct folio *folio)
  521. {
  522. struct anon_vma *anon_vma = NULL;
  523. unsigned long anon_mapping;
  524. VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
  525. rcu_read_lock();
  526. anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
  527. if ((anon_mapping & FOLIO_MAPPING_FLAGS) != FOLIO_MAPPING_ANON)
  528. goto out;
  529. if (!folio_mapped(folio))
  530. goto out;
  531. anon_vma = (struct anon_vma *) (anon_mapping - FOLIO_MAPPING_ANON);
  532. if (!atomic_inc_not_zero(&anon_vma->refcount)) {
  533. anon_vma = NULL;
  534. goto out;
  535. }
  536. /*
  537. * If this folio is still mapped, then its anon_vma cannot have been
  538. * freed. But if it has been unmapped, we have no security against the
  539. * anon_vma structure being freed and reused (for another anon_vma:
  540. * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
  541. * above cannot corrupt).
  542. */
  543. if (!folio_mapped(folio)) {
  544. rcu_read_unlock();
  545. put_anon_vma(anon_vma);
  546. return NULL;
  547. }
  548. out:
  549. rcu_read_unlock();
  550. return anon_vma;
  551. }
  552. /*
  553. * Similar to folio_get_anon_vma() except it locks the anon_vma.
  554. *
  555. * Its a little more complex as it tries to keep the fast path to a single
  556. * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
  557. * reference like with folio_get_anon_vma() and then block on the mutex
  558. * on !rwc->try_lock case.
  559. */
  560. struct anon_vma *folio_lock_anon_vma_read(const struct folio *folio,
  561. struct rmap_walk_control *rwc)
  562. {
  563. struct anon_vma *anon_vma = NULL;
  564. struct anon_vma *root_anon_vma;
  565. unsigned long anon_mapping;
  566. VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
  567. rcu_read_lock();
  568. anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
  569. if ((anon_mapping & FOLIO_MAPPING_FLAGS) != FOLIO_MAPPING_ANON)
  570. goto out;
  571. if (!folio_mapped(folio))
  572. goto out;
  573. anon_vma = (struct anon_vma *) (anon_mapping - FOLIO_MAPPING_ANON);
  574. root_anon_vma = READ_ONCE(anon_vma->root);
  575. if (down_read_trylock(&root_anon_vma->rwsem)) {
  576. /*
  577. * If the folio is still mapped, then this anon_vma is still
  578. * its anon_vma, and holding the mutex ensures that it will
  579. * not go away, see anon_vma_free().
  580. */
  581. if (!folio_mapped(folio)) {
  582. up_read(&root_anon_vma->rwsem);
  583. anon_vma = NULL;
  584. }
  585. goto out;
  586. }
  587. if (rwc && rwc->try_lock) {
  588. anon_vma = NULL;
  589. rwc->contended = true;
  590. goto out;
  591. }
  592. /* trylock failed, we got to sleep */
  593. if (!atomic_inc_not_zero(&anon_vma->refcount)) {
  594. anon_vma = NULL;
  595. goto out;
  596. }
  597. if (!folio_mapped(folio)) {
  598. rcu_read_unlock();
  599. put_anon_vma(anon_vma);
  600. return NULL;
  601. }
  602. /* we pinned the anon_vma, its safe to sleep */
  603. rcu_read_unlock();
  604. anon_vma_lock_read(anon_vma);
  605. if (atomic_dec_and_test(&anon_vma->refcount)) {
  606. /*
  607. * Oops, we held the last refcount, release the lock
  608. * and bail -- can't simply use put_anon_vma() because
  609. * we'll deadlock on the anon_vma_lock_write() recursion.
  610. */
  611. anon_vma_unlock_read(anon_vma);
  612. __put_anon_vma(anon_vma);
  613. anon_vma = NULL;
  614. }
  615. return anon_vma;
  616. out:
  617. rcu_read_unlock();
  618. return anon_vma;
  619. }
  620. #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
  621. /*
  622. * Flush TLB entries for recently unmapped pages from remote CPUs. It is
  623. * important if a PTE was dirty when it was unmapped that it's flushed
  624. * before any IO is initiated on the page to prevent lost writes. Similarly,
  625. * it must be flushed before freeing to prevent data leakage.
  626. */
  627. void try_to_unmap_flush(void)
  628. {
  629. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  630. if (!tlb_ubc->flush_required)
  631. return;
  632. arch_tlbbatch_flush(&tlb_ubc->arch);
  633. tlb_ubc->flush_required = false;
  634. tlb_ubc->writable = false;
  635. }
  636. /* Flush iff there are potentially writable TLB entries that can race with IO */
  637. void try_to_unmap_flush_dirty(void)
  638. {
  639. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  640. if (tlb_ubc->writable)
  641. try_to_unmap_flush();
  642. }
  643. /*
  644. * Bits 0-14 of mm->tlb_flush_batched record pending generations.
  645. * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
  646. */
  647. #define TLB_FLUSH_BATCH_FLUSHED_SHIFT 16
  648. #define TLB_FLUSH_BATCH_PENDING_MASK \
  649. ((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
  650. #define TLB_FLUSH_BATCH_PENDING_LARGE \
  651. (TLB_FLUSH_BATCH_PENDING_MASK / 2)
  652. static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
  653. unsigned long start, unsigned long end)
  654. {
  655. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  656. int batch;
  657. bool writable = pte_dirty(pteval);
  658. if (!pte_accessible(mm, pteval))
  659. return;
  660. arch_tlbbatch_add_pending(&tlb_ubc->arch, mm, start, end);
  661. tlb_ubc->flush_required = true;
  662. /*
  663. * Ensure compiler does not re-order the setting of tlb_flush_batched
  664. * before the PTE is cleared.
  665. */
  666. barrier();
  667. batch = atomic_read(&mm->tlb_flush_batched);
  668. retry:
  669. if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
  670. /*
  671. * Prevent `pending' from catching up with `flushed' because of
  672. * overflow. Reset `pending' and `flushed' to be 1 and 0 if
  673. * `pending' becomes large.
  674. */
  675. if (!atomic_try_cmpxchg(&mm->tlb_flush_batched, &batch, 1))
  676. goto retry;
  677. } else {
  678. atomic_inc(&mm->tlb_flush_batched);
  679. }
  680. /*
  681. * If the PTE was dirty then it's best to assume it's writable. The
  682. * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
  683. * before the page is queued for IO.
  684. */
  685. if (writable)
  686. tlb_ubc->writable = true;
  687. }
  688. /*
  689. * Returns true if the TLB flush should be deferred to the end of a batch of
  690. * unmap operations to reduce IPIs.
  691. */
  692. static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
  693. {
  694. if (!(flags & TTU_BATCH_FLUSH))
  695. return false;
  696. return arch_tlbbatch_should_defer(mm);
  697. }
  698. /*
  699. * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
  700. * releasing the PTL if TLB flushes are batched. It's possible for a parallel
  701. * operation such as mprotect or munmap to race between reclaim unmapping
  702. * the page and flushing the page. If this race occurs, it potentially allows
  703. * access to data via a stale TLB entry. Tracking all mm's that have TLB
  704. * batching in flight would be expensive during reclaim so instead track
  705. * whether TLB batching occurred in the past and if so then do a flush here
  706. * if required. This will cost one additional flush per reclaim cycle paid
  707. * by the first operation at risk such as mprotect and mumap.
  708. *
  709. * This must be called under the PTL so that an access to tlb_flush_batched
  710. * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
  711. * via the PTL.
  712. */
  713. void flush_tlb_batched_pending(struct mm_struct *mm)
  714. {
  715. int batch = atomic_read(&mm->tlb_flush_batched);
  716. int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
  717. int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
  718. if (pending != flushed) {
  719. flush_tlb_mm(mm);
  720. /*
  721. * If the new TLB flushing is pending during flushing, leave
  722. * mm->tlb_flush_batched as is, to avoid losing flushing.
  723. */
  724. atomic_cmpxchg(&mm->tlb_flush_batched, batch,
  725. pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
  726. }
  727. }
  728. #else
  729. static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
  730. unsigned long start, unsigned long end)
  731. {
  732. }
  733. static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
  734. {
  735. return false;
  736. }
  737. #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
  738. /**
  739. * page_address_in_vma - The virtual address of a page in this VMA.
  740. * @folio: The folio containing the page.
  741. * @page: The page within the folio.
  742. * @vma: The VMA we need to know the address in.
  743. *
  744. * Calculates the user virtual address of this page in the specified VMA.
  745. * It is the caller's responsibility to check the page is actually
  746. * within the VMA. There may not currently be a PTE pointing at this
  747. * page, but if a page fault occurs at this address, this is the page
  748. * which will be accessed.
  749. *
  750. * Context: Caller should hold a reference to the folio. Caller should
  751. * hold a lock (eg the i_mmap_lock or the mmap_lock) which keeps the
  752. * VMA from being altered.
  753. *
  754. * Return: The virtual address corresponding to this page in the VMA.
  755. */
  756. unsigned long page_address_in_vma(const struct folio *folio,
  757. const struct page *page, const struct vm_area_struct *vma)
  758. {
  759. if (folio_test_anon(folio)) {
  760. struct anon_vma *anon_vma = folio_anon_vma(folio);
  761. /*
  762. * Note: swapoff's unuse_vma() is more efficient with this
  763. * check, and needs it to match anon_vma when KSM is active.
  764. */
  765. if (!vma->anon_vma || !anon_vma ||
  766. vma->anon_vma->root != anon_vma->root)
  767. return -EFAULT;
  768. } else if (!vma->vm_file) {
  769. return -EFAULT;
  770. } else if (vma->vm_file->f_mapping != folio->mapping) {
  771. return -EFAULT;
  772. }
  773. /* KSM folios don't reach here because of the !anon_vma check */
  774. return vma_address(vma, page_pgoff(folio, page), 1);
  775. }
  776. /*
  777. * Returns the actual pmd_t* where we expect 'address' to be mapped from, or
  778. * NULL if it doesn't exist. No guarantees / checks on what the pmd_t*
  779. * represents.
  780. */
  781. pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
  782. {
  783. pgd_t *pgd;
  784. p4d_t *p4d;
  785. pud_t *pud;
  786. pmd_t *pmd = NULL;
  787. pgd = pgd_offset(mm, address);
  788. if (!pgd_present(*pgd))
  789. goto out;
  790. p4d = p4d_offset(pgd, address);
  791. if (!p4d_present(*p4d))
  792. goto out;
  793. pud = pud_offset(p4d, address);
  794. if (!pud_present(*pud))
  795. goto out;
  796. pmd = pmd_offset(pud, address);
  797. out:
  798. return pmd;
  799. }
  800. struct folio_referenced_arg {
  801. int mapcount;
  802. int referenced;
  803. vm_flags_t vm_flags;
  804. struct mem_cgroup *memcg;
  805. };
  806. /*
  807. * arg: folio_referenced_arg will be passed
  808. */
  809. static bool folio_referenced_one(struct folio *folio,
  810. struct vm_area_struct *vma, unsigned long address, void *arg)
  811. {
  812. struct folio_referenced_arg *pra = arg;
  813. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  814. int ptes = 0, referenced = 0;
  815. unsigned int nr;
  816. while (page_vma_mapped_walk(&pvmw)) {
  817. address = pvmw.address;
  818. nr = 1;
  819. if (vma->vm_flags & VM_LOCKED) {
  820. ptes++;
  821. pra->mapcount--;
  822. /* Only mlock fully mapped pages */
  823. if (pvmw.pte && ptes != pvmw.nr_pages)
  824. continue;
  825. /*
  826. * All PTEs must be protected by page table lock in
  827. * order to mlock the page.
  828. *
  829. * If page table boundary has been cross, current ptl
  830. * only protect part of ptes.
  831. */
  832. if (pvmw.flags & PVMW_PGTABLE_CROSSED)
  833. continue;
  834. /* Restore the mlock which got missed */
  835. mlock_vma_folio(folio, vma);
  836. page_vma_mapped_walk_done(&pvmw);
  837. pra->vm_flags |= VM_LOCKED;
  838. return false; /* To break the loop */
  839. }
  840. /*
  841. * Skip the non-shared swapbacked folio mapped solely by
  842. * the exiting or OOM-reaped process. This avoids redundant
  843. * swap-out followed by an immediate unmap.
  844. */
  845. if ((!atomic_read(&vma->vm_mm->mm_users) ||
  846. check_stable_address_space(vma->vm_mm)) &&
  847. folio_test_anon(folio) && folio_test_swapbacked(folio) &&
  848. !folio_maybe_mapped_shared(folio)) {
  849. pra->referenced = -1;
  850. page_vma_mapped_walk_done(&pvmw);
  851. return false;
  852. }
  853. if (lru_gen_enabled() && pvmw.pte) {
  854. if (lru_gen_look_around(&pvmw))
  855. referenced++;
  856. } else if (pvmw.pte) {
  857. if (folio_test_large(folio)) {
  858. unsigned long end_addr = pmd_addr_end(address, vma->vm_end);
  859. unsigned int max_nr = (end_addr - address) >> PAGE_SHIFT;
  860. pte_t pteval = ptep_get(pvmw.pte);
  861. nr = folio_pte_batch(folio, pvmw.pte,
  862. pteval, max_nr);
  863. }
  864. ptes += nr;
  865. if (clear_flush_young_ptes_notify(vma, address, pvmw.pte, nr))
  866. referenced++;
  867. /* Skip the batched PTEs */
  868. pvmw.pte += nr - 1;
  869. pvmw.address += (nr - 1) * PAGE_SIZE;
  870. } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
  871. if (pmdp_clear_flush_young_notify(vma, address,
  872. pvmw.pmd))
  873. referenced++;
  874. } else {
  875. /* unexpected pmd-mapped folio? */
  876. WARN_ON_ONCE(1);
  877. }
  878. pra->mapcount -= nr;
  879. /*
  880. * If we are sure that we batched the entire folio,
  881. * we can just optimize and stop right here.
  882. */
  883. if (ptes == pvmw.nr_pages) {
  884. page_vma_mapped_walk_done(&pvmw);
  885. break;
  886. }
  887. }
  888. if (referenced)
  889. folio_clear_idle(folio);
  890. if (folio_test_clear_young(folio))
  891. referenced++;
  892. if (referenced) {
  893. pra->referenced++;
  894. pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
  895. }
  896. if (!pra->mapcount)
  897. return false; /* To break the loop */
  898. return true;
  899. }
  900. static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
  901. {
  902. struct folio_referenced_arg *pra = arg;
  903. struct mem_cgroup *memcg = pra->memcg;
  904. /*
  905. * Ignore references from this mapping if it has no recency. If the
  906. * folio has been used in another mapping, we will catch it; if this
  907. * other mapping is already gone, the unmap path will have set the
  908. * referenced flag or activated the folio in zap_pte_range().
  909. */
  910. if (!vma_has_recency(vma))
  911. return true;
  912. /*
  913. * If we are reclaiming on behalf of a cgroup, skip counting on behalf
  914. * of references from different cgroups.
  915. */
  916. if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
  917. return true;
  918. return false;
  919. }
  920. /**
  921. * folio_referenced() - Test if the folio was referenced.
  922. * @folio: The folio to test.
  923. * @is_locked: Caller holds lock on the folio.
  924. * @memcg: target memory cgroup
  925. * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
  926. *
  927. * Quick test_and_clear_referenced for all mappings of a folio,
  928. *
  929. * Return: The number of mappings which referenced the folio. Return -1 if
  930. * the function bailed out due to rmap lock contention.
  931. */
  932. int folio_referenced(struct folio *folio, int is_locked,
  933. struct mem_cgroup *memcg, vm_flags_t *vm_flags)
  934. {
  935. bool we_locked = false;
  936. struct folio_referenced_arg pra = {
  937. .mapcount = folio_mapcount(folio),
  938. .memcg = memcg,
  939. };
  940. struct rmap_walk_control rwc = {
  941. .rmap_one = folio_referenced_one,
  942. .arg = (void *)&pra,
  943. .anon_lock = folio_lock_anon_vma_read,
  944. .try_lock = true,
  945. .invalid_vma = invalid_folio_referenced_vma,
  946. };
  947. *vm_flags = 0;
  948. if (!pra.mapcount)
  949. return 0;
  950. if (!folio_raw_mapping(folio))
  951. return 0;
  952. if (!is_locked) {
  953. we_locked = folio_trylock(folio);
  954. if (!we_locked)
  955. return 1;
  956. }
  957. rmap_walk(folio, &rwc);
  958. *vm_flags = pra.vm_flags;
  959. if (we_locked)
  960. folio_unlock(folio);
  961. return rwc.contended ? -1 : pra.referenced;
  962. }
  963. static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
  964. {
  965. int cleaned = 0;
  966. struct vm_area_struct *vma = pvmw->vma;
  967. struct mmu_notifier_range range;
  968. unsigned long address = pvmw->address;
  969. /*
  970. * We have to assume the worse case ie pmd for invalidation. Note that
  971. * the folio can not be freed from this function.
  972. */
  973. mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE, 0,
  974. vma->vm_mm, address, vma_address_end(pvmw));
  975. mmu_notifier_invalidate_range_start(&range);
  976. while (page_vma_mapped_walk(pvmw)) {
  977. int ret = 0;
  978. address = pvmw->address;
  979. if (pvmw->pte) {
  980. pte_t *pte = pvmw->pte;
  981. pte_t entry = ptep_get(pte);
  982. /*
  983. * PFN swap PTEs, such as device-exclusive ones, that
  984. * actually map pages are clean and not writable from a
  985. * CPU perspective. The MMU notifier takes care of any
  986. * device aspects.
  987. */
  988. if (!pte_present(entry))
  989. continue;
  990. if (!pte_dirty(entry) && !pte_write(entry))
  991. continue;
  992. flush_cache_page(vma, address, pte_pfn(entry));
  993. entry = ptep_clear_flush(vma, address, pte);
  994. entry = pte_wrprotect(entry);
  995. entry = pte_mkclean(entry);
  996. set_pte_at(vma->vm_mm, address, pte, entry);
  997. ret = 1;
  998. } else {
  999. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1000. pmd_t *pmd = pvmw->pmd;
  1001. pmd_t entry = pmdp_get(pmd);
  1002. /*
  1003. * Please see the comment above (!pte_present).
  1004. * A non present PMD is not writable from a CPU
  1005. * perspective.
  1006. */
  1007. if (!pmd_present(entry))
  1008. continue;
  1009. if (!pmd_dirty(entry) && !pmd_write(entry))
  1010. continue;
  1011. flush_cache_range(vma, address,
  1012. address + HPAGE_PMD_SIZE);
  1013. entry = pmdp_invalidate(vma, address, pmd);
  1014. entry = pmd_wrprotect(entry);
  1015. entry = pmd_mkclean(entry);
  1016. set_pmd_at(vma->vm_mm, address, pmd, entry);
  1017. ret = 1;
  1018. #else
  1019. /* unexpected pmd-mapped folio? */
  1020. WARN_ON_ONCE(1);
  1021. #endif
  1022. }
  1023. if (ret)
  1024. cleaned++;
  1025. }
  1026. mmu_notifier_invalidate_range_end(&range);
  1027. return cleaned;
  1028. }
  1029. static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
  1030. unsigned long address, void *arg)
  1031. {
  1032. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
  1033. int *cleaned = arg;
  1034. *cleaned += page_vma_mkclean_one(&pvmw);
  1035. return true;
  1036. }
  1037. static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
  1038. {
  1039. if (vma->vm_flags & VM_SHARED)
  1040. return false;
  1041. return true;
  1042. }
  1043. int folio_mkclean(struct folio *folio)
  1044. {
  1045. int cleaned = 0;
  1046. struct address_space *mapping;
  1047. struct rmap_walk_control rwc = {
  1048. .arg = (void *)&cleaned,
  1049. .rmap_one = page_mkclean_one,
  1050. .invalid_vma = invalid_mkclean_vma,
  1051. };
  1052. BUG_ON(!folio_test_locked(folio));
  1053. if (!folio_mapped(folio))
  1054. return 0;
  1055. mapping = folio_mapping(folio);
  1056. if (!mapping)
  1057. return 0;
  1058. rmap_walk(folio, &rwc);
  1059. return cleaned;
  1060. }
  1061. EXPORT_SYMBOL_GPL(folio_mkclean);
  1062. struct wrprotect_file_state {
  1063. int cleaned;
  1064. pgoff_t pgoff;
  1065. unsigned long pfn;
  1066. unsigned long nr_pages;
  1067. };
  1068. static bool mapping_wrprotect_range_one(struct folio *folio,
  1069. struct vm_area_struct *vma, unsigned long address, void *arg)
  1070. {
  1071. struct wrprotect_file_state *state = (struct wrprotect_file_state *)arg;
  1072. struct page_vma_mapped_walk pvmw = {
  1073. .pfn = state->pfn,
  1074. .nr_pages = state->nr_pages,
  1075. .pgoff = state->pgoff,
  1076. .vma = vma,
  1077. .address = address,
  1078. .flags = PVMW_SYNC,
  1079. };
  1080. state->cleaned += page_vma_mkclean_one(&pvmw);
  1081. return true;
  1082. }
  1083. static void __rmap_walk_file(struct folio *folio, struct address_space *mapping,
  1084. pgoff_t pgoff_start, unsigned long nr_pages,
  1085. struct rmap_walk_control *rwc, bool locked);
  1086. /**
  1087. * mapping_wrprotect_range() - Write-protect all mappings in a specified range.
  1088. *
  1089. * @mapping: The mapping whose reverse mapping should be traversed.
  1090. * @pgoff: The page offset at which @pfn is mapped within @mapping.
  1091. * @pfn: The PFN of the page mapped in @mapping at @pgoff.
  1092. * @nr_pages: The number of physically contiguous base pages spanned.
  1093. *
  1094. * Traverses the reverse mapping, finding all VMAs which contain a shared
  1095. * mapping of the pages in the specified range in @mapping, and write-protects
  1096. * them (that is, updates the page tables to mark the mappings read-only such
  1097. * that a write protection fault arises when the mappings are written to).
  1098. *
  1099. * The @pfn value need not refer to a folio, but rather can reference a kernel
  1100. * allocation which is mapped into userland. We therefore do not require that
  1101. * the page maps to a folio with a valid mapping or index field, rather the
  1102. * caller specifies these in @mapping and @pgoff.
  1103. *
  1104. * Return: the number of write-protected PTEs, or an error.
  1105. */
  1106. int mapping_wrprotect_range(struct address_space *mapping, pgoff_t pgoff,
  1107. unsigned long pfn, unsigned long nr_pages)
  1108. {
  1109. struct wrprotect_file_state state = {
  1110. .cleaned = 0,
  1111. .pgoff = pgoff,
  1112. .pfn = pfn,
  1113. .nr_pages = nr_pages,
  1114. };
  1115. struct rmap_walk_control rwc = {
  1116. .arg = (void *)&state,
  1117. .rmap_one = mapping_wrprotect_range_one,
  1118. .invalid_vma = invalid_mkclean_vma,
  1119. };
  1120. if (!mapping)
  1121. return 0;
  1122. __rmap_walk_file(/* folio = */NULL, mapping, pgoff, nr_pages, &rwc,
  1123. /* locked = */false);
  1124. return state.cleaned;
  1125. }
  1126. EXPORT_SYMBOL_GPL(mapping_wrprotect_range);
  1127. /**
  1128. * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
  1129. * [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
  1130. * within the @vma of shared mappings. And since clean PTEs
  1131. * should also be readonly, write protects them too.
  1132. * @pfn: start pfn.
  1133. * @nr_pages: number of physically contiguous pages srarting with @pfn.
  1134. * @pgoff: page offset that the @pfn mapped with.
  1135. * @vma: vma that @pfn mapped within.
  1136. *
  1137. * Returns the number of cleaned PTEs (including PMDs).
  1138. */
  1139. int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
  1140. struct vm_area_struct *vma)
  1141. {
  1142. struct page_vma_mapped_walk pvmw = {
  1143. .pfn = pfn,
  1144. .nr_pages = nr_pages,
  1145. .pgoff = pgoff,
  1146. .vma = vma,
  1147. .flags = PVMW_SYNC,
  1148. };
  1149. if (invalid_mkclean_vma(vma, NULL))
  1150. return 0;
  1151. pvmw.address = vma_address(vma, pgoff, nr_pages);
  1152. VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
  1153. return page_vma_mkclean_one(&pvmw);
  1154. }
  1155. static void __folio_mod_stat(struct folio *folio, int nr, int nr_pmdmapped)
  1156. {
  1157. int idx;
  1158. if (nr) {
  1159. idx = folio_test_anon(folio) ? NR_ANON_MAPPED : NR_FILE_MAPPED;
  1160. lruvec_stat_mod_folio(folio, idx, nr);
  1161. }
  1162. if (nr_pmdmapped) {
  1163. if (folio_test_anon(folio)) {
  1164. idx = NR_ANON_THPS;
  1165. lruvec_stat_mod_folio(folio, idx, nr_pmdmapped);
  1166. } else {
  1167. /* NR_*_PMDMAPPED are not maintained per-memcg */
  1168. idx = folio_test_swapbacked(folio) ?
  1169. NR_SHMEM_PMDMAPPED : NR_FILE_PMDMAPPED;
  1170. __mod_node_page_state(folio_pgdat(folio), idx,
  1171. nr_pmdmapped);
  1172. }
  1173. }
  1174. }
  1175. static __always_inline void __folio_add_rmap(struct folio *folio,
  1176. struct page *page, int nr_pages, struct vm_area_struct *vma,
  1177. enum pgtable_level level)
  1178. {
  1179. atomic_t *mapped = &folio->_nr_pages_mapped;
  1180. const int orig_nr_pages = nr_pages;
  1181. int first = 0, nr = 0, nr_pmdmapped = 0;
  1182. __folio_rmap_sanity_checks(folio, page, nr_pages, level);
  1183. switch (level) {
  1184. case PGTABLE_LEVEL_PTE:
  1185. if (!folio_test_large(folio)) {
  1186. nr = atomic_inc_and_test(&folio->_mapcount);
  1187. break;
  1188. }
  1189. if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
  1190. nr = folio_add_return_large_mapcount(folio, orig_nr_pages, vma);
  1191. if (nr == orig_nr_pages)
  1192. /* Was completely unmapped. */
  1193. nr = folio_large_nr_pages(folio);
  1194. else
  1195. nr = 0;
  1196. break;
  1197. }
  1198. do {
  1199. first += atomic_inc_and_test(&page->_mapcount);
  1200. } while (page++, --nr_pages > 0);
  1201. if (first &&
  1202. atomic_add_return_relaxed(first, mapped) < ENTIRELY_MAPPED)
  1203. nr = first;
  1204. folio_add_large_mapcount(folio, orig_nr_pages, vma);
  1205. break;
  1206. case PGTABLE_LEVEL_PMD:
  1207. case PGTABLE_LEVEL_PUD:
  1208. first = atomic_inc_and_test(&folio->_entire_mapcount);
  1209. if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
  1210. if (level == PGTABLE_LEVEL_PMD && first)
  1211. nr_pmdmapped = folio_large_nr_pages(folio);
  1212. nr = folio_inc_return_large_mapcount(folio, vma);
  1213. if (nr == 1)
  1214. /* Was completely unmapped. */
  1215. nr = folio_large_nr_pages(folio);
  1216. else
  1217. nr = 0;
  1218. break;
  1219. }
  1220. if (first) {
  1221. nr = atomic_add_return_relaxed(ENTIRELY_MAPPED, mapped);
  1222. if (likely(nr < ENTIRELY_MAPPED + ENTIRELY_MAPPED)) {
  1223. nr_pages = folio_large_nr_pages(folio);
  1224. /*
  1225. * We only track PMD mappings of PMD-sized
  1226. * folios separately.
  1227. */
  1228. if (level == PGTABLE_LEVEL_PMD)
  1229. nr_pmdmapped = nr_pages;
  1230. nr = nr_pages - (nr & FOLIO_PAGES_MAPPED);
  1231. /* Raced ahead of a remove and another add? */
  1232. if (unlikely(nr < 0))
  1233. nr = 0;
  1234. } else {
  1235. /* Raced ahead of a remove of ENTIRELY_MAPPED */
  1236. nr = 0;
  1237. }
  1238. }
  1239. folio_inc_large_mapcount(folio, vma);
  1240. break;
  1241. default:
  1242. BUILD_BUG();
  1243. }
  1244. __folio_mod_stat(folio, nr, nr_pmdmapped);
  1245. }
  1246. /**
  1247. * folio_move_anon_rmap - move a folio to our anon_vma
  1248. * @folio: The folio to move to our anon_vma
  1249. * @vma: The vma the folio belongs to
  1250. *
  1251. * When a folio belongs exclusively to one process after a COW event,
  1252. * that folio can be moved into the anon_vma that belongs to just that
  1253. * process, so the rmap code will not search the parent or sibling processes.
  1254. */
  1255. void folio_move_anon_rmap(struct folio *folio, struct vm_area_struct *vma)
  1256. {
  1257. void *anon_vma = vma->anon_vma;
  1258. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  1259. VM_BUG_ON_VMA(!anon_vma, vma);
  1260. anon_vma += FOLIO_MAPPING_ANON;
  1261. /*
  1262. * Ensure that anon_vma and the FOLIO_MAPPING_ANON bit are written
  1263. * simultaneously, so a concurrent reader (eg folio_referenced()'s
  1264. * folio_test_anon()) will not see one without the other.
  1265. */
  1266. WRITE_ONCE(folio->mapping, anon_vma);
  1267. }
  1268. /**
  1269. * __folio_set_anon - set up a new anonymous rmap for a folio
  1270. * @folio: The folio to set up the new anonymous rmap for.
  1271. * @vma: VM area to add the folio to.
  1272. * @address: User virtual address of the mapping
  1273. * @exclusive: Whether the folio is exclusive to the process.
  1274. */
  1275. static void __folio_set_anon(struct folio *folio, struct vm_area_struct *vma,
  1276. unsigned long address, bool exclusive)
  1277. {
  1278. struct anon_vma *anon_vma = vma->anon_vma;
  1279. BUG_ON(!anon_vma);
  1280. /*
  1281. * If the folio isn't exclusive to this vma, we must use the _oldest_
  1282. * possible anon_vma for the folio mapping!
  1283. */
  1284. if (!exclusive)
  1285. anon_vma = anon_vma->root;
  1286. /*
  1287. * page_idle does a lockless/optimistic rmap scan on folio->mapping.
  1288. * Make sure the compiler doesn't split the stores of anon_vma and
  1289. * the FOLIO_MAPPING_ANON type identifier, otherwise the rmap code
  1290. * could mistake the mapping for a struct address_space and crash.
  1291. */
  1292. anon_vma = (void *) anon_vma + FOLIO_MAPPING_ANON;
  1293. WRITE_ONCE(folio->mapping, (struct address_space *) anon_vma);
  1294. folio->index = linear_page_index(vma, address);
  1295. }
  1296. /**
  1297. * __page_check_anon_rmap - sanity check anonymous rmap addition
  1298. * @folio: The folio containing @page.
  1299. * @page: the page to check the mapping of
  1300. * @vma: the vm area in which the mapping is added
  1301. * @address: the user virtual address mapped
  1302. */
  1303. static void __page_check_anon_rmap(const struct folio *folio,
  1304. const struct page *page, struct vm_area_struct *vma,
  1305. unsigned long address)
  1306. {
  1307. /*
  1308. * The page's anon-rmap details (mapping and index) are guaranteed to
  1309. * be set up correctly at this point.
  1310. *
  1311. * We have exclusion against folio_add_anon_rmap_*() because the caller
  1312. * always holds the page locked.
  1313. *
  1314. * We have exclusion against folio_add_new_anon_rmap because those pages
  1315. * are initially only visible via the pagetables, and the pte is locked
  1316. * over the call to folio_add_new_anon_rmap.
  1317. */
  1318. VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
  1319. folio);
  1320. VM_BUG_ON_PAGE(page_pgoff(folio, page) != linear_page_index(vma, address),
  1321. page);
  1322. }
  1323. static __always_inline void __folio_add_anon_rmap(struct folio *folio,
  1324. struct page *page, int nr_pages, struct vm_area_struct *vma,
  1325. unsigned long address, rmap_t flags, enum pgtable_level level)
  1326. {
  1327. int i;
  1328. VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
  1329. __folio_add_rmap(folio, page, nr_pages, vma, level);
  1330. if (likely(!folio_test_ksm(folio)))
  1331. __page_check_anon_rmap(folio, page, vma, address);
  1332. if (flags & RMAP_EXCLUSIVE) {
  1333. switch (level) {
  1334. case PGTABLE_LEVEL_PTE:
  1335. for (i = 0; i < nr_pages; i++)
  1336. SetPageAnonExclusive(page + i);
  1337. break;
  1338. case PGTABLE_LEVEL_PMD:
  1339. SetPageAnonExclusive(page);
  1340. break;
  1341. case PGTABLE_LEVEL_PUD:
  1342. /*
  1343. * Keep the compiler happy, we don't support anonymous
  1344. * PUD mappings.
  1345. */
  1346. WARN_ON_ONCE(1);
  1347. break;
  1348. default:
  1349. BUILD_BUG();
  1350. }
  1351. }
  1352. VM_WARN_ON_FOLIO(!folio_test_large(folio) && PageAnonExclusive(page) &&
  1353. atomic_read(&folio->_mapcount) > 0, folio);
  1354. for (i = 0; i < nr_pages; i++) {
  1355. struct page *cur_page = page + i;
  1356. VM_WARN_ON_FOLIO(folio_test_large(folio) &&
  1357. folio_entire_mapcount(folio) > 1 &&
  1358. PageAnonExclusive(cur_page), folio);
  1359. if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT))
  1360. continue;
  1361. /*
  1362. * While PTE-mapping a THP we have a PMD and a PTE
  1363. * mapping.
  1364. */
  1365. VM_WARN_ON_FOLIO(atomic_read(&cur_page->_mapcount) > 0 &&
  1366. PageAnonExclusive(cur_page), folio);
  1367. }
  1368. /*
  1369. * Only mlock it if the folio is fully mapped to the VMA.
  1370. *
  1371. * Partially mapped folios can be split on reclaim and part outside
  1372. * of mlocked VMA can be evicted or freed.
  1373. */
  1374. if (folio_nr_pages(folio) == nr_pages)
  1375. mlock_vma_folio(folio, vma);
  1376. }
  1377. /**
  1378. * folio_add_anon_rmap_ptes - add PTE mappings to a page range of an anon folio
  1379. * @folio: The folio to add the mappings to
  1380. * @page: The first page to add
  1381. * @nr_pages: The number of pages which will be mapped
  1382. * @vma: The vm area in which the mappings are added
  1383. * @address: The user virtual address of the first page to map
  1384. * @flags: The rmap flags
  1385. *
  1386. * The page range of folio is defined by [first_page, first_page + nr_pages)
  1387. *
  1388. * The caller needs to hold the page table lock, and the page must be locked in
  1389. * the anon_vma case: to serialize mapping,index checking after setting,
  1390. * and to ensure that an anon folio is not being upgraded racily to a KSM folio
  1391. * (but KSM folios are never downgraded).
  1392. */
  1393. void folio_add_anon_rmap_ptes(struct folio *folio, struct page *page,
  1394. int nr_pages, struct vm_area_struct *vma, unsigned long address,
  1395. rmap_t flags)
  1396. {
  1397. __folio_add_anon_rmap(folio, page, nr_pages, vma, address, flags,
  1398. PGTABLE_LEVEL_PTE);
  1399. }
  1400. /**
  1401. * folio_add_anon_rmap_pmd - add a PMD mapping to a page range of an anon folio
  1402. * @folio: The folio to add the mapping to
  1403. * @page: The first page to add
  1404. * @vma: The vm area in which the mapping is added
  1405. * @address: The user virtual address of the first page to map
  1406. * @flags: The rmap flags
  1407. *
  1408. * The page range of folio is defined by [first_page, first_page + HPAGE_PMD_NR)
  1409. *
  1410. * The caller needs to hold the page table lock, and the page must be locked in
  1411. * the anon_vma case: to serialize mapping,index checking after setting.
  1412. */
  1413. void folio_add_anon_rmap_pmd(struct folio *folio, struct page *page,
  1414. struct vm_area_struct *vma, unsigned long address, rmap_t flags)
  1415. {
  1416. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1417. __folio_add_anon_rmap(folio, page, HPAGE_PMD_NR, vma, address, flags,
  1418. PGTABLE_LEVEL_PMD);
  1419. #else
  1420. WARN_ON_ONCE(true);
  1421. #endif
  1422. }
  1423. /**
  1424. * folio_add_new_anon_rmap - Add mapping to a new anonymous folio.
  1425. * @folio: The folio to add the mapping to.
  1426. * @vma: the vm area in which the mapping is added
  1427. * @address: the user virtual address mapped
  1428. * @flags: The rmap flags
  1429. *
  1430. * Like folio_add_anon_rmap_*() but must only be called on *new* folios.
  1431. * This means the inc-and-test can be bypassed.
  1432. * The folio doesn't necessarily need to be locked while it's exclusive
  1433. * unless two threads map it concurrently. However, the folio must be
  1434. * locked if it's shared.
  1435. *
  1436. * If the folio is pmd-mappable, it is accounted as a THP.
  1437. */
  1438. void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
  1439. unsigned long address, rmap_t flags)
  1440. {
  1441. const bool exclusive = flags & RMAP_EXCLUSIVE;
  1442. int nr = 1, nr_pmdmapped = 0;
  1443. VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
  1444. VM_WARN_ON_FOLIO(!exclusive && !folio_test_locked(folio), folio);
  1445. /*
  1446. * VM_DROPPABLE mappings don't swap; instead they're just dropped when
  1447. * under memory pressure.
  1448. */
  1449. if (!folio_test_swapbacked(folio) && !(vma->vm_flags & VM_DROPPABLE))
  1450. __folio_set_swapbacked(folio);
  1451. __folio_set_anon(folio, vma, address, exclusive);
  1452. if (likely(!folio_test_large(folio))) {
  1453. /* increment count (starts at -1) */
  1454. atomic_set(&folio->_mapcount, 0);
  1455. if (exclusive)
  1456. SetPageAnonExclusive(&folio->page);
  1457. } else if (!folio_test_pmd_mappable(folio)) {
  1458. int i;
  1459. nr = folio_large_nr_pages(folio);
  1460. for (i = 0; i < nr; i++) {
  1461. struct page *page = folio_page(folio, i);
  1462. if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
  1463. /* increment count (starts at -1) */
  1464. atomic_set(&page->_mapcount, 0);
  1465. if (exclusive)
  1466. SetPageAnonExclusive(page);
  1467. }
  1468. folio_set_large_mapcount(folio, nr, vma);
  1469. if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
  1470. atomic_set(&folio->_nr_pages_mapped, nr);
  1471. } else {
  1472. nr = folio_large_nr_pages(folio);
  1473. /* increment count (starts at -1) */
  1474. atomic_set(&folio->_entire_mapcount, 0);
  1475. folio_set_large_mapcount(folio, 1, vma);
  1476. if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
  1477. atomic_set(&folio->_nr_pages_mapped, ENTIRELY_MAPPED);
  1478. if (exclusive)
  1479. SetPageAnonExclusive(&folio->page);
  1480. nr_pmdmapped = nr;
  1481. }
  1482. VM_WARN_ON_ONCE(address < vma->vm_start ||
  1483. address + (nr << PAGE_SHIFT) > vma->vm_end);
  1484. __folio_mod_stat(folio, nr, nr_pmdmapped);
  1485. mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
  1486. }
  1487. static __always_inline void __folio_add_file_rmap(struct folio *folio,
  1488. struct page *page, int nr_pages, struct vm_area_struct *vma,
  1489. enum pgtable_level level)
  1490. {
  1491. VM_WARN_ON_FOLIO(folio_test_anon(folio), folio);
  1492. __folio_add_rmap(folio, page, nr_pages, vma, level);
  1493. /*
  1494. * Only mlock it if the folio is fully mapped to the VMA.
  1495. *
  1496. * Partially mapped folios can be split on reclaim and part outside
  1497. * of mlocked VMA can be evicted or freed.
  1498. */
  1499. if (folio_nr_pages(folio) == nr_pages)
  1500. mlock_vma_folio(folio, vma);
  1501. }
  1502. /**
  1503. * folio_add_file_rmap_ptes - add PTE mappings to a page range of a folio
  1504. * @folio: The folio to add the mappings to
  1505. * @page: The first page to add
  1506. * @nr_pages: The number of pages that will be mapped using PTEs
  1507. * @vma: The vm area in which the mappings are added
  1508. *
  1509. * The page range of the folio is defined by [page, page + nr_pages)
  1510. *
  1511. * The caller needs to hold the page table lock.
  1512. */
  1513. void folio_add_file_rmap_ptes(struct folio *folio, struct page *page,
  1514. int nr_pages, struct vm_area_struct *vma)
  1515. {
  1516. __folio_add_file_rmap(folio, page, nr_pages, vma, PGTABLE_LEVEL_PTE);
  1517. }
  1518. /**
  1519. * folio_add_file_rmap_pmd - add a PMD mapping to a page range of a folio
  1520. * @folio: The folio to add the mapping to
  1521. * @page: The first page to add
  1522. * @vma: The vm area in which the mapping is added
  1523. *
  1524. * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
  1525. *
  1526. * The caller needs to hold the page table lock.
  1527. */
  1528. void folio_add_file_rmap_pmd(struct folio *folio, struct page *page,
  1529. struct vm_area_struct *vma)
  1530. {
  1531. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1532. __folio_add_file_rmap(folio, page, HPAGE_PMD_NR, vma, PGTABLE_LEVEL_PMD);
  1533. #else
  1534. WARN_ON_ONCE(true);
  1535. #endif
  1536. }
  1537. /**
  1538. * folio_add_file_rmap_pud - add a PUD mapping to a page range of a folio
  1539. * @folio: The folio to add the mapping to
  1540. * @page: The first page to add
  1541. * @vma: The vm area in which the mapping is added
  1542. *
  1543. * The page range of the folio is defined by [page, page + HPAGE_PUD_NR)
  1544. *
  1545. * The caller needs to hold the page table lock.
  1546. */
  1547. void folio_add_file_rmap_pud(struct folio *folio, struct page *page,
  1548. struct vm_area_struct *vma)
  1549. {
  1550. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
  1551. defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
  1552. __folio_add_file_rmap(folio, page, HPAGE_PUD_NR, vma, PGTABLE_LEVEL_PUD);
  1553. #else
  1554. WARN_ON_ONCE(true);
  1555. #endif
  1556. }
  1557. static __always_inline void __folio_remove_rmap(struct folio *folio,
  1558. struct page *page, int nr_pages, struct vm_area_struct *vma,
  1559. enum pgtable_level level)
  1560. {
  1561. atomic_t *mapped = &folio->_nr_pages_mapped;
  1562. int last = 0, nr = 0, nr_pmdmapped = 0;
  1563. bool partially_mapped = false;
  1564. __folio_rmap_sanity_checks(folio, page, nr_pages, level);
  1565. switch (level) {
  1566. case PGTABLE_LEVEL_PTE:
  1567. if (!folio_test_large(folio)) {
  1568. nr = atomic_add_negative(-1, &folio->_mapcount);
  1569. break;
  1570. }
  1571. if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
  1572. nr = folio_sub_return_large_mapcount(folio, nr_pages, vma);
  1573. if (!nr) {
  1574. /* Now completely unmapped. */
  1575. nr = folio_large_nr_pages(folio);
  1576. } else {
  1577. partially_mapped = nr < folio_large_nr_pages(folio) &&
  1578. !folio_entire_mapcount(folio);
  1579. nr = 0;
  1580. }
  1581. break;
  1582. }
  1583. folio_sub_large_mapcount(folio, nr_pages, vma);
  1584. do {
  1585. last += atomic_add_negative(-1, &page->_mapcount);
  1586. } while (page++, --nr_pages > 0);
  1587. if (last &&
  1588. atomic_sub_return_relaxed(last, mapped) < ENTIRELY_MAPPED)
  1589. nr = last;
  1590. partially_mapped = nr && atomic_read(mapped);
  1591. break;
  1592. case PGTABLE_LEVEL_PMD:
  1593. case PGTABLE_LEVEL_PUD:
  1594. if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
  1595. last = atomic_add_negative(-1, &folio->_entire_mapcount);
  1596. if (level == PGTABLE_LEVEL_PMD && last)
  1597. nr_pmdmapped = folio_large_nr_pages(folio);
  1598. nr = folio_dec_return_large_mapcount(folio, vma);
  1599. if (!nr) {
  1600. /* Now completely unmapped. */
  1601. nr = folio_large_nr_pages(folio);
  1602. } else {
  1603. partially_mapped = last &&
  1604. nr < folio_large_nr_pages(folio);
  1605. nr = 0;
  1606. }
  1607. break;
  1608. }
  1609. folio_dec_large_mapcount(folio, vma);
  1610. last = atomic_add_negative(-1, &folio->_entire_mapcount);
  1611. if (last) {
  1612. nr = atomic_sub_return_relaxed(ENTIRELY_MAPPED, mapped);
  1613. if (likely(nr < ENTIRELY_MAPPED)) {
  1614. nr_pages = folio_large_nr_pages(folio);
  1615. if (level == PGTABLE_LEVEL_PMD)
  1616. nr_pmdmapped = nr_pages;
  1617. nr = nr_pages - nr;
  1618. /* Raced ahead of another remove and an add? */
  1619. if (unlikely(nr < 0))
  1620. nr = 0;
  1621. } else {
  1622. /* An add of ENTIRELY_MAPPED raced ahead */
  1623. nr = 0;
  1624. }
  1625. }
  1626. partially_mapped = nr && nr < nr_pmdmapped;
  1627. break;
  1628. default:
  1629. BUILD_BUG();
  1630. }
  1631. /*
  1632. * Queue anon large folio for deferred split if at least one page of
  1633. * the folio is unmapped and at least one page is still mapped.
  1634. *
  1635. * Check partially_mapped first to ensure it is a large folio.
  1636. *
  1637. * Device private folios do not support deferred splitting and
  1638. * shrinker based scanning of the folios to free.
  1639. */
  1640. if (partially_mapped && folio_test_anon(folio) &&
  1641. !folio_test_partially_mapped(folio) &&
  1642. !folio_is_device_private(folio))
  1643. deferred_split_folio(folio, true);
  1644. __folio_mod_stat(folio, -nr, -nr_pmdmapped);
  1645. /*
  1646. * It would be tidy to reset folio_test_anon mapping when fully
  1647. * unmapped, but that might overwrite a racing folio_add_anon_rmap_*()
  1648. * which increments mapcount after us but sets mapping before us:
  1649. * so leave the reset to free_pages_prepare, and remember that
  1650. * it's only reliable while mapped.
  1651. */
  1652. munlock_vma_folio(folio, vma);
  1653. }
  1654. /**
  1655. * folio_remove_rmap_ptes - remove PTE mappings from a page range of a folio
  1656. * @folio: The folio to remove the mappings from
  1657. * @page: The first page to remove
  1658. * @nr_pages: The number of pages that will be removed from the mapping
  1659. * @vma: The vm area from which the mappings are removed
  1660. *
  1661. * The page range of the folio is defined by [page, page + nr_pages)
  1662. *
  1663. * The caller needs to hold the page table lock.
  1664. */
  1665. void folio_remove_rmap_ptes(struct folio *folio, struct page *page,
  1666. int nr_pages, struct vm_area_struct *vma)
  1667. {
  1668. __folio_remove_rmap(folio, page, nr_pages, vma, PGTABLE_LEVEL_PTE);
  1669. }
  1670. /**
  1671. * folio_remove_rmap_pmd - remove a PMD mapping from a page range of a folio
  1672. * @folio: The folio to remove the mapping from
  1673. * @page: The first page to remove
  1674. * @vma: The vm area from which the mapping is removed
  1675. *
  1676. * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
  1677. *
  1678. * The caller needs to hold the page table lock.
  1679. */
  1680. void folio_remove_rmap_pmd(struct folio *folio, struct page *page,
  1681. struct vm_area_struct *vma)
  1682. {
  1683. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1684. __folio_remove_rmap(folio, page, HPAGE_PMD_NR, vma, PGTABLE_LEVEL_PMD);
  1685. #else
  1686. WARN_ON_ONCE(true);
  1687. #endif
  1688. }
  1689. /**
  1690. * folio_remove_rmap_pud - remove a PUD mapping from a page range of a folio
  1691. * @folio: The folio to remove the mapping from
  1692. * @page: The first page to remove
  1693. * @vma: The vm area from which the mapping is removed
  1694. *
  1695. * The page range of the folio is defined by [page, page + HPAGE_PUD_NR)
  1696. *
  1697. * The caller needs to hold the page table lock.
  1698. */
  1699. void folio_remove_rmap_pud(struct folio *folio, struct page *page,
  1700. struct vm_area_struct *vma)
  1701. {
  1702. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
  1703. defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
  1704. __folio_remove_rmap(folio, page, HPAGE_PUD_NR, vma, PGTABLE_LEVEL_PUD);
  1705. #else
  1706. WARN_ON_ONCE(true);
  1707. #endif
  1708. }
  1709. static inline unsigned int folio_unmap_pte_batch(struct folio *folio,
  1710. struct page_vma_mapped_walk *pvmw,
  1711. enum ttu_flags flags, pte_t pte)
  1712. {
  1713. unsigned long end_addr, addr = pvmw->address;
  1714. struct vm_area_struct *vma = pvmw->vma;
  1715. unsigned int max_nr;
  1716. if (flags & TTU_HWPOISON)
  1717. return 1;
  1718. if (!folio_test_large(folio))
  1719. return 1;
  1720. /* We may only batch within a single VMA and a single page table. */
  1721. end_addr = pmd_addr_end(addr, vma->vm_end);
  1722. max_nr = (end_addr - addr) >> PAGE_SHIFT;
  1723. /* We only support lazyfree or file folios batching for now ... */
  1724. if (folio_test_anon(folio) && folio_test_swapbacked(folio))
  1725. return 1;
  1726. if (pte_unused(pte))
  1727. return 1;
  1728. if (userfaultfd_wp(vma))
  1729. return 1;
  1730. /*
  1731. * If unmap fails, we need to restore the ptes. To avoid accidentally
  1732. * upgrading write permissions for ptes that were not originally
  1733. * writable, and to avoid losing the soft-dirty bit, use the
  1734. * appropriate FPB flags.
  1735. */
  1736. return folio_pte_batch_flags(folio, vma, pvmw->pte, &pte, max_nr,
  1737. FPB_RESPECT_WRITE | FPB_RESPECT_SOFT_DIRTY);
  1738. }
  1739. /*
  1740. * @arg: enum ttu_flags will be passed to this argument
  1741. */
  1742. static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
  1743. unsigned long address, void *arg)
  1744. {
  1745. struct mm_struct *mm = vma->vm_mm;
  1746. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  1747. bool anon_exclusive, ret = true;
  1748. pte_t pteval;
  1749. struct page *subpage;
  1750. struct mmu_notifier_range range;
  1751. enum ttu_flags flags = (enum ttu_flags)(long)arg;
  1752. unsigned long nr_pages = 1, end_addr;
  1753. unsigned long pfn;
  1754. unsigned long hsz = 0;
  1755. int ptes = 0;
  1756. /*
  1757. * When racing against e.g. zap_pte_range() on another cpu,
  1758. * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
  1759. * try_to_unmap() may return before page_mapped() has become false,
  1760. * if page table locking is skipped: use TTU_SYNC to wait for that.
  1761. */
  1762. if (flags & TTU_SYNC)
  1763. pvmw.flags = PVMW_SYNC;
  1764. /*
  1765. * For THP, we have to assume the worse case ie pmd for invalidation.
  1766. * For hugetlb, it could be much worse if we need to do pud
  1767. * invalidation in the case of pmd sharing.
  1768. *
  1769. * Note that the folio can not be freed in this function as call of
  1770. * try_to_unmap() must hold a reference on the folio.
  1771. */
  1772. range.end = vma_address_end(&pvmw);
  1773. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
  1774. address, range.end);
  1775. if (folio_test_hugetlb(folio)) {
  1776. /*
  1777. * If sharing is possible, start and end will be adjusted
  1778. * accordingly.
  1779. */
  1780. adjust_range_if_pmd_sharing_possible(vma, &range.start,
  1781. &range.end);
  1782. /* We need the huge page size for set_huge_pte_at() */
  1783. hsz = huge_page_size(hstate_vma(vma));
  1784. }
  1785. mmu_notifier_invalidate_range_start(&range);
  1786. while (page_vma_mapped_walk(&pvmw)) {
  1787. /*
  1788. * If the folio is in an mlock()d vma, we must not swap it out.
  1789. */
  1790. if (!(flags & TTU_IGNORE_MLOCK) &&
  1791. (vma->vm_flags & VM_LOCKED)) {
  1792. ptes++;
  1793. /*
  1794. * Set 'ret' to indicate the page cannot be unmapped.
  1795. *
  1796. * Do not jump to walk_abort immediately as additional
  1797. * iteration might be required to detect fully mapped
  1798. * folio an mlock it.
  1799. */
  1800. ret = false;
  1801. /* Only mlock fully mapped pages */
  1802. if (pvmw.pte && ptes != pvmw.nr_pages)
  1803. continue;
  1804. /*
  1805. * All PTEs must be protected by page table lock in
  1806. * order to mlock the page.
  1807. *
  1808. * If page table boundary has been cross, current ptl
  1809. * only protect part of ptes.
  1810. */
  1811. if (pvmw.flags & PVMW_PGTABLE_CROSSED)
  1812. goto walk_done;
  1813. /* Restore the mlock which got missed */
  1814. mlock_vma_folio(folio, vma);
  1815. goto walk_done;
  1816. }
  1817. if (!pvmw.pte) {
  1818. if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
  1819. if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
  1820. goto walk_done;
  1821. /*
  1822. * unmap_huge_pmd_locked has either already marked
  1823. * the folio as swap-backed or decided to retain it
  1824. * due to GUP or speculative references.
  1825. */
  1826. goto walk_abort;
  1827. }
  1828. if (flags & TTU_SPLIT_HUGE_PMD) {
  1829. /*
  1830. * We temporarily have to drop the PTL and
  1831. * restart so we can process the PTE-mapped THP.
  1832. */
  1833. split_huge_pmd_locked(vma, pvmw.address,
  1834. pvmw.pmd, false);
  1835. flags &= ~TTU_SPLIT_HUGE_PMD;
  1836. page_vma_mapped_walk_restart(&pvmw);
  1837. continue;
  1838. }
  1839. }
  1840. /* Unexpected PMD-mapped THP? */
  1841. VM_BUG_ON_FOLIO(!pvmw.pte, folio);
  1842. /*
  1843. * Handle PFN swap PTEs, such as device-exclusive ones, that
  1844. * actually map pages.
  1845. */
  1846. pteval = ptep_get(pvmw.pte);
  1847. if (likely(pte_present(pteval))) {
  1848. pfn = pte_pfn(pteval);
  1849. } else {
  1850. const softleaf_t entry = softleaf_from_pte(pteval);
  1851. pfn = softleaf_to_pfn(entry);
  1852. VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
  1853. }
  1854. subpage = folio_page(folio, pfn - folio_pfn(folio));
  1855. address = pvmw.address;
  1856. anon_exclusive = folio_test_anon(folio) &&
  1857. PageAnonExclusive(subpage);
  1858. if (folio_test_hugetlb(folio)) {
  1859. bool anon = folio_test_anon(folio);
  1860. /*
  1861. * The try_to_unmap() is only passed a hugetlb page
  1862. * in the case where the hugetlb page is poisoned.
  1863. */
  1864. VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
  1865. /*
  1866. * huge_pmd_unshare may unmap an entire PMD page.
  1867. * There is no way of knowing exactly which PMDs may
  1868. * be cached for this mm, so we must flush them all.
  1869. * start/end were already adjusted above to cover this
  1870. * range.
  1871. */
  1872. flush_cache_range(vma, range.start, range.end);
  1873. /*
  1874. * To call huge_pmd_unshare, i_mmap_rwsem must be
  1875. * held in write mode. Caller needs to explicitly
  1876. * do this outside rmap routines.
  1877. *
  1878. * We also must hold hugetlb vma_lock in write mode.
  1879. * Lock order dictates acquiring vma_lock BEFORE
  1880. * i_mmap_rwsem. We can only try lock here and fail
  1881. * if unsuccessful.
  1882. */
  1883. if (!anon) {
  1884. struct mmu_gather tlb;
  1885. VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
  1886. if (!hugetlb_vma_trylock_write(vma))
  1887. goto walk_abort;
  1888. tlb_gather_mmu_vma(&tlb, vma);
  1889. if (huge_pmd_unshare(&tlb, vma, address, pvmw.pte)) {
  1890. hugetlb_vma_unlock_write(vma);
  1891. huge_pmd_unshare_flush(&tlb, vma);
  1892. tlb_finish_mmu(&tlb);
  1893. /*
  1894. * The PMD table was unmapped,
  1895. * consequently unmapping the folio.
  1896. */
  1897. goto walk_done;
  1898. }
  1899. hugetlb_vma_unlock_write(vma);
  1900. tlb_finish_mmu(&tlb);
  1901. }
  1902. pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
  1903. if (pte_dirty(pteval))
  1904. folio_mark_dirty(folio);
  1905. } else if (likely(pte_present(pteval))) {
  1906. nr_pages = folio_unmap_pte_batch(folio, &pvmw, flags, pteval);
  1907. end_addr = address + nr_pages * PAGE_SIZE;
  1908. flush_cache_range(vma, address, end_addr);
  1909. /* Nuke the page table entry. */
  1910. pteval = get_and_clear_ptes(mm, address, pvmw.pte, nr_pages);
  1911. /*
  1912. * We clear the PTE but do not flush so potentially
  1913. * a remote CPU could still be writing to the folio.
  1914. * If the entry was previously clean then the
  1915. * architecture must guarantee that a clear->dirty
  1916. * transition on a cached TLB entry is written through
  1917. * and traps if the PTE is unmapped.
  1918. */
  1919. if (should_defer_flush(mm, flags))
  1920. set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
  1921. else
  1922. flush_tlb_range(vma, address, end_addr);
  1923. if (pte_dirty(pteval))
  1924. folio_mark_dirty(folio);
  1925. } else {
  1926. pte_clear(mm, address, pvmw.pte);
  1927. }
  1928. /*
  1929. * Now the pte is cleared. If this pte was uffd-wp armed,
  1930. * we may want to replace a none pte with a marker pte if
  1931. * it's file-backed, so we don't lose the tracking info.
  1932. */
  1933. pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
  1934. /* Update high watermark before we lower rss */
  1935. update_hiwater_rss(mm);
  1936. if (PageHWPoison(subpage) && (flags & TTU_HWPOISON)) {
  1937. pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
  1938. if (folio_test_hugetlb(folio)) {
  1939. hugetlb_count_sub(folio_nr_pages(folio), mm);
  1940. set_huge_pte_at(mm, address, pvmw.pte, pteval,
  1941. hsz);
  1942. } else {
  1943. dec_mm_counter(mm, mm_counter(folio));
  1944. set_pte_at(mm, address, pvmw.pte, pteval);
  1945. }
  1946. } else if (likely(pte_present(pteval)) && pte_unused(pteval) &&
  1947. !userfaultfd_armed(vma)) {
  1948. /*
  1949. * The guest indicated that the page content is of no
  1950. * interest anymore. Simply discard the pte, vmscan
  1951. * will take care of the rest.
  1952. * A future reference will then fault in a new zero
  1953. * page. When userfaultfd is active, we must not drop
  1954. * this page though, as its main user (postcopy
  1955. * migration) will not expect userfaults on already
  1956. * copied pages.
  1957. */
  1958. dec_mm_counter(mm, mm_counter(folio));
  1959. } else if (folio_test_anon(folio)) {
  1960. swp_entry_t entry = page_swap_entry(subpage);
  1961. pte_t swp_pte;
  1962. /*
  1963. * Store the swap location in the pte.
  1964. * See handle_pte_fault() ...
  1965. */
  1966. if (unlikely(folio_test_swapbacked(folio) !=
  1967. folio_test_swapcache(folio))) {
  1968. WARN_ON_ONCE(1);
  1969. goto walk_abort;
  1970. }
  1971. /* MADV_FREE page check */
  1972. if (!folio_test_swapbacked(folio)) {
  1973. int ref_count, map_count;
  1974. /*
  1975. * Synchronize with gup_pte_range():
  1976. * - clear PTE; barrier; read refcount
  1977. * - inc refcount; barrier; read PTE
  1978. */
  1979. smp_mb();
  1980. ref_count = folio_ref_count(folio);
  1981. map_count = folio_mapcount(folio);
  1982. /*
  1983. * Order reads for page refcount and dirty flag
  1984. * (see comments in __remove_mapping()).
  1985. */
  1986. smp_rmb();
  1987. if (folio_test_dirty(folio) && !(vma->vm_flags & VM_DROPPABLE)) {
  1988. /*
  1989. * redirtied either using the page table or a previously
  1990. * obtained GUP reference.
  1991. */
  1992. set_ptes(mm, address, pvmw.pte, pteval, nr_pages);
  1993. folio_set_swapbacked(folio);
  1994. goto walk_abort;
  1995. } else if (ref_count != 1 + map_count) {
  1996. /*
  1997. * Additional reference. Could be a GUP reference or any
  1998. * speculative reference. GUP users must mark the folio
  1999. * dirty if there was a modification. This folio cannot be
  2000. * reclaimed right now either way, so act just like nothing
  2001. * happened.
  2002. * We'll come back here later and detect if the folio was
  2003. * dirtied when the additional reference is gone.
  2004. */
  2005. set_ptes(mm, address, pvmw.pte, pteval, nr_pages);
  2006. goto walk_abort;
  2007. }
  2008. add_mm_counter(mm, MM_ANONPAGES, -nr_pages);
  2009. goto discard;
  2010. }
  2011. if (folio_dup_swap(folio, subpage) < 0) {
  2012. set_pte_at(mm, address, pvmw.pte, pteval);
  2013. goto walk_abort;
  2014. }
  2015. /*
  2016. * arch_unmap_one() is expected to be a NOP on
  2017. * architectures where we could have PFN swap PTEs,
  2018. * so we'll not check/care.
  2019. */
  2020. if (arch_unmap_one(mm, vma, address, pteval) < 0) {
  2021. folio_put_swap(folio, subpage);
  2022. set_pte_at(mm, address, pvmw.pte, pteval);
  2023. goto walk_abort;
  2024. }
  2025. /* See folio_try_share_anon_rmap(): clear PTE first. */
  2026. if (anon_exclusive &&
  2027. folio_try_share_anon_rmap_pte(folio, subpage)) {
  2028. folio_put_swap(folio, subpage);
  2029. set_pte_at(mm, address, pvmw.pte, pteval);
  2030. goto walk_abort;
  2031. }
  2032. if (list_empty(&mm->mmlist)) {
  2033. spin_lock(&mmlist_lock);
  2034. if (list_empty(&mm->mmlist))
  2035. list_add(&mm->mmlist, &init_mm.mmlist);
  2036. spin_unlock(&mmlist_lock);
  2037. }
  2038. dec_mm_counter(mm, MM_ANONPAGES);
  2039. inc_mm_counter(mm, MM_SWAPENTS);
  2040. swp_pte = swp_entry_to_pte(entry);
  2041. if (anon_exclusive)
  2042. swp_pte = pte_swp_mkexclusive(swp_pte);
  2043. if (likely(pte_present(pteval))) {
  2044. if (pte_soft_dirty(pteval))
  2045. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2046. if (pte_uffd_wp(pteval))
  2047. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  2048. } else {
  2049. if (pte_swp_soft_dirty(pteval))
  2050. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2051. if (pte_swp_uffd_wp(pteval))
  2052. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  2053. }
  2054. set_pte_at(mm, address, pvmw.pte, swp_pte);
  2055. } else {
  2056. /*
  2057. * This is a locked file-backed folio,
  2058. * so it cannot be removed from the page
  2059. * cache and replaced by a new folio before
  2060. * mmu_notifier_invalidate_range_end, so no
  2061. * concurrent thread might update its page table
  2062. * to point at a new folio while a device is
  2063. * still using this folio.
  2064. *
  2065. * See Documentation/mm/mmu_notifier.rst
  2066. */
  2067. add_mm_counter(mm, mm_counter_file(folio), -nr_pages);
  2068. }
  2069. discard:
  2070. if (unlikely(folio_test_hugetlb(folio))) {
  2071. hugetlb_remove_rmap(folio);
  2072. } else {
  2073. folio_remove_rmap_ptes(folio, subpage, nr_pages, vma);
  2074. }
  2075. if (vma->vm_flags & VM_LOCKED)
  2076. mlock_drain_local();
  2077. folio_put_refs(folio, nr_pages);
  2078. /*
  2079. * If we are sure that we batched the entire folio and cleared
  2080. * all PTEs, we can just optimize and stop right here.
  2081. */
  2082. if (nr_pages == folio_nr_pages(folio))
  2083. goto walk_done;
  2084. continue;
  2085. walk_abort:
  2086. ret = false;
  2087. walk_done:
  2088. page_vma_mapped_walk_done(&pvmw);
  2089. break;
  2090. }
  2091. mmu_notifier_invalidate_range_end(&range);
  2092. return ret;
  2093. }
  2094. static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
  2095. {
  2096. return vma_is_temporary_stack(vma);
  2097. }
  2098. static int folio_not_mapped(struct folio *folio)
  2099. {
  2100. return !folio_mapped(folio);
  2101. }
  2102. /**
  2103. * try_to_unmap - Try to remove all page table mappings to a folio.
  2104. * @folio: The folio to unmap.
  2105. * @flags: action and flags
  2106. *
  2107. * Tries to remove all the page table entries which are mapping this
  2108. * folio. It is the caller's responsibility to check if the folio is
  2109. * still mapped if needed (use TTU_SYNC to prevent accounting races).
  2110. *
  2111. * Context: Caller must hold the folio lock.
  2112. */
  2113. void try_to_unmap(struct folio *folio, enum ttu_flags flags)
  2114. {
  2115. struct rmap_walk_control rwc = {
  2116. .rmap_one = try_to_unmap_one,
  2117. .arg = (void *)flags,
  2118. .done = folio_not_mapped,
  2119. .anon_lock = folio_lock_anon_vma_read,
  2120. };
  2121. if (flags & TTU_RMAP_LOCKED)
  2122. rmap_walk_locked(folio, &rwc);
  2123. else
  2124. rmap_walk(folio, &rwc);
  2125. }
  2126. /*
  2127. * @arg: enum ttu_flags will be passed to this argument.
  2128. *
  2129. * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
  2130. * containing migration entries.
  2131. */
  2132. static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
  2133. unsigned long address, void *arg)
  2134. {
  2135. struct mm_struct *mm = vma->vm_mm;
  2136. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  2137. bool anon_exclusive, writable, ret = true;
  2138. pte_t pteval;
  2139. struct page *subpage;
  2140. struct mmu_notifier_range range;
  2141. enum ttu_flags flags = (enum ttu_flags)(long)arg;
  2142. unsigned long pfn;
  2143. unsigned long hsz = 0;
  2144. /*
  2145. * When racing against e.g. zap_pte_range() on another cpu,
  2146. * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
  2147. * try_to_migrate() may return before page_mapped() has become false,
  2148. * if page table locking is skipped: use TTU_SYNC to wait for that.
  2149. */
  2150. if (flags & TTU_SYNC)
  2151. pvmw.flags = PVMW_SYNC;
  2152. /*
  2153. * For THP, we have to assume the worse case ie pmd for invalidation.
  2154. * For hugetlb, it could be much worse if we need to do pud
  2155. * invalidation in the case of pmd sharing.
  2156. *
  2157. * Note that the page can not be free in this function as call of
  2158. * try_to_unmap() must hold a reference on the page.
  2159. */
  2160. range.end = vma_address_end(&pvmw);
  2161. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
  2162. address, range.end);
  2163. if (folio_test_hugetlb(folio)) {
  2164. /*
  2165. * If sharing is possible, start and end will be adjusted
  2166. * accordingly.
  2167. */
  2168. adjust_range_if_pmd_sharing_possible(vma, &range.start,
  2169. &range.end);
  2170. /* We need the huge page size for set_huge_pte_at() */
  2171. hsz = huge_page_size(hstate_vma(vma));
  2172. }
  2173. mmu_notifier_invalidate_range_start(&range);
  2174. while (page_vma_mapped_walk(&pvmw)) {
  2175. /* PMD-mapped THP migration entry */
  2176. if (!pvmw.pte) {
  2177. __maybe_unused unsigned long pfn;
  2178. __maybe_unused pmd_t pmdval;
  2179. if (flags & TTU_SPLIT_HUGE_PMD) {
  2180. /*
  2181. * split_huge_pmd_locked() might leave the
  2182. * folio mapped through PTEs. Retry the walk
  2183. * so we can detect this scenario and properly
  2184. * abort the walk.
  2185. */
  2186. split_huge_pmd_locked(vma, pvmw.address,
  2187. pvmw.pmd, true);
  2188. flags &= ~TTU_SPLIT_HUGE_PMD;
  2189. page_vma_mapped_walk_restart(&pvmw);
  2190. continue;
  2191. }
  2192. #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
  2193. pmdval = pmdp_get(pvmw.pmd);
  2194. if (likely(pmd_present(pmdval)))
  2195. pfn = pmd_pfn(pmdval);
  2196. else
  2197. pfn = softleaf_to_pfn(softleaf_from_pmd(pmdval));
  2198. subpage = folio_page(folio, pfn - folio_pfn(folio));
  2199. VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
  2200. !folio_test_pmd_mappable(folio), folio);
  2201. if (set_pmd_migration_entry(&pvmw, subpage)) {
  2202. ret = false;
  2203. page_vma_mapped_walk_done(&pvmw);
  2204. break;
  2205. }
  2206. continue;
  2207. #endif
  2208. }
  2209. /* Unexpected PMD-mapped THP? */
  2210. VM_BUG_ON_FOLIO(!pvmw.pte, folio);
  2211. /*
  2212. * Handle PFN swap PTEs, such as device-exclusive ones, that
  2213. * actually map pages.
  2214. */
  2215. pteval = ptep_get(pvmw.pte);
  2216. if (likely(pte_present(pteval))) {
  2217. pfn = pte_pfn(pteval);
  2218. } else {
  2219. const softleaf_t entry = softleaf_from_pte(pteval);
  2220. pfn = softleaf_to_pfn(entry);
  2221. VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
  2222. }
  2223. subpage = folio_page(folio, pfn - folio_pfn(folio));
  2224. address = pvmw.address;
  2225. anon_exclusive = folio_test_anon(folio) &&
  2226. PageAnonExclusive(subpage);
  2227. if (folio_test_hugetlb(folio)) {
  2228. bool anon = folio_test_anon(folio);
  2229. /*
  2230. * huge_pmd_unshare may unmap an entire PMD page.
  2231. * There is no way of knowing exactly which PMDs may
  2232. * be cached for this mm, so we must flush them all.
  2233. * start/end were already adjusted above to cover this
  2234. * range.
  2235. */
  2236. flush_cache_range(vma, range.start, range.end);
  2237. /*
  2238. * To call huge_pmd_unshare, i_mmap_rwsem must be
  2239. * held in write mode. Caller needs to explicitly
  2240. * do this outside rmap routines.
  2241. *
  2242. * We also must hold hugetlb vma_lock in write mode.
  2243. * Lock order dictates acquiring vma_lock BEFORE
  2244. * i_mmap_rwsem. We can only try lock here and
  2245. * fail if unsuccessful.
  2246. */
  2247. if (!anon) {
  2248. struct mmu_gather tlb;
  2249. VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
  2250. if (!hugetlb_vma_trylock_write(vma)) {
  2251. page_vma_mapped_walk_done(&pvmw);
  2252. ret = false;
  2253. break;
  2254. }
  2255. tlb_gather_mmu_vma(&tlb, vma);
  2256. if (huge_pmd_unshare(&tlb, vma, address, pvmw.pte)) {
  2257. hugetlb_vma_unlock_write(vma);
  2258. huge_pmd_unshare_flush(&tlb, vma);
  2259. tlb_finish_mmu(&tlb);
  2260. /*
  2261. * The PMD table was unmapped,
  2262. * consequently unmapping the folio.
  2263. */
  2264. page_vma_mapped_walk_done(&pvmw);
  2265. break;
  2266. }
  2267. hugetlb_vma_unlock_write(vma);
  2268. tlb_finish_mmu(&tlb);
  2269. }
  2270. /* Nuke the hugetlb page table entry */
  2271. pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
  2272. if (pte_dirty(pteval))
  2273. folio_mark_dirty(folio);
  2274. writable = pte_write(pteval);
  2275. } else if (likely(pte_present(pteval))) {
  2276. flush_cache_page(vma, address, pfn);
  2277. /* Nuke the page table entry. */
  2278. if (should_defer_flush(mm, flags)) {
  2279. /*
  2280. * We clear the PTE but do not flush so potentially
  2281. * a remote CPU could still be writing to the folio.
  2282. * If the entry was previously clean then the
  2283. * architecture must guarantee that a clear->dirty
  2284. * transition on a cached TLB entry is written through
  2285. * and traps if the PTE is unmapped.
  2286. */
  2287. pteval = ptep_get_and_clear(mm, address, pvmw.pte);
  2288. set_tlb_ubc_flush_pending(mm, pteval, address, address + PAGE_SIZE);
  2289. } else {
  2290. pteval = ptep_clear_flush(vma, address, pvmw.pte);
  2291. }
  2292. if (pte_dirty(pteval))
  2293. folio_mark_dirty(folio);
  2294. writable = pte_write(pteval);
  2295. } else {
  2296. const softleaf_t entry = softleaf_from_pte(pteval);
  2297. pte_clear(mm, address, pvmw.pte);
  2298. writable = softleaf_is_device_private_write(entry);
  2299. }
  2300. VM_WARN_ON_FOLIO(writable && folio_test_anon(folio) &&
  2301. !anon_exclusive, folio);
  2302. /* Update high watermark before we lower rss */
  2303. update_hiwater_rss(mm);
  2304. if (PageHWPoison(subpage)) {
  2305. VM_WARN_ON_FOLIO(folio_is_device_private(folio), folio);
  2306. pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
  2307. if (folio_test_hugetlb(folio)) {
  2308. hugetlb_count_sub(folio_nr_pages(folio), mm);
  2309. set_huge_pte_at(mm, address, pvmw.pte, pteval,
  2310. hsz);
  2311. } else {
  2312. dec_mm_counter(mm, mm_counter(folio));
  2313. set_pte_at(mm, address, pvmw.pte, pteval);
  2314. }
  2315. } else if (likely(pte_present(pteval)) && pte_unused(pteval) &&
  2316. !userfaultfd_armed(vma)) {
  2317. /*
  2318. * The guest indicated that the page content is of no
  2319. * interest anymore. Simply discard the pte, vmscan
  2320. * will take care of the rest.
  2321. * A future reference will then fault in a new zero
  2322. * page. When userfaultfd is active, we must not drop
  2323. * this page though, as its main user (postcopy
  2324. * migration) will not expect userfaults on already
  2325. * copied pages.
  2326. */
  2327. dec_mm_counter(mm, mm_counter(folio));
  2328. } else {
  2329. swp_entry_t entry;
  2330. pte_t swp_pte;
  2331. /*
  2332. * arch_unmap_one() is expected to be a NOP on
  2333. * architectures where we could have PFN swap PTEs,
  2334. * so we'll not check/care.
  2335. */
  2336. if (arch_unmap_one(mm, vma, address, pteval) < 0) {
  2337. if (folio_test_hugetlb(folio))
  2338. set_huge_pte_at(mm, address, pvmw.pte,
  2339. pteval, hsz);
  2340. else
  2341. set_pte_at(mm, address, pvmw.pte, pteval);
  2342. ret = false;
  2343. page_vma_mapped_walk_done(&pvmw);
  2344. break;
  2345. }
  2346. /* See folio_try_share_anon_rmap_pte(): clear PTE first. */
  2347. if (folio_test_hugetlb(folio)) {
  2348. if (anon_exclusive &&
  2349. hugetlb_try_share_anon_rmap(folio)) {
  2350. set_huge_pte_at(mm, address, pvmw.pte,
  2351. pteval, hsz);
  2352. ret = false;
  2353. page_vma_mapped_walk_done(&pvmw);
  2354. break;
  2355. }
  2356. } else if (anon_exclusive &&
  2357. folio_try_share_anon_rmap_pte(folio, subpage)) {
  2358. set_pte_at(mm, address, pvmw.pte, pteval);
  2359. ret = false;
  2360. page_vma_mapped_walk_done(&pvmw);
  2361. break;
  2362. }
  2363. /*
  2364. * Store the pfn of the page in a special migration
  2365. * pte. do_swap_page() will wait until the migration
  2366. * pte is removed and then restart fault handling.
  2367. */
  2368. if (writable)
  2369. entry = make_writable_migration_entry(
  2370. page_to_pfn(subpage));
  2371. else if (anon_exclusive)
  2372. entry = make_readable_exclusive_migration_entry(
  2373. page_to_pfn(subpage));
  2374. else
  2375. entry = make_readable_migration_entry(
  2376. page_to_pfn(subpage));
  2377. if (likely(pte_present(pteval))) {
  2378. if (pte_young(pteval))
  2379. entry = make_migration_entry_young(entry);
  2380. if (pte_dirty(pteval))
  2381. entry = make_migration_entry_dirty(entry);
  2382. swp_pte = swp_entry_to_pte(entry);
  2383. if (pte_soft_dirty(pteval))
  2384. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2385. if (pte_uffd_wp(pteval))
  2386. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  2387. } else {
  2388. swp_pte = swp_entry_to_pte(entry);
  2389. if (pte_swp_soft_dirty(pteval))
  2390. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2391. if (pte_swp_uffd_wp(pteval))
  2392. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  2393. }
  2394. if (folio_test_hugetlb(folio))
  2395. set_huge_pte_at(mm, address, pvmw.pte, swp_pte,
  2396. hsz);
  2397. else
  2398. set_pte_at(mm, address, pvmw.pte, swp_pte);
  2399. trace_set_migration_pte(address, pte_val(swp_pte),
  2400. folio_order(folio));
  2401. /*
  2402. * No need to invalidate here it will synchronize on
  2403. * against the special swap migration pte.
  2404. */
  2405. }
  2406. if (unlikely(folio_test_hugetlb(folio)))
  2407. hugetlb_remove_rmap(folio);
  2408. else
  2409. folio_remove_rmap_pte(folio, subpage, vma);
  2410. if (vma->vm_flags & VM_LOCKED)
  2411. mlock_drain_local();
  2412. folio_put(folio);
  2413. }
  2414. mmu_notifier_invalidate_range_end(&range);
  2415. return ret;
  2416. }
  2417. /**
  2418. * try_to_migrate - try to replace all page table mappings with swap entries
  2419. * @folio: the folio to replace page table entries for
  2420. * @flags: action and flags
  2421. *
  2422. * Tries to remove all the page table entries which are mapping this folio and
  2423. * replace them with special swap entries. Caller must hold the folio lock.
  2424. */
  2425. void try_to_migrate(struct folio *folio, enum ttu_flags flags)
  2426. {
  2427. struct rmap_walk_control rwc = {
  2428. .rmap_one = try_to_migrate_one,
  2429. .arg = (void *)flags,
  2430. .done = folio_not_mapped,
  2431. .anon_lock = folio_lock_anon_vma_read,
  2432. };
  2433. /*
  2434. * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
  2435. * TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags.
  2436. */
  2437. if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
  2438. TTU_SYNC | TTU_BATCH_FLUSH)))
  2439. return;
  2440. if (folio_is_zone_device(folio) &&
  2441. (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
  2442. return;
  2443. /*
  2444. * During exec, a temporary VMA is setup and later moved.
  2445. * The VMA is moved under the anon_vma lock but not the
  2446. * page tables leading to a race where migration cannot
  2447. * find the migration ptes. Rather than increasing the
  2448. * locking requirements of exec(), migration skips
  2449. * temporary VMAs until after exec() completes.
  2450. */
  2451. if (!folio_test_ksm(folio) && folio_test_anon(folio))
  2452. rwc.invalid_vma = invalid_migration_vma;
  2453. if (flags & TTU_RMAP_LOCKED)
  2454. rmap_walk_locked(folio, &rwc);
  2455. else
  2456. rmap_walk(folio, &rwc);
  2457. }
  2458. #ifdef CONFIG_DEVICE_PRIVATE
  2459. /**
  2460. * make_device_exclusive() - Mark a page for exclusive use by a device
  2461. * @mm: mm_struct of associated target process
  2462. * @addr: the virtual address to mark for exclusive device access
  2463. * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
  2464. * @foliop: folio pointer will be stored here on success.
  2465. *
  2466. * This function looks up the page mapped at the given address, grabs a
  2467. * folio reference, locks the folio and replaces the PTE with special
  2468. * device-exclusive PFN swap entry, preventing access through the process
  2469. * page tables. The function will return with the folio locked and referenced.
  2470. *
  2471. * On fault, the device-exclusive entries are replaced with the original PTE
  2472. * under folio lock, after calling MMU notifiers.
  2473. *
  2474. * Only anonymous non-hugetlb folios are supported and the VMA must have
  2475. * write permissions such that we can fault in the anonymous page writable
  2476. * in order to mark it exclusive. The caller must hold the mmap_lock in read
  2477. * mode.
  2478. *
  2479. * A driver using this to program access from a device must use a mmu notifier
  2480. * critical section to hold a device specific lock during programming. Once
  2481. * programming is complete it should drop the folio lock and reference after
  2482. * which point CPU access to the page will revoke the exclusive access.
  2483. *
  2484. * Notes:
  2485. * #. This function always operates on individual PTEs mapping individual
  2486. * pages. PMD-sized THPs are first remapped to be mapped by PTEs before
  2487. * the conversion happens on a single PTE corresponding to @addr.
  2488. * #. While concurrent access through the process page tables is prevented,
  2489. * concurrent access through other page references (e.g., earlier GUP
  2490. * invocation) is not handled and not supported.
  2491. * #. device-exclusive entries are considered "clean" and "old" by core-mm.
  2492. * Device drivers must update the folio state when informed by MMU
  2493. * notifiers.
  2494. *
  2495. * Returns: pointer to mapped page on success, otherwise a negative error.
  2496. */
  2497. struct page *make_device_exclusive(struct mm_struct *mm, unsigned long addr,
  2498. void *owner, struct folio **foliop)
  2499. {
  2500. struct mmu_notifier_range range;
  2501. struct folio *folio, *fw_folio;
  2502. struct vm_area_struct *vma;
  2503. struct folio_walk fw;
  2504. struct page *page;
  2505. swp_entry_t entry;
  2506. pte_t swp_pte;
  2507. int ret;
  2508. mmap_assert_locked(mm);
  2509. addr = PAGE_ALIGN_DOWN(addr);
  2510. /*
  2511. * Fault in the page writable and try to lock it; note that if the
  2512. * address would already be marked for exclusive use by a device,
  2513. * the GUP call would undo that first by triggering a fault.
  2514. *
  2515. * If any other device would already map this page exclusively, the
  2516. * fault will trigger a conversion to an ordinary
  2517. * (non-device-exclusive) PTE and issue a MMU_NOTIFY_EXCLUSIVE.
  2518. */
  2519. retry:
  2520. page = get_user_page_vma_remote(mm, addr,
  2521. FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
  2522. &vma);
  2523. if (IS_ERR(page))
  2524. return page;
  2525. folio = page_folio(page);
  2526. if (!folio_test_anon(folio) || folio_test_hugetlb(folio)) {
  2527. folio_put(folio);
  2528. return ERR_PTR(-EOPNOTSUPP);
  2529. }
  2530. ret = folio_lock_killable(folio);
  2531. if (ret) {
  2532. folio_put(folio);
  2533. return ERR_PTR(ret);
  2534. }
  2535. /*
  2536. * Inform secondary MMUs that we are going to convert this PTE to
  2537. * device-exclusive, such that they unmap it now. Note that the
  2538. * caller must filter this event out to prevent livelocks.
  2539. */
  2540. mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0,
  2541. mm, addr, addr + PAGE_SIZE, owner);
  2542. mmu_notifier_invalidate_range_start(&range);
  2543. /*
  2544. * Let's do a second walk and make sure we still find the same page
  2545. * mapped writable. Note that any page of an anonymous folio can
  2546. * only be mapped writable using exactly one PTE ("exclusive"), so
  2547. * there cannot be other mappings.
  2548. */
  2549. fw_folio = folio_walk_start(&fw, vma, addr, 0);
  2550. if (fw_folio != folio || fw.page != page ||
  2551. fw.level != FW_LEVEL_PTE || !pte_write(fw.pte)) {
  2552. if (fw_folio)
  2553. folio_walk_end(&fw, vma);
  2554. mmu_notifier_invalidate_range_end(&range);
  2555. folio_unlock(folio);
  2556. folio_put(folio);
  2557. goto retry;
  2558. }
  2559. /* Nuke the page table entry so we get the uptodate dirty bit. */
  2560. flush_cache_page(vma, addr, page_to_pfn(page));
  2561. fw.pte = ptep_clear_flush(vma, addr, fw.ptep);
  2562. /* Set the dirty flag on the folio now the PTE is gone. */
  2563. if (pte_dirty(fw.pte))
  2564. folio_mark_dirty(folio);
  2565. /*
  2566. * Store the pfn of the page in a special device-exclusive PFN swap PTE.
  2567. * do_swap_page() will trigger the conversion back while holding the
  2568. * folio lock.
  2569. */
  2570. entry = make_device_exclusive_entry(page_to_pfn(page));
  2571. swp_pte = swp_entry_to_pte(entry);
  2572. if (pte_soft_dirty(fw.pte))
  2573. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2574. /* The pte is writable, uffd-wp does not apply. */
  2575. set_pte_at(mm, addr, fw.ptep, swp_pte);
  2576. folio_walk_end(&fw, vma);
  2577. mmu_notifier_invalidate_range_end(&range);
  2578. *foliop = folio;
  2579. return page;
  2580. }
  2581. EXPORT_SYMBOL_GPL(make_device_exclusive);
  2582. #endif
  2583. void __put_anon_vma(struct anon_vma *anon_vma)
  2584. {
  2585. struct anon_vma *root = anon_vma->root;
  2586. anon_vma_free(anon_vma);
  2587. if (root != anon_vma && atomic_dec_and_test(&root->refcount))
  2588. anon_vma_free(root);
  2589. }
  2590. static struct anon_vma *rmap_walk_anon_lock(const struct folio *folio,
  2591. struct rmap_walk_control *rwc)
  2592. {
  2593. struct anon_vma *anon_vma;
  2594. if (rwc->anon_lock)
  2595. return rwc->anon_lock(folio, rwc);
  2596. /*
  2597. * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
  2598. * because that depends on page_mapped(); but not all its usages
  2599. * are holding mmap_lock. Users without mmap_lock are required to
  2600. * take a reference count to prevent the anon_vma disappearing
  2601. */
  2602. anon_vma = folio_anon_vma(folio);
  2603. if (!anon_vma)
  2604. return NULL;
  2605. if (anon_vma_trylock_read(anon_vma))
  2606. goto out;
  2607. if (rwc->try_lock) {
  2608. anon_vma = NULL;
  2609. rwc->contended = true;
  2610. goto out;
  2611. }
  2612. anon_vma_lock_read(anon_vma);
  2613. out:
  2614. return anon_vma;
  2615. }
  2616. /*
  2617. * rmap_walk_anon - do something to anonymous page using the object-based
  2618. * rmap method
  2619. * @folio: the folio to be handled
  2620. * @rwc: control variable according to each walk type
  2621. * @locked: caller holds relevant rmap lock
  2622. *
  2623. * Find all the mappings of a folio using the mapping pointer and the vma
  2624. * chains contained in the anon_vma struct it points to.
  2625. */
  2626. static void rmap_walk_anon(struct folio *folio,
  2627. struct rmap_walk_control *rwc, bool locked)
  2628. {
  2629. struct anon_vma *anon_vma;
  2630. pgoff_t pgoff_start, pgoff_end;
  2631. struct anon_vma_chain *avc;
  2632. /*
  2633. * The folio lock ensures that folio->mapping can't be changed under us
  2634. * to an anon_vma with different root.
  2635. */
  2636. VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
  2637. if (locked) {
  2638. anon_vma = folio_anon_vma(folio);
  2639. /* anon_vma disappear under us? */
  2640. VM_BUG_ON_FOLIO(!anon_vma, folio);
  2641. } else {
  2642. anon_vma = rmap_walk_anon_lock(folio, rwc);
  2643. }
  2644. if (!anon_vma)
  2645. return;
  2646. pgoff_start = folio_pgoff(folio);
  2647. pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
  2648. anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
  2649. pgoff_start, pgoff_end) {
  2650. struct vm_area_struct *vma = avc->vma;
  2651. unsigned long address = vma_address(vma, pgoff_start,
  2652. folio_nr_pages(folio));
  2653. VM_BUG_ON_VMA(address == -EFAULT, vma);
  2654. cond_resched();
  2655. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2656. continue;
  2657. if (!rwc->rmap_one(folio, vma, address, rwc->arg))
  2658. break;
  2659. if (rwc->done && rwc->done(folio))
  2660. break;
  2661. }
  2662. if (!locked)
  2663. anon_vma_unlock_read(anon_vma);
  2664. }
  2665. /**
  2666. * __rmap_walk_file() - Traverse the reverse mapping for a file-backed mapping
  2667. * of a page mapped within a specified page cache object at a specified offset.
  2668. *
  2669. * @folio: Either the folio whose mappings to traverse, or if NULL,
  2670. * the callbacks specified in @rwc will be configured such
  2671. * as to be able to look up mappings correctly.
  2672. * @mapping: The page cache object whose mapping VMAs we intend to
  2673. * traverse. If @folio is non-NULL, this should be equal to
  2674. * folio_mapping(folio).
  2675. * @pgoff_start: The offset within @mapping of the page which we are
  2676. * looking up. If @folio is non-NULL, this should be equal
  2677. * to folio_pgoff(folio).
  2678. * @nr_pages: The number of pages mapped by the mapping. If @folio is
  2679. * non-NULL, this should be equal to folio_nr_pages(folio).
  2680. * @rwc: The reverse mapping walk control object describing how
  2681. * the traversal should proceed.
  2682. * @locked: Is the @mapping already locked? If not, we acquire the
  2683. * lock.
  2684. */
  2685. static void __rmap_walk_file(struct folio *folio, struct address_space *mapping,
  2686. pgoff_t pgoff_start, unsigned long nr_pages,
  2687. struct rmap_walk_control *rwc, bool locked)
  2688. {
  2689. pgoff_t pgoff_end = pgoff_start + nr_pages - 1;
  2690. struct vm_area_struct *vma;
  2691. VM_WARN_ON_FOLIO(folio && mapping != folio_mapping(folio), folio);
  2692. VM_WARN_ON_FOLIO(folio && pgoff_start != folio_pgoff(folio), folio);
  2693. VM_WARN_ON_FOLIO(folio && nr_pages != folio_nr_pages(folio), folio);
  2694. if (!locked) {
  2695. if (i_mmap_trylock_read(mapping))
  2696. goto lookup;
  2697. if (rwc->try_lock) {
  2698. rwc->contended = true;
  2699. return;
  2700. }
  2701. i_mmap_lock_read(mapping);
  2702. }
  2703. lookup:
  2704. vma_interval_tree_foreach(vma, &mapping->i_mmap,
  2705. pgoff_start, pgoff_end) {
  2706. unsigned long address = vma_address(vma, pgoff_start, nr_pages);
  2707. VM_BUG_ON_VMA(address == -EFAULT, vma);
  2708. cond_resched();
  2709. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2710. continue;
  2711. if (!rwc->rmap_one(folio, vma, address, rwc->arg))
  2712. goto done;
  2713. if (rwc->done && rwc->done(folio))
  2714. goto done;
  2715. }
  2716. done:
  2717. if (!locked)
  2718. i_mmap_unlock_read(mapping);
  2719. }
  2720. /*
  2721. * rmap_walk_file - do something to file page using the object-based rmap method
  2722. * @folio: the folio to be handled
  2723. * @rwc: control variable according to each walk type
  2724. * @locked: caller holds relevant rmap lock
  2725. *
  2726. * Find all the mappings of a folio using the mapping pointer and the vma chains
  2727. * contained in the address_space struct it points to.
  2728. */
  2729. static void rmap_walk_file(struct folio *folio,
  2730. struct rmap_walk_control *rwc, bool locked)
  2731. {
  2732. /*
  2733. * The folio lock not only makes sure that folio->mapping cannot
  2734. * suddenly be NULLified by truncation, it makes sure that the structure
  2735. * at mapping cannot be freed and reused yet, so we can safely take
  2736. * mapping->i_mmap_rwsem.
  2737. */
  2738. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2739. if (!folio->mapping)
  2740. return;
  2741. __rmap_walk_file(folio, folio->mapping, folio->index,
  2742. folio_nr_pages(folio), rwc, locked);
  2743. }
  2744. void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
  2745. {
  2746. if (unlikely(folio_test_ksm(folio)))
  2747. rmap_walk_ksm(folio, rwc);
  2748. else if (folio_test_anon(folio))
  2749. rmap_walk_anon(folio, rwc, false);
  2750. else
  2751. rmap_walk_file(folio, rwc, false);
  2752. }
  2753. /* Like rmap_walk, but caller holds relevant rmap lock */
  2754. void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
  2755. {
  2756. /* no ksm support for now */
  2757. VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
  2758. if (folio_test_anon(folio))
  2759. rmap_walk_anon(folio, rwc, true);
  2760. else
  2761. rmap_walk_file(folio, rwc, true);
  2762. }
  2763. #ifdef CONFIG_HUGETLB_PAGE
  2764. /*
  2765. * The following two functions are for anonymous (private mapped) hugepages.
  2766. * Unlike common anonymous pages, anonymous hugepages have no accounting code
  2767. * and no lru code, because we handle hugepages differently from common pages.
  2768. */
  2769. void hugetlb_add_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
  2770. unsigned long address, rmap_t flags)
  2771. {
  2772. VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
  2773. VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
  2774. atomic_inc(&folio->_entire_mapcount);
  2775. atomic_inc(&folio->_large_mapcount);
  2776. if (flags & RMAP_EXCLUSIVE)
  2777. SetPageAnonExclusive(&folio->page);
  2778. VM_WARN_ON_FOLIO(folio_entire_mapcount(folio) > 1 &&
  2779. PageAnonExclusive(&folio->page), folio);
  2780. }
  2781. void hugetlb_add_new_anon_rmap(struct folio *folio,
  2782. struct vm_area_struct *vma, unsigned long address)
  2783. {
  2784. VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
  2785. BUG_ON(address < vma->vm_start || address >= vma->vm_end);
  2786. /* increment count (starts at -1) */
  2787. atomic_set(&folio->_entire_mapcount, 0);
  2788. atomic_set(&folio->_large_mapcount, 0);
  2789. folio_clear_hugetlb_restore_reserve(folio);
  2790. __folio_set_anon(folio, vma, address, true);
  2791. SetPageAnonExclusive(&folio->page);
  2792. }
  2793. #endif /* CONFIG_HUGETLB_PAGE */