rmap.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578
  1. /*
  2. * mm/rmap.c - physical to virtual reverse mappings
  3. *
  4. * Copyright 2001, Rik van Riel <[email protected]>
  5. * Released under the General Public License (GPL).
  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 <[email protected]> 2001
  15. * File methods by Dave McCracken <[email protected]> 2003, 2004
  16. * Anonymous methods by Andrea Arcangeli <[email protected]> 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. * page->flags PG_locked (lock_page)
  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. * folio_lock_memcg move_lock (in block_dirty_folio)
  35. * i_pages lock (widely used)
  36. * lruvec->lru_lock (in folio_lruvec_lock_irq)
  37. * inode->i_lock (in set_page_dirty's __mark_inode_dirty)
  38. * bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
  39. * sb_lock (within inode_lock in fs/fs-writeback.c)
  40. * i_pages lock (widely used, in set_page_dirty,
  41. * in arch-dependent flush_dcache_mmap_lock,
  42. * within bdi.wb->list_lock in __sync_single_inode)
  43. *
  44. * anon_vma->rwsem,mapping->i_mmap_rwsem (memory_failure, collect_procs_anon)
  45. * ->tasklist_lock
  46. * pte map lock
  47. *
  48. * hugetlbfs PageHuge() take locks in this order:
  49. * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
  50. * vma_lock (hugetlb specific lock for pmd_sharing)
  51. * mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
  52. * page->flags PG_locked (lock_page)
  53. */
  54. #include <linux/mm.h>
  55. #include <linux/sched/mm.h>
  56. #include <linux/sched/task.h>
  57. #include <linux/pagemap.h>
  58. #include <linux/swap.h>
  59. #include <linux/swapops.h>
  60. #include <linux/slab.h>
  61. #include <linux/init.h>
  62. #include <linux/ksm.h>
  63. #include <linux/rmap.h>
  64. #include <linux/rcupdate.h>
  65. #include <linux/export.h>
  66. #include <linux/memcontrol.h>
  67. #include <linux/mmu_notifier.h>
  68. #include <linux/migrate.h>
  69. #include <linux/hugetlb.h>
  70. #include <linux/huge_mm.h>
  71. #include <linux/backing-dev.h>
  72. #include <linux/page_idle.h>
  73. #include <linux/memremap.h>
  74. #include <linux/userfaultfd_k.h>
  75. #include <linux/mm_inline.h>
  76. #include <asm/tlbflush.h>
  77. #define CREATE_TRACE_POINTS
  78. #include <trace/events/tlb.h>
  79. #include <trace/events/migrate.h>
  80. #undef CREATE_TRACE_POINTS
  81. #include <trace/hooks/mm.h>
  82. #include "internal.h"
  83. static struct kmem_cache *anon_vma_cachep;
  84. static struct kmem_cache *anon_vma_chain_cachep;
  85. static inline struct anon_vma *anon_vma_alloc(void)
  86. {
  87. struct anon_vma *anon_vma;
  88. anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
  89. if (anon_vma) {
  90. atomic_set(&anon_vma->refcount, 1);
  91. anon_vma->num_children = 0;
  92. anon_vma->num_active_vmas = 0;
  93. anon_vma->parent = anon_vma;
  94. /*
  95. * Initialise the anon_vma root to point to itself. If called
  96. * from fork, the root will be reset to the parents anon_vma.
  97. */
  98. anon_vma->root = anon_vma;
  99. }
  100. return anon_vma;
  101. }
  102. static inline void anon_vma_free(struct anon_vma *anon_vma)
  103. {
  104. VM_BUG_ON(atomic_read(&anon_vma->refcount));
  105. /*
  106. * Synchronize against folio_lock_anon_vma_read() such that
  107. * we can safely hold the lock without the anon_vma getting
  108. * freed.
  109. *
  110. * Relies on the full mb implied by the atomic_dec_and_test() from
  111. * put_anon_vma() against the acquire barrier implied by
  112. * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
  113. *
  114. * folio_lock_anon_vma_read() VS put_anon_vma()
  115. * down_read_trylock() atomic_dec_and_test()
  116. * LOCK MB
  117. * atomic_read() rwsem_is_locked()
  118. *
  119. * LOCK should suffice since the actual taking of the lock must
  120. * happen _before_ what follows.
  121. */
  122. might_sleep();
  123. if (rwsem_is_locked(&anon_vma->root->rwsem)) {
  124. anon_vma_lock_write(anon_vma);
  125. anon_vma_unlock_write(anon_vma);
  126. }
  127. kmem_cache_free(anon_vma_cachep, anon_vma);
  128. }
  129. static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
  130. {
  131. return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
  132. }
  133. static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
  134. {
  135. kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
  136. }
  137. static void anon_vma_chain_link(struct vm_area_struct *vma,
  138. struct anon_vma_chain *avc,
  139. struct anon_vma *anon_vma)
  140. {
  141. avc->vma = vma;
  142. avc->anon_vma = anon_vma;
  143. list_add(&avc->same_vma, &vma->anon_vma_chain);
  144. anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
  145. }
  146. /**
  147. * __anon_vma_prepare - attach an anon_vma to a memory region
  148. * @vma: the memory region in question
  149. *
  150. * This makes sure the memory mapping described by 'vma' has
  151. * an 'anon_vma' attached to it, so that we can associate the
  152. * anonymous pages mapped into it with that anon_vma.
  153. *
  154. * The common case will be that we already have one, which
  155. * is handled inline by anon_vma_prepare(). But if
  156. * not we either need to find an adjacent mapping that we
  157. * can re-use the anon_vma from (very common when the only
  158. * reason for splitting a vma has been mprotect()), or we
  159. * allocate a new one.
  160. *
  161. * Anon-vma allocations are very subtle, because we may have
  162. * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
  163. * and that may actually touch the rwsem even in the newly
  164. * allocated vma (it depends on RCU to make sure that the
  165. * anon_vma isn't actually destroyed).
  166. *
  167. * As a result, we need to do proper anon_vma locking even
  168. * for the new allocation. At the same time, we do not want
  169. * to do any locking for the common case of already having
  170. * an anon_vma.
  171. *
  172. * This must be called with the mmap_lock held for reading.
  173. */
  174. int __anon_vma_prepare(struct vm_area_struct *vma)
  175. {
  176. struct mm_struct *mm = vma->vm_mm;
  177. struct anon_vma *anon_vma, *allocated;
  178. struct anon_vma_chain *avc;
  179. might_sleep();
  180. avc = anon_vma_chain_alloc(GFP_KERNEL);
  181. if (!avc)
  182. goto out_enomem;
  183. anon_vma = find_mergeable_anon_vma(vma);
  184. allocated = NULL;
  185. if (!anon_vma) {
  186. anon_vma = anon_vma_alloc();
  187. if (unlikely(!anon_vma))
  188. goto out_enomem_free_avc;
  189. anon_vma->num_children++; /* self-parent link for new root */
  190. allocated = anon_vma;
  191. }
  192. anon_vma_lock_write(anon_vma);
  193. /* page_table_lock to protect against threads */
  194. spin_lock(&mm->page_table_lock);
  195. if (likely(!vma->anon_vma)) {
  196. vma->anon_vma = anon_vma;
  197. anon_vma_chain_link(vma, avc, anon_vma);
  198. anon_vma->num_active_vmas++;
  199. allocated = NULL;
  200. avc = NULL;
  201. }
  202. spin_unlock(&mm->page_table_lock);
  203. anon_vma_unlock_write(anon_vma);
  204. if (unlikely(allocated))
  205. put_anon_vma(allocated);
  206. if (unlikely(avc))
  207. anon_vma_chain_free(avc);
  208. return 0;
  209. out_enomem_free_avc:
  210. anon_vma_chain_free(avc);
  211. out_enomem:
  212. return -ENOMEM;
  213. }
  214. /*
  215. * This is a useful helper function for locking the anon_vma root as
  216. * we traverse the vma->anon_vma_chain, looping over anon_vma's that
  217. * have the same vma.
  218. *
  219. * Such anon_vma's should have the same root, so you'd expect to see
  220. * just a single mutex_lock for the whole traversal.
  221. */
  222. static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
  223. {
  224. struct anon_vma *new_root = anon_vma->root;
  225. if (new_root != root) {
  226. if (WARN_ON_ONCE(root))
  227. up_write(&root->rwsem);
  228. root = new_root;
  229. down_write(&root->rwsem);
  230. }
  231. return root;
  232. }
  233. static inline void unlock_anon_vma_root(struct anon_vma *root)
  234. {
  235. if (root)
  236. up_write(&root->rwsem);
  237. }
  238. /*
  239. * Attach the anon_vmas from src to dst.
  240. * Returns 0 on success, -ENOMEM on failure.
  241. *
  242. * anon_vma_clone() is called by __vma_adjust(), __split_vma(), copy_vma() and
  243. * anon_vma_fork(). The first three want an exact copy of src, while the last
  244. * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
  245. * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
  246. * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
  247. *
  248. * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
  249. * and reuse existing anon_vma which has no vmas and only one child anon_vma.
  250. * This prevents degradation of anon_vma hierarchy to endless linear chain in
  251. * case of constantly forking task. On the other hand, an anon_vma with more
  252. * than one child isn't reused even if there was no alive vma, thus rmap
  253. * walker has a good chance of avoiding scanning the whole hierarchy when it
  254. * searches where page is mapped.
  255. */
  256. int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
  257. {
  258. struct anon_vma_chain *avc, *pavc;
  259. struct anon_vma *root = NULL;
  260. list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
  261. struct anon_vma *anon_vma;
  262. avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
  263. if (unlikely(!avc)) {
  264. unlock_anon_vma_root(root);
  265. root = NULL;
  266. avc = anon_vma_chain_alloc(GFP_KERNEL);
  267. if (!avc)
  268. goto enomem_failure;
  269. }
  270. anon_vma = pavc->anon_vma;
  271. root = lock_anon_vma_root(root, anon_vma);
  272. anon_vma_chain_link(dst, avc, anon_vma);
  273. /*
  274. * Reuse existing anon_vma if it has no vma and only one
  275. * anon_vma child.
  276. *
  277. * Root anon_vma is never reused:
  278. * it has self-parent reference and at least one child.
  279. */
  280. if (!dst->anon_vma && src->anon_vma &&
  281. anon_vma->num_children < 2 &&
  282. anon_vma->num_active_vmas == 0)
  283. dst->anon_vma = anon_vma;
  284. }
  285. if (dst->anon_vma)
  286. dst->anon_vma->num_active_vmas++;
  287. unlock_anon_vma_root(root);
  288. return 0;
  289. enomem_failure:
  290. /*
  291. * dst->anon_vma is dropped here otherwise its degree can be incorrectly
  292. * decremented in unlink_anon_vmas().
  293. * We can safely do this because callers of anon_vma_clone() don't care
  294. * about dst->anon_vma if anon_vma_clone() failed.
  295. */
  296. dst->anon_vma = NULL;
  297. unlink_anon_vmas(dst);
  298. return -ENOMEM;
  299. }
  300. /*
  301. * Attach vma to its own anon_vma, as well as to the anon_vmas that
  302. * the corresponding VMA in the parent process is attached to.
  303. * Returns 0 on success, non-zero on failure.
  304. */
  305. int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
  306. {
  307. struct anon_vma_chain *avc;
  308. struct anon_vma *anon_vma;
  309. int error;
  310. /* Don't bother if the parent process has no anon_vma here. */
  311. if (!pvma->anon_vma)
  312. return 0;
  313. /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
  314. vma->anon_vma = NULL;
  315. /*
  316. * First, attach the new VMA to the parent VMA's anon_vmas,
  317. * so rmap can find non-COWed pages in child processes.
  318. */
  319. error = anon_vma_clone(vma, pvma);
  320. if (error)
  321. return error;
  322. /* An existing anon_vma has been reused, all done then. */
  323. if (vma->anon_vma)
  324. return 0;
  325. /* Then add our own anon_vma. */
  326. anon_vma = anon_vma_alloc();
  327. if (!anon_vma)
  328. goto out_error;
  329. anon_vma->num_active_vmas++;
  330. avc = anon_vma_chain_alloc(GFP_KERNEL);
  331. if (!avc)
  332. goto out_error_free_anon_vma;
  333. /*
  334. * The root anon_vma's rwsem is the lock actually used when we
  335. * lock any of the anon_vmas in this anon_vma tree.
  336. */
  337. anon_vma->root = pvma->anon_vma->root;
  338. anon_vma->parent = pvma->anon_vma;
  339. /*
  340. * With refcounts, an anon_vma can stay around longer than the
  341. * process it belongs to. The root anon_vma needs to be pinned until
  342. * this anon_vma is freed, because the lock lives in the root.
  343. */
  344. get_anon_vma(anon_vma->root);
  345. /* Mark this anon_vma as the one where our new (COWed) pages go. */
  346. vma->anon_vma = anon_vma;
  347. anon_vma_lock_write(anon_vma);
  348. anon_vma_chain_link(vma, avc, anon_vma);
  349. anon_vma->parent->num_children++;
  350. anon_vma_unlock_write(anon_vma);
  351. return 0;
  352. out_error_free_anon_vma:
  353. put_anon_vma(anon_vma);
  354. out_error:
  355. unlink_anon_vmas(vma);
  356. return -ENOMEM;
  357. }
  358. void unlink_anon_vmas(struct vm_area_struct *vma)
  359. {
  360. struct anon_vma_chain *avc, *next;
  361. struct anon_vma *root = NULL;
  362. /*
  363. * Unlink each anon_vma chained to the VMA. This list is ordered
  364. * from newest to oldest, ensuring the root anon_vma gets freed last.
  365. */
  366. list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
  367. struct anon_vma *anon_vma = avc->anon_vma;
  368. root = lock_anon_vma_root(root, anon_vma);
  369. anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
  370. /*
  371. * Leave empty anon_vmas on the list - we'll need
  372. * to free them outside the lock.
  373. */
  374. if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
  375. anon_vma->parent->num_children--;
  376. continue;
  377. }
  378. list_del(&avc->same_vma);
  379. anon_vma_chain_free(avc);
  380. }
  381. if (vma->anon_vma) {
  382. vma->anon_vma->num_active_vmas--;
  383. /*
  384. * vma would still be needed after unlink, and anon_vma will be prepared
  385. * when handle fault.
  386. */
  387. vma->anon_vma = NULL;
  388. }
  389. unlock_anon_vma_root(root);
  390. /*
  391. * Iterate the list once more, it now only contains empty and unlinked
  392. * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
  393. * needing to write-acquire the anon_vma->root->rwsem.
  394. */
  395. list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
  396. struct anon_vma *anon_vma = avc->anon_vma;
  397. VM_WARN_ON(anon_vma->num_children);
  398. VM_WARN_ON(anon_vma->num_active_vmas);
  399. put_anon_vma(anon_vma);
  400. list_del(&avc->same_vma);
  401. anon_vma_chain_free(avc);
  402. }
  403. }
  404. static void anon_vma_ctor(void *data)
  405. {
  406. struct anon_vma *anon_vma = data;
  407. init_rwsem(&anon_vma->rwsem);
  408. atomic_set(&anon_vma->refcount, 0);
  409. anon_vma->rb_root = RB_ROOT_CACHED;
  410. }
  411. void __init anon_vma_init(void)
  412. {
  413. anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
  414. 0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
  415. anon_vma_ctor);
  416. anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
  417. SLAB_PANIC|SLAB_ACCOUNT);
  418. }
  419. /*
  420. * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
  421. *
  422. * Since there is no serialization what so ever against page_remove_rmap()
  423. * the best this function can do is return a refcount increased anon_vma
  424. * that might have been relevant to this page.
  425. *
  426. * The page might have been remapped to a different anon_vma or the anon_vma
  427. * returned may already be freed (and even reused).
  428. *
  429. * In case it was remapped to a different anon_vma, the new anon_vma will be a
  430. * child of the old anon_vma, and the anon_vma lifetime rules will therefore
  431. * ensure that any anon_vma obtained from the page will still be valid for as
  432. * long as we observe page_mapped() [ hence all those page_mapped() tests ].
  433. *
  434. * All users of this function must be very careful when walking the anon_vma
  435. * chain and verify that the page in question is indeed mapped in it
  436. * [ something equivalent to page_mapped_in_vma() ].
  437. *
  438. * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
  439. * page_remove_rmap() that the anon_vma pointer from page->mapping is valid
  440. * if there is a mapcount, we can dereference the anon_vma after observing
  441. * those.
  442. */
  443. struct anon_vma *folio_get_anon_vma(struct folio *folio)
  444. {
  445. struct anon_vma *anon_vma = NULL;
  446. unsigned long anon_mapping;
  447. rcu_read_lock();
  448. anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
  449. if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
  450. goto out;
  451. if (!folio_mapped(folio))
  452. goto out;
  453. anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
  454. if (!atomic_inc_not_zero(&anon_vma->refcount)) {
  455. anon_vma = NULL;
  456. goto out;
  457. }
  458. /*
  459. * If this folio is still mapped, then its anon_vma cannot have been
  460. * freed. But if it has been unmapped, we have no security against the
  461. * anon_vma structure being freed and reused (for another anon_vma:
  462. * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
  463. * above cannot corrupt).
  464. */
  465. if (!folio_mapped(folio)) {
  466. rcu_read_unlock();
  467. put_anon_vma(anon_vma);
  468. return NULL;
  469. }
  470. out:
  471. rcu_read_unlock();
  472. return anon_vma;
  473. }
  474. /*
  475. * Similar to folio_get_anon_vma() except it locks the anon_vma.
  476. *
  477. * Its a little more complex as it tries to keep the fast path to a single
  478. * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
  479. * reference like with folio_get_anon_vma() and then block on the mutex
  480. * on !rwc->try_lock case.
  481. */
  482. struct anon_vma *folio_lock_anon_vma_read(struct folio *folio,
  483. struct rmap_walk_control *rwc)
  484. {
  485. struct anon_vma *anon_vma = NULL;
  486. struct anon_vma *root_anon_vma;
  487. unsigned long anon_mapping;
  488. rcu_read_lock();
  489. anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
  490. if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
  491. goto out;
  492. if (!folio_mapped(folio))
  493. goto out;
  494. anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
  495. root_anon_vma = READ_ONCE(anon_vma->root);
  496. if (down_read_trylock(&root_anon_vma->rwsem)) {
  497. /*
  498. * If the folio is still mapped, then this anon_vma is still
  499. * its anon_vma, and holding the mutex ensures that it will
  500. * not go away, see anon_vma_free().
  501. */
  502. if (!folio_mapped(folio)) {
  503. up_read(&root_anon_vma->rwsem);
  504. anon_vma = NULL;
  505. }
  506. goto out;
  507. }
  508. if (rwc && rwc->try_lock) {
  509. anon_vma = NULL;
  510. rwc->contended = true;
  511. goto out;
  512. }
  513. /* trylock failed, we got to sleep */
  514. if (!atomic_inc_not_zero(&anon_vma->refcount)) {
  515. anon_vma = NULL;
  516. goto out;
  517. }
  518. if (!folio_mapped(folio)) {
  519. rcu_read_unlock();
  520. put_anon_vma(anon_vma);
  521. return NULL;
  522. }
  523. /* we pinned the anon_vma, its safe to sleep */
  524. rcu_read_unlock();
  525. anon_vma_lock_read(anon_vma);
  526. if (atomic_dec_and_test(&anon_vma->refcount)) {
  527. /*
  528. * Oops, we held the last refcount, release the lock
  529. * and bail -- can't simply use put_anon_vma() because
  530. * we'll deadlock on the anon_vma_lock_write() recursion.
  531. */
  532. anon_vma_unlock_read(anon_vma);
  533. __put_anon_vma(anon_vma);
  534. anon_vma = NULL;
  535. }
  536. return anon_vma;
  537. out:
  538. rcu_read_unlock();
  539. return anon_vma;
  540. }
  541. #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
  542. /*
  543. * Flush TLB entries for recently unmapped pages from remote CPUs. It is
  544. * important if a PTE was dirty when it was unmapped that it's flushed
  545. * before any IO is initiated on the page to prevent lost writes. Similarly,
  546. * it must be flushed before freeing to prevent data leakage.
  547. */
  548. void try_to_unmap_flush(void)
  549. {
  550. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  551. if (!tlb_ubc->flush_required)
  552. return;
  553. arch_tlbbatch_flush(&tlb_ubc->arch);
  554. tlb_ubc->flush_required = false;
  555. tlb_ubc->writable = false;
  556. }
  557. /* Flush iff there are potentially writable TLB entries that can race with IO */
  558. void try_to_unmap_flush_dirty(void)
  559. {
  560. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  561. if (tlb_ubc->writable)
  562. try_to_unmap_flush();
  563. }
  564. /*
  565. * Bits 0-14 of mm->tlb_flush_batched record pending generations.
  566. * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
  567. */
  568. #define TLB_FLUSH_BATCH_FLUSHED_SHIFT 16
  569. #define TLB_FLUSH_BATCH_PENDING_MASK \
  570. ((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
  571. #define TLB_FLUSH_BATCH_PENDING_LARGE \
  572. (TLB_FLUSH_BATCH_PENDING_MASK / 2)
  573. static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
  574. {
  575. struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
  576. int batch, nbatch;
  577. arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
  578. tlb_ubc->flush_required = true;
  579. /*
  580. * Ensure compiler does not re-order the setting of tlb_flush_batched
  581. * before the PTE is cleared.
  582. */
  583. barrier();
  584. batch = atomic_read(&mm->tlb_flush_batched);
  585. retry:
  586. if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
  587. /*
  588. * Prevent `pending' from catching up with `flushed' because of
  589. * overflow. Reset `pending' and `flushed' to be 1 and 0 if
  590. * `pending' becomes large.
  591. */
  592. nbatch = atomic_cmpxchg(&mm->tlb_flush_batched, batch, 1);
  593. if (nbatch != batch) {
  594. batch = nbatch;
  595. goto retry;
  596. }
  597. } else {
  598. atomic_inc(&mm->tlb_flush_batched);
  599. }
  600. /*
  601. * If the PTE was dirty then it's best to assume it's writable. The
  602. * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
  603. * before the page is queued for IO.
  604. */
  605. if (writable)
  606. tlb_ubc->writable = true;
  607. }
  608. /*
  609. * Returns true if the TLB flush should be deferred to the end of a batch of
  610. * unmap operations to reduce IPIs.
  611. */
  612. static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
  613. {
  614. bool should_defer = false;
  615. if (!(flags & TTU_BATCH_FLUSH))
  616. return false;
  617. /* If remote CPUs need to be flushed then defer batch the flush */
  618. if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
  619. should_defer = true;
  620. put_cpu();
  621. return should_defer;
  622. }
  623. /*
  624. * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
  625. * releasing the PTL if TLB flushes are batched. It's possible for a parallel
  626. * operation such as mprotect or munmap to race between reclaim unmapping
  627. * the page and flushing the page. If this race occurs, it potentially allows
  628. * access to data via a stale TLB entry. Tracking all mm's that have TLB
  629. * batching in flight would be expensive during reclaim so instead track
  630. * whether TLB batching occurred in the past and if so then do a flush here
  631. * if required. This will cost one additional flush per reclaim cycle paid
  632. * by the first operation at risk such as mprotect and mumap.
  633. *
  634. * This must be called under the PTL so that an access to tlb_flush_batched
  635. * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
  636. * via the PTL.
  637. */
  638. void flush_tlb_batched_pending(struct mm_struct *mm)
  639. {
  640. int batch = atomic_read(&mm->tlb_flush_batched);
  641. int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
  642. int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
  643. if (pending != flushed) {
  644. flush_tlb_mm(mm);
  645. /*
  646. * If the new TLB flushing is pending during flushing, leave
  647. * mm->tlb_flush_batched as is, to avoid losing flushing.
  648. */
  649. atomic_cmpxchg(&mm->tlb_flush_batched, batch,
  650. pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
  651. }
  652. }
  653. #else
  654. static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
  655. {
  656. }
  657. static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
  658. {
  659. return false;
  660. }
  661. #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
  662. /*
  663. * At what user virtual address is page expected in vma?
  664. * Caller should check the page is actually part of the vma.
  665. */
  666. unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
  667. {
  668. struct folio *folio = page_folio(page);
  669. if (folio_test_anon(folio)) {
  670. struct anon_vma *page__anon_vma = folio_anon_vma(folio);
  671. /*
  672. * Note: swapoff's unuse_vma() is more efficient with this
  673. * check, and needs it to match anon_vma when KSM is active.
  674. */
  675. if (!vma->anon_vma || !page__anon_vma ||
  676. vma->anon_vma->root != page__anon_vma->root)
  677. return -EFAULT;
  678. } else if (!vma->vm_file) {
  679. return -EFAULT;
  680. } else if (vma->vm_file->f_mapping != folio->mapping) {
  681. return -EFAULT;
  682. }
  683. return vma_address(page, vma);
  684. }
  685. /*
  686. * Returns the actual pmd_t* where we expect 'address' to be mapped from, or
  687. * NULL if it doesn't exist. No guarantees / checks on what the pmd_t*
  688. * represents.
  689. */
  690. pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
  691. {
  692. pgd_t *pgd;
  693. p4d_t *p4d;
  694. pud_t *pud;
  695. pmd_t *pmd = NULL;
  696. pgd = pgd_offset(mm, address);
  697. if (!pgd_present(*pgd))
  698. goto out;
  699. p4d = p4d_offset(pgd, address);
  700. if (!p4d_present(*p4d))
  701. goto out;
  702. pud = pud_offset(p4d, address);
  703. if (!pud_present(*pud))
  704. goto out;
  705. pmd = pmd_offset(pud, address);
  706. out:
  707. return pmd;
  708. }
  709. struct folio_referenced_arg {
  710. int mapcount;
  711. int referenced;
  712. unsigned long vm_flags;
  713. struct mem_cgroup *memcg;
  714. };
  715. /*
  716. * arg: folio_referenced_arg will be passed
  717. */
  718. static bool folio_referenced_one(struct folio *folio,
  719. struct vm_area_struct *vma, unsigned long address, void *arg)
  720. {
  721. struct folio_referenced_arg *pra = arg;
  722. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  723. int referenced = 0;
  724. while (page_vma_mapped_walk(&pvmw)) {
  725. address = pvmw.address;
  726. if ((vma->vm_flags & VM_LOCKED) &&
  727. (!folio_test_large(folio) || !pvmw.pte)) {
  728. /* Restore the mlock which got missed */
  729. mlock_vma_folio(folio, vma, !pvmw.pte);
  730. page_vma_mapped_walk_done(&pvmw);
  731. pra->vm_flags |= VM_LOCKED;
  732. return false; /* To break the loop */
  733. }
  734. if (pvmw.pte) {
  735. trace_android_vh_look_around(&pvmw, folio, vma, &referenced);
  736. if (lru_gen_enabled() && pte_young(*pvmw.pte)) {
  737. lru_gen_look_around(&pvmw);
  738. referenced++;
  739. }
  740. if (ptep_clear_flush_young_notify(vma, address,
  741. pvmw.pte))
  742. referenced++;
  743. } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
  744. if (pmdp_clear_flush_young_notify(vma, address,
  745. pvmw.pmd))
  746. referenced++;
  747. } else {
  748. /* unexpected pmd-mapped folio? */
  749. WARN_ON_ONCE(1);
  750. }
  751. pra->mapcount--;
  752. }
  753. if (referenced)
  754. folio_clear_idle(folio);
  755. if (folio_test_clear_young(folio))
  756. referenced++;
  757. if (referenced) {
  758. pra->referenced++;
  759. pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
  760. }
  761. if (!pra->mapcount)
  762. return false; /* To break the loop */
  763. return true;
  764. }
  765. static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
  766. {
  767. struct folio_referenced_arg *pra = arg;
  768. struct mem_cgroup *memcg = pra->memcg;
  769. /*
  770. * Ignore references from this mapping if it has no recency. If the
  771. * folio has been used in another mapping, we will catch it; if this
  772. * other mapping is already gone, the unmap path will have set the
  773. * referenced flag or activated the folio in zap_pte_range().
  774. */
  775. if (!vma_has_recency(vma))
  776. return true;
  777. /*
  778. * If we are reclaiming on behalf of a cgroup, skip counting on behalf
  779. * of references from different cgroups.
  780. */
  781. if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
  782. return true;
  783. return false;
  784. }
  785. /**
  786. * folio_referenced() - Test if the folio was referenced.
  787. * @folio: The folio to test.
  788. * @is_locked: Caller holds lock on the folio.
  789. * @memcg: target memory cgroup
  790. * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
  791. *
  792. * Quick test_and_clear_referenced for all mappings of a folio,
  793. *
  794. * Return: The number of mappings which referenced the folio. Return -1 if
  795. * the function bailed out due to rmap lock contention.
  796. */
  797. int folio_referenced(struct folio *folio, int is_locked,
  798. struct mem_cgroup *memcg, unsigned long *vm_flags)
  799. {
  800. int we_locked = 0;
  801. struct folio_referenced_arg pra = {
  802. .mapcount = folio_mapcount(folio),
  803. .memcg = memcg,
  804. };
  805. struct rmap_walk_control rwc = {
  806. .rmap_one = folio_referenced_one,
  807. .arg = (void *)&pra,
  808. .anon_lock = folio_lock_anon_vma_read,
  809. .try_lock = true,
  810. .invalid_vma = invalid_folio_referenced_vma,
  811. };
  812. *vm_flags = 0;
  813. if (!pra.mapcount)
  814. return 0;
  815. if (!folio_raw_mapping(folio))
  816. return 0;
  817. if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
  818. we_locked = folio_trylock(folio);
  819. if (!we_locked)
  820. return 1;
  821. }
  822. rmap_walk(folio, &rwc);
  823. *vm_flags = pra.vm_flags;
  824. if (we_locked)
  825. folio_unlock(folio);
  826. return rwc.contended ? -1 : pra.referenced;
  827. }
  828. EXPORT_SYMBOL_GPL(folio_referenced);
  829. static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
  830. {
  831. int cleaned = 0;
  832. struct vm_area_struct *vma = pvmw->vma;
  833. struct mmu_notifier_range range;
  834. unsigned long address = pvmw->address;
  835. /*
  836. * We have to assume the worse case ie pmd for invalidation. Note that
  837. * the folio can not be freed from this function.
  838. */
  839. mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
  840. 0, vma, vma->vm_mm, address,
  841. vma_address_end(pvmw));
  842. mmu_notifier_invalidate_range_start(&range);
  843. while (page_vma_mapped_walk(pvmw)) {
  844. int ret = 0;
  845. address = pvmw->address;
  846. if (pvmw->pte) {
  847. pte_t entry;
  848. pte_t *pte = pvmw->pte;
  849. if (!pte_dirty(*pte) && !pte_write(*pte))
  850. continue;
  851. flush_cache_page(vma, address, pte_pfn(*pte));
  852. entry = ptep_clear_flush(vma, address, pte);
  853. entry = pte_wrprotect(entry);
  854. entry = pte_mkclean(entry);
  855. set_pte_at(vma->vm_mm, address, pte, entry);
  856. ret = 1;
  857. } else {
  858. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  859. pmd_t *pmd = pvmw->pmd;
  860. pmd_t entry;
  861. if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
  862. continue;
  863. flush_cache_range(vma, address,
  864. address + HPAGE_PMD_SIZE);
  865. entry = pmdp_invalidate(vma, address, pmd);
  866. entry = pmd_wrprotect(entry);
  867. entry = pmd_mkclean(entry);
  868. set_pmd_at(vma->vm_mm, address, pmd, entry);
  869. ret = 1;
  870. #else
  871. /* unexpected pmd-mapped folio? */
  872. WARN_ON_ONCE(1);
  873. #endif
  874. }
  875. /*
  876. * No need to call mmu_notifier_invalidate_range() as we are
  877. * downgrading page table protection not changing it to point
  878. * to a new page.
  879. *
  880. * See Documentation/mm/mmu_notifier.rst
  881. */
  882. if (ret)
  883. cleaned++;
  884. }
  885. mmu_notifier_invalidate_range_end(&range);
  886. return cleaned;
  887. }
  888. static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
  889. unsigned long address, void *arg)
  890. {
  891. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
  892. int *cleaned = arg;
  893. *cleaned += page_vma_mkclean_one(&pvmw);
  894. return true;
  895. }
  896. static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
  897. {
  898. if (vma->vm_flags & VM_SHARED)
  899. return false;
  900. return true;
  901. }
  902. int folio_mkclean(struct folio *folio)
  903. {
  904. int cleaned = 0;
  905. struct address_space *mapping;
  906. struct rmap_walk_control rwc = {
  907. .arg = (void *)&cleaned,
  908. .rmap_one = page_mkclean_one,
  909. .invalid_vma = invalid_mkclean_vma,
  910. };
  911. BUG_ON(!folio_test_locked(folio));
  912. if (!folio_mapped(folio))
  913. return 0;
  914. mapping = folio_mapping(folio);
  915. if (!mapping)
  916. return 0;
  917. rmap_walk(folio, &rwc);
  918. return cleaned;
  919. }
  920. EXPORT_SYMBOL_GPL(folio_mkclean);
  921. /**
  922. * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
  923. * [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
  924. * within the @vma of shared mappings. And since clean PTEs
  925. * should also be readonly, write protects them too.
  926. * @pfn: start pfn.
  927. * @nr_pages: number of physically contiguous pages srarting with @pfn.
  928. * @pgoff: page offset that the @pfn mapped with.
  929. * @vma: vma that @pfn mapped within.
  930. *
  931. * Returns the number of cleaned PTEs (including PMDs).
  932. */
  933. int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
  934. struct vm_area_struct *vma)
  935. {
  936. struct page_vma_mapped_walk pvmw = {
  937. .pfn = pfn,
  938. .nr_pages = nr_pages,
  939. .pgoff = pgoff,
  940. .vma = vma,
  941. .flags = PVMW_SYNC,
  942. };
  943. if (invalid_mkclean_vma(vma, NULL))
  944. return 0;
  945. pvmw.address = vma_pgoff_address(pgoff, nr_pages, vma);
  946. VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
  947. return page_vma_mkclean_one(&pvmw);
  948. }
  949. /**
  950. * page_move_anon_rmap - move a page to our anon_vma
  951. * @page: the page to move to our anon_vma
  952. * @vma: the vma the page belongs to
  953. *
  954. * When a page belongs exclusively to one process after a COW event,
  955. * that page can be moved into the anon_vma that belongs to just that
  956. * process, so the rmap code will not search the parent or sibling
  957. * processes.
  958. */
  959. void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
  960. {
  961. void *anon_vma = vma->anon_vma;
  962. struct folio *folio = page_folio(page);
  963. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  964. VM_BUG_ON_VMA(!anon_vma, vma);
  965. anon_vma += PAGE_MAPPING_ANON;
  966. /*
  967. * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
  968. * simultaneously, so a concurrent reader (eg folio_referenced()'s
  969. * folio_test_anon()) will not see one without the other.
  970. */
  971. WRITE_ONCE(folio->mapping, anon_vma);
  972. SetPageAnonExclusive(page);
  973. }
  974. /**
  975. * __page_set_anon_rmap - set up new anonymous rmap
  976. * @page: Page or Hugepage to add to rmap
  977. * @vma: VM area to add page to.
  978. * @address: User virtual address of the mapping
  979. * @exclusive: the page is exclusively owned by the current process
  980. */
  981. static void __page_set_anon_rmap(struct page *page,
  982. struct vm_area_struct *vma, unsigned long address, int exclusive)
  983. {
  984. struct anon_vma *anon_vma = vma->anon_vma;
  985. BUG_ON(!anon_vma);
  986. if (PageAnon(page))
  987. goto out;
  988. /*
  989. * If the page isn't exclusively mapped into this vma,
  990. * we must use the _oldest_ possible anon_vma for the
  991. * page mapping!
  992. */
  993. if (!exclusive)
  994. anon_vma = anon_vma->root;
  995. /*
  996. * page_idle does a lockless/optimistic rmap scan on page->mapping.
  997. * Make sure the compiler doesn't split the stores of anon_vma and
  998. * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
  999. * could mistake the mapping for a struct address_space and crash.
  1000. */
  1001. anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
  1002. WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
  1003. page->index = linear_page_index(vma, address);
  1004. out:
  1005. if (exclusive)
  1006. SetPageAnonExclusive(page);
  1007. }
  1008. /**
  1009. * __page_check_anon_rmap - sanity check anonymous rmap addition
  1010. * @page: the page to add the mapping to
  1011. * @vma: the vm area in which the mapping is added
  1012. * @address: the user virtual address mapped
  1013. */
  1014. static void __page_check_anon_rmap(struct page *page,
  1015. struct vm_area_struct *vma, unsigned long address)
  1016. {
  1017. struct folio *folio = page_folio(page);
  1018. /*
  1019. * The page's anon-rmap details (mapping and index) are guaranteed to
  1020. * be set up correctly at this point.
  1021. *
  1022. * We have exclusion against page_add_anon_rmap because the caller
  1023. * always holds the page locked.
  1024. *
  1025. * We have exclusion against page_add_new_anon_rmap because those pages
  1026. * are initially only visible via the pagetables, and the pte is locked
  1027. * over the call to page_add_new_anon_rmap.
  1028. */
  1029. VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
  1030. folio);
  1031. VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
  1032. page);
  1033. }
  1034. /**
  1035. * page_add_anon_rmap - add pte mapping to an anonymous page
  1036. * @page: the page to add the mapping to
  1037. * @vma: the vm area in which the mapping is added
  1038. * @address: the user virtual address mapped
  1039. * @flags: the rmap flags
  1040. *
  1041. * The caller needs to hold the pte lock, and the page must be locked in
  1042. * the anon_vma case: to serialize mapping,index checking after setting,
  1043. * and to ensure that PageAnon is not being upgraded racily to PageKsm
  1044. * (but PageKsm is never downgraded to PageAnon).
  1045. */
  1046. void page_add_anon_rmap(struct page *page,
  1047. struct vm_area_struct *vma, unsigned long address, rmap_t flags)
  1048. {
  1049. bool compound = flags & RMAP_COMPOUND;
  1050. bool first;
  1051. if (unlikely(PageKsm(page)))
  1052. lock_page_memcg(page);
  1053. else
  1054. VM_BUG_ON_PAGE(!PageLocked(page), page);
  1055. if (compound) {
  1056. atomic_t *mapcount;
  1057. VM_BUG_ON_PAGE(!PageLocked(page), page);
  1058. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  1059. mapcount = compound_mapcount_ptr(page);
  1060. first = atomic_inc_and_test(mapcount);
  1061. } else {
  1062. first = atomic_inc_and_test(&page->_mapcount);
  1063. }
  1064. VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
  1065. VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
  1066. if (first) {
  1067. int nr = compound ? thp_nr_pages(page) : 1;
  1068. /*
  1069. * We use the irq-unsafe __{inc|mod}_zone_page_stat because
  1070. * these counters are not modified in interrupt context, and
  1071. * pte lock(a spinlock) is held, which implies preemption
  1072. * disabled.
  1073. */
  1074. if (compound)
  1075. __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
  1076. __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
  1077. }
  1078. if (unlikely(PageKsm(page)))
  1079. unlock_page_memcg(page);
  1080. /* address might be in next vma when migration races vma_adjust */
  1081. else if (first)
  1082. __page_set_anon_rmap(page, vma, address,
  1083. !!(flags & RMAP_EXCLUSIVE));
  1084. else
  1085. __page_check_anon_rmap(page, vma, address);
  1086. mlock_vma_page(page, vma, compound);
  1087. }
  1088. /**
  1089. * page_add_new_anon_rmap - add mapping to a new anonymous page
  1090. * @page: the page to add the mapping to
  1091. * @vma: the vm area in which the mapping is added
  1092. * @address: the user virtual address mapped
  1093. *
  1094. * If it's a compound page, it is accounted as a compound page. As the page
  1095. * is new, it's assume to get mapped exclusively by a single process.
  1096. *
  1097. * Same as page_add_anon_rmap but must only be called on *new* pages.
  1098. * This means the inc-and-test can be bypassed.
  1099. * Page does not have to be locked.
  1100. */
  1101. void page_add_new_anon_rmap(struct page *page,
  1102. struct vm_area_struct *vma, unsigned long address)
  1103. {
  1104. const bool compound = PageCompound(page);
  1105. int nr = compound ? thp_nr_pages(page) : 1;
  1106. VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
  1107. __SetPageSwapBacked(page);
  1108. if (compound) {
  1109. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  1110. /* increment count (starts at -1) */
  1111. atomic_set(compound_mapcount_ptr(page), 0);
  1112. atomic_set(compound_pincount_ptr(page), 0);
  1113. __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
  1114. } else {
  1115. /* increment count (starts at -1) */
  1116. atomic_set(&page->_mapcount, 0);
  1117. }
  1118. __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
  1119. __page_set_anon_rmap(page, vma, address, 1);
  1120. trace_android_vh_page_add_new_anon_rmap(page, vma, address);
  1121. }
  1122. /**
  1123. * page_add_file_rmap - add pte mapping to a file page
  1124. * @page: the page to add the mapping to
  1125. * @vma: the vm area in which the mapping is added
  1126. * @compound: charge the page as compound or small page
  1127. *
  1128. * The caller needs to hold the pte lock.
  1129. */
  1130. void page_add_file_rmap(struct page *page,
  1131. struct vm_area_struct *vma, bool compound)
  1132. {
  1133. int i, nr = 0;
  1134. VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
  1135. lock_page_memcg(page);
  1136. if (compound && PageTransHuge(page)) {
  1137. int nr_pages = thp_nr_pages(page);
  1138. for (i = 0; i < nr_pages; i++) {
  1139. if (atomic_inc_and_test(&page[i]._mapcount))
  1140. nr++;
  1141. }
  1142. if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
  1143. goto out;
  1144. /*
  1145. * It is racy to ClearPageDoubleMap in page_remove_file_rmap();
  1146. * but page lock is held by all page_add_file_rmap() compound
  1147. * callers, and SetPageDoubleMap below warns if !PageLocked:
  1148. * so here is a place that DoubleMap can be safely cleared.
  1149. */
  1150. VM_WARN_ON_ONCE(!PageLocked(page));
  1151. if (nr == nr_pages && PageDoubleMap(page))
  1152. ClearPageDoubleMap(page);
  1153. if (PageSwapBacked(page))
  1154. __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
  1155. nr_pages);
  1156. else
  1157. __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
  1158. nr_pages);
  1159. } else {
  1160. if (PageTransCompound(page) && page_mapping(page)) {
  1161. VM_WARN_ON_ONCE(!PageLocked(page));
  1162. SetPageDoubleMap(compound_head(page));
  1163. }
  1164. if (atomic_inc_and_test(&page->_mapcount))
  1165. nr++;
  1166. }
  1167. out:
  1168. if (nr)
  1169. __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
  1170. unlock_page_memcg(page);
  1171. mlock_vma_page(page, vma, compound);
  1172. }
  1173. static void page_remove_file_rmap(struct page *page, bool compound)
  1174. {
  1175. int i, nr = 0;
  1176. VM_BUG_ON_PAGE(compound && !PageHead(page), page);
  1177. /* Hugepages are not counted in NR_FILE_MAPPED for now. */
  1178. if (unlikely(PageHuge(page))) {
  1179. /* hugetlb pages are always mapped with pmds */
  1180. atomic_dec(compound_mapcount_ptr(page));
  1181. return;
  1182. }
  1183. /* page still mapped by someone else? */
  1184. if (compound && PageTransHuge(page)) {
  1185. int nr_pages = thp_nr_pages(page);
  1186. for (i = 0; i < nr_pages; i++) {
  1187. if (atomic_add_negative(-1, &page[i]._mapcount))
  1188. nr++;
  1189. }
  1190. if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
  1191. goto out;
  1192. if (PageSwapBacked(page))
  1193. __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
  1194. -nr_pages);
  1195. else
  1196. __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
  1197. -nr_pages);
  1198. } else {
  1199. if (atomic_add_negative(-1, &page->_mapcount))
  1200. nr++;
  1201. }
  1202. out:
  1203. if (nr)
  1204. __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
  1205. }
  1206. static void page_remove_anon_compound_rmap(struct page *page)
  1207. {
  1208. int i, nr;
  1209. if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
  1210. return;
  1211. /* Hugepages are not counted in NR_ANON_PAGES for now. */
  1212. if (unlikely(PageHuge(page)))
  1213. return;
  1214. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
  1215. return;
  1216. __mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
  1217. if (TestClearPageDoubleMap(page)) {
  1218. /*
  1219. * Subpages can be mapped with PTEs too. Check how many of
  1220. * them are still mapped.
  1221. */
  1222. for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
  1223. if (atomic_add_negative(-1, &page[i]._mapcount))
  1224. nr++;
  1225. }
  1226. /*
  1227. * Queue the page for deferred split if at least one small
  1228. * page of the compound page is unmapped, but at least one
  1229. * small page is still mapped.
  1230. */
  1231. if (nr && nr < thp_nr_pages(page))
  1232. deferred_split_huge_page(page);
  1233. } else {
  1234. nr = thp_nr_pages(page);
  1235. }
  1236. if (nr)
  1237. __mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
  1238. }
  1239. /**
  1240. * page_remove_rmap - take down pte mapping from a page
  1241. * @page: page to remove mapping from
  1242. * @vma: the vm area from which the mapping is removed
  1243. * @compound: uncharge the page as compound or small page
  1244. *
  1245. * The caller needs to hold the pte lock.
  1246. */
  1247. void page_remove_rmap(struct page *page,
  1248. struct vm_area_struct *vma, bool compound)
  1249. {
  1250. lock_page_memcg(page);
  1251. if (!PageAnon(page)) {
  1252. page_remove_file_rmap(page, compound);
  1253. goto out;
  1254. }
  1255. if (compound) {
  1256. page_remove_anon_compound_rmap(page);
  1257. goto out;
  1258. }
  1259. /* page still mapped by someone else? */
  1260. if (!atomic_add_negative(-1, &page->_mapcount))
  1261. goto out;
  1262. /*
  1263. * We use the irq-unsafe __{inc|mod}_zone_page_stat because
  1264. * these counters are not modified in interrupt context, and
  1265. * pte lock(a spinlock) is held, which implies preemption disabled.
  1266. */
  1267. __dec_lruvec_page_state(page, NR_ANON_MAPPED);
  1268. if (PageTransCompound(page))
  1269. deferred_split_huge_page(compound_head(page));
  1270. /*
  1271. * It would be tidy to reset the PageAnon mapping here,
  1272. * but that might overwrite a racing page_add_anon_rmap
  1273. * which increments mapcount after us but sets mapping
  1274. * before us: so leave the reset to free_unref_page,
  1275. * and remember that it's only reliable while mapped.
  1276. * Leaving it set also helps swapoff to reinstate ptes
  1277. * faster for those pages still in swapcache.
  1278. */
  1279. out:
  1280. unlock_page_memcg(page);
  1281. munlock_vma_page(page, vma, compound);
  1282. }
  1283. /*
  1284. * @arg: enum ttu_flags will be passed to this argument
  1285. */
  1286. static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
  1287. unsigned long address, void *arg)
  1288. {
  1289. struct mm_struct *mm = vma->vm_mm;
  1290. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  1291. pte_t pteval;
  1292. struct page *subpage;
  1293. bool anon_exclusive, ret = true;
  1294. struct mmu_notifier_range range;
  1295. enum ttu_flags flags = (enum ttu_flags)(long)arg;
  1296. /*
  1297. * When racing against e.g. zap_pte_range() on another cpu,
  1298. * in between its ptep_get_and_clear_full() and page_remove_rmap(),
  1299. * try_to_unmap() may return before page_mapped() has become false,
  1300. * if page table locking is skipped: use TTU_SYNC to wait for that.
  1301. */
  1302. if (flags & TTU_SYNC)
  1303. pvmw.flags = PVMW_SYNC;
  1304. if (flags & TTU_SPLIT_HUGE_PMD)
  1305. split_huge_pmd_address(vma, address, false, folio);
  1306. /*
  1307. * For THP, we have to assume the worse case ie pmd for invalidation.
  1308. * For hugetlb, it could be much worse if we need to do pud
  1309. * invalidation in the case of pmd sharing.
  1310. *
  1311. * Note that the folio can not be freed in this function as call of
  1312. * try_to_unmap() must hold a reference on the folio.
  1313. */
  1314. range.end = vma_address_end(&pvmw);
  1315. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
  1316. address, range.end);
  1317. if (folio_test_hugetlb(folio)) {
  1318. /*
  1319. * If sharing is possible, start and end will be adjusted
  1320. * accordingly.
  1321. */
  1322. adjust_range_if_pmd_sharing_possible(vma, &range.start,
  1323. &range.end);
  1324. }
  1325. mmu_notifier_invalidate_range_start(&range);
  1326. while (page_vma_mapped_walk(&pvmw)) {
  1327. /* Unexpected PMD-mapped THP? */
  1328. VM_BUG_ON_FOLIO(!pvmw.pte, folio);
  1329. /*
  1330. * If the folio is in an mlock()d vma, we must not swap it out.
  1331. */
  1332. if (!(flags & TTU_IGNORE_MLOCK) &&
  1333. (vma->vm_flags & VM_LOCKED)) {
  1334. /* Restore the mlock which got missed */
  1335. mlock_vma_folio(folio, vma, false);
  1336. page_vma_mapped_walk_done(&pvmw);
  1337. ret = false;
  1338. break;
  1339. }
  1340. subpage = folio_page(folio,
  1341. pte_pfn(*pvmw.pte) - folio_pfn(folio));
  1342. address = pvmw.address;
  1343. anon_exclusive = folio_test_anon(folio) &&
  1344. PageAnonExclusive(subpage);
  1345. if (folio_test_hugetlb(folio)) {
  1346. bool anon = folio_test_anon(folio);
  1347. /*
  1348. * The try_to_unmap() is only passed a hugetlb page
  1349. * in the case where the hugetlb page is poisoned.
  1350. */
  1351. VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
  1352. /*
  1353. * huge_pmd_unshare may unmap an entire PMD page.
  1354. * There is no way of knowing exactly which PMDs may
  1355. * be cached for this mm, so we must flush them all.
  1356. * start/end were already adjusted above to cover this
  1357. * range.
  1358. */
  1359. flush_cache_range(vma, range.start, range.end);
  1360. /*
  1361. * To call huge_pmd_unshare, i_mmap_rwsem must be
  1362. * held in write mode. Caller needs to explicitly
  1363. * do this outside rmap routines.
  1364. *
  1365. * We also must hold hugetlb vma_lock in write mode.
  1366. * Lock order dictates acquiring vma_lock BEFORE
  1367. * i_mmap_rwsem. We can only try lock here and fail
  1368. * if unsuccessful.
  1369. */
  1370. if (!anon) {
  1371. VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
  1372. if (!hugetlb_vma_trylock_write(vma)) {
  1373. page_vma_mapped_walk_done(&pvmw);
  1374. ret = false;
  1375. break;
  1376. }
  1377. if (huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
  1378. hugetlb_vma_unlock_write(vma);
  1379. flush_tlb_range(vma,
  1380. range.start, range.end);
  1381. mmu_notifier_invalidate_range(mm,
  1382. range.start, range.end);
  1383. /*
  1384. * The ref count of the PMD page was
  1385. * dropped which is part of the way map
  1386. * counting is done for shared PMDs.
  1387. * Return 'true' here. When there is
  1388. * no other sharing, huge_pmd_unshare
  1389. * returns false and we will unmap the
  1390. * actual page and drop map count
  1391. * to zero.
  1392. */
  1393. page_vma_mapped_walk_done(&pvmw);
  1394. break;
  1395. }
  1396. hugetlb_vma_unlock_write(vma);
  1397. }
  1398. pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
  1399. } else {
  1400. flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
  1401. /* Nuke the page table entry. */
  1402. if (should_defer_flush(mm, flags)) {
  1403. /*
  1404. * We clear the PTE but do not flush so potentially
  1405. * a remote CPU could still be writing to the folio.
  1406. * If the entry was previously clean then the
  1407. * architecture must guarantee that a clear->dirty
  1408. * transition on a cached TLB entry is written through
  1409. * and traps if the PTE is unmapped.
  1410. */
  1411. pteval = ptep_get_and_clear(mm, address, pvmw.pte);
  1412. set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
  1413. } else {
  1414. pteval = ptep_clear_flush(vma, address, pvmw.pte);
  1415. }
  1416. }
  1417. /*
  1418. * Now the pte is cleared. If this pte was uffd-wp armed,
  1419. * we may want to replace a none pte with a marker pte if
  1420. * it's file-backed, so we don't lose the tracking info.
  1421. */
  1422. pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
  1423. /* Set the dirty flag on the folio now the pte is gone. */
  1424. if (pte_dirty(pteval))
  1425. folio_mark_dirty(folio);
  1426. /* Update high watermark before we lower rss */
  1427. update_hiwater_rss(mm);
  1428. if (PageHWPoison(subpage) && (flags & TTU_HWPOISON)) {
  1429. pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
  1430. if (folio_test_hugetlb(folio)) {
  1431. hugetlb_count_sub(folio_nr_pages(folio), mm);
  1432. set_huge_pte_at(mm, address, pvmw.pte, pteval);
  1433. } else {
  1434. dec_mm_counter(mm, mm_counter(&folio->page));
  1435. set_pte_at(mm, address, pvmw.pte, pteval);
  1436. }
  1437. } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
  1438. /*
  1439. * The guest indicated that the page content is of no
  1440. * interest anymore. Simply discard the pte, vmscan
  1441. * will take care of the rest.
  1442. * A future reference will then fault in a new zero
  1443. * page. When userfaultfd is active, we must not drop
  1444. * this page though, as its main user (postcopy
  1445. * migration) will not expect userfaults on already
  1446. * copied pages.
  1447. */
  1448. dec_mm_counter(mm, mm_counter(&folio->page));
  1449. /* We have to invalidate as we cleared the pte */
  1450. mmu_notifier_invalidate_range(mm, address,
  1451. address + PAGE_SIZE);
  1452. } else if (folio_test_anon(folio)) {
  1453. swp_entry_t entry = { .val = page_private(subpage) };
  1454. pte_t swp_pte;
  1455. /*
  1456. * Store the swap location in the pte.
  1457. * See handle_pte_fault() ...
  1458. */
  1459. if (unlikely(folio_test_swapbacked(folio) !=
  1460. folio_test_swapcache(folio))) {
  1461. WARN_ON_ONCE(1);
  1462. ret = false;
  1463. /* We have to invalidate as we cleared the pte */
  1464. mmu_notifier_invalidate_range(mm, address,
  1465. address + PAGE_SIZE);
  1466. page_vma_mapped_walk_done(&pvmw);
  1467. break;
  1468. }
  1469. /* MADV_FREE page check */
  1470. if (!folio_test_swapbacked(folio)) {
  1471. int ref_count, map_count;
  1472. /*
  1473. * Synchronize with gup_pte_range():
  1474. * - clear PTE; barrier; read refcount
  1475. * - inc refcount; barrier; read PTE
  1476. */
  1477. smp_mb();
  1478. ref_count = folio_ref_count(folio);
  1479. map_count = folio_mapcount(folio);
  1480. /*
  1481. * Order reads for page refcount and dirty flag
  1482. * (see comments in __remove_mapping()).
  1483. */
  1484. smp_rmb();
  1485. /*
  1486. * The only page refs must be one from isolation
  1487. * plus the rmap(s) (dropped by discard:).
  1488. */
  1489. if (ref_count == 1 + map_count &&
  1490. !folio_test_dirty(folio)) {
  1491. /* Invalidate as we cleared the pte */
  1492. mmu_notifier_invalidate_range(mm,
  1493. address, address + PAGE_SIZE);
  1494. dec_mm_counter(mm, MM_ANONPAGES);
  1495. goto discard;
  1496. }
  1497. /*
  1498. * If the folio was redirtied, it cannot be
  1499. * discarded. Remap the page to page table.
  1500. */
  1501. set_pte_at(mm, address, pvmw.pte, pteval);
  1502. folio_set_swapbacked(folio);
  1503. ret = false;
  1504. page_vma_mapped_walk_done(&pvmw);
  1505. break;
  1506. }
  1507. if (swap_duplicate(entry) < 0) {
  1508. set_pte_at(mm, address, pvmw.pte, pteval);
  1509. ret = false;
  1510. page_vma_mapped_walk_done(&pvmw);
  1511. break;
  1512. }
  1513. if (arch_unmap_one(mm, vma, address, pteval) < 0) {
  1514. swap_free(entry);
  1515. set_pte_at(mm, address, pvmw.pte, pteval);
  1516. ret = false;
  1517. page_vma_mapped_walk_done(&pvmw);
  1518. break;
  1519. }
  1520. /* See page_try_share_anon_rmap(): clear PTE first. */
  1521. if (anon_exclusive &&
  1522. page_try_share_anon_rmap(subpage)) {
  1523. swap_free(entry);
  1524. set_pte_at(mm, address, pvmw.pte, pteval);
  1525. ret = false;
  1526. page_vma_mapped_walk_done(&pvmw);
  1527. break;
  1528. }
  1529. /*
  1530. * Note: We *don't* remember if the page was mapped
  1531. * exclusively in the swap pte if the architecture
  1532. * doesn't support __HAVE_ARCH_PTE_SWP_EXCLUSIVE. In
  1533. * that case, swapin code has to re-determine that
  1534. * manually and might detect the page as possibly
  1535. * shared, for example, if there are other references on
  1536. * the page or if the page is under writeback. We made
  1537. * sure that there are no GUP pins on the page that
  1538. * would rely on it, so for GUP pins this is fine.
  1539. */
  1540. if (list_empty(&mm->mmlist)) {
  1541. spin_lock(&mmlist_lock);
  1542. if (list_empty(&mm->mmlist))
  1543. list_add(&mm->mmlist, &init_mm.mmlist);
  1544. spin_unlock(&mmlist_lock);
  1545. }
  1546. dec_mm_counter(mm, MM_ANONPAGES);
  1547. inc_mm_counter(mm, MM_SWAPENTS);
  1548. swp_pte = swp_entry_to_pte(entry);
  1549. if (anon_exclusive)
  1550. swp_pte = pte_swp_mkexclusive(swp_pte);
  1551. if (pte_soft_dirty(pteval))
  1552. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  1553. if (pte_uffd_wp(pteval))
  1554. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  1555. set_pte_at(mm, address, pvmw.pte, swp_pte);
  1556. /* Invalidate as we cleared the pte */
  1557. mmu_notifier_invalidate_range(mm, address,
  1558. address + PAGE_SIZE);
  1559. } else {
  1560. /*
  1561. * This is a locked file-backed folio,
  1562. * so it cannot be removed from the page
  1563. * cache and replaced by a new folio before
  1564. * mmu_notifier_invalidate_range_end, so no
  1565. * concurrent thread might update its page table
  1566. * to point at a new folio while a device is
  1567. * still using this folio.
  1568. *
  1569. * See Documentation/mm/mmu_notifier.rst
  1570. */
  1571. dec_mm_counter(mm, mm_counter_file(&folio->page));
  1572. }
  1573. discard:
  1574. /*
  1575. * No need to call mmu_notifier_invalidate_range() it has be
  1576. * done above for all cases requiring it to happen under page
  1577. * table lock before mmu_notifier_invalidate_range_end()
  1578. *
  1579. * See Documentation/mm/mmu_notifier.rst
  1580. */
  1581. page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
  1582. if (vma->vm_flags & VM_LOCKED)
  1583. mlock_page_drain_local();
  1584. folio_put(folio);
  1585. }
  1586. mmu_notifier_invalidate_range_end(&range);
  1587. trace_android_vh_try_to_unmap_one(folio, vma, address, arg, ret);
  1588. return ret;
  1589. }
  1590. static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
  1591. {
  1592. return vma_is_temporary_stack(vma);
  1593. }
  1594. static int page_not_mapped(struct folio *folio)
  1595. {
  1596. return !folio_mapped(folio);
  1597. }
  1598. /**
  1599. * try_to_unmap - Try to remove all page table mappings to a folio.
  1600. * @folio: The folio to unmap.
  1601. * @flags: action and flags
  1602. *
  1603. * Tries to remove all the page table entries which are mapping this
  1604. * folio. It is the caller's responsibility to check if the folio is
  1605. * still mapped if needed (use TTU_SYNC to prevent accounting races).
  1606. *
  1607. * Context: Caller must hold the folio lock.
  1608. */
  1609. void try_to_unmap(struct folio *folio, enum ttu_flags flags)
  1610. {
  1611. struct rmap_walk_control rwc = {
  1612. .rmap_one = try_to_unmap_one,
  1613. .arg = (void *)flags,
  1614. .done = page_not_mapped,
  1615. .anon_lock = folio_lock_anon_vma_read,
  1616. };
  1617. if (flags & TTU_RMAP_LOCKED)
  1618. rmap_walk_locked(folio, &rwc);
  1619. else
  1620. rmap_walk(folio, &rwc);
  1621. }
  1622. /*
  1623. * @arg: enum ttu_flags will be passed to this argument.
  1624. *
  1625. * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
  1626. * containing migration entries.
  1627. */
  1628. static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
  1629. unsigned long address, void *arg)
  1630. {
  1631. struct mm_struct *mm = vma->vm_mm;
  1632. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  1633. pte_t pteval;
  1634. struct page *subpage;
  1635. bool anon_exclusive, ret = true;
  1636. struct mmu_notifier_range range;
  1637. enum ttu_flags flags = (enum ttu_flags)(long)arg;
  1638. /*
  1639. * When racing against e.g. zap_pte_range() on another cpu,
  1640. * in between its ptep_get_and_clear_full() and page_remove_rmap(),
  1641. * try_to_migrate() may return before page_mapped() has become false,
  1642. * if page table locking is skipped: use TTU_SYNC to wait for that.
  1643. */
  1644. if (flags & TTU_SYNC)
  1645. pvmw.flags = PVMW_SYNC;
  1646. /*
  1647. * unmap_page() in mm/huge_memory.c is the only user of migration with
  1648. * TTU_SPLIT_HUGE_PMD and it wants to freeze.
  1649. */
  1650. if (flags & TTU_SPLIT_HUGE_PMD)
  1651. split_huge_pmd_address(vma, address, true, folio);
  1652. /*
  1653. * For THP, we have to assume the worse case ie pmd for invalidation.
  1654. * For hugetlb, it could be much worse if we need to do pud
  1655. * invalidation in the case of pmd sharing.
  1656. *
  1657. * Note that the page can not be free in this function as call of
  1658. * try_to_unmap() must hold a reference on the page.
  1659. */
  1660. range.end = vma_address_end(&pvmw);
  1661. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
  1662. address, range.end);
  1663. if (folio_test_hugetlb(folio)) {
  1664. /*
  1665. * If sharing is possible, start and end will be adjusted
  1666. * accordingly.
  1667. */
  1668. adjust_range_if_pmd_sharing_possible(vma, &range.start,
  1669. &range.end);
  1670. }
  1671. mmu_notifier_invalidate_range_start(&range);
  1672. while (page_vma_mapped_walk(&pvmw)) {
  1673. #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
  1674. /* PMD-mapped THP migration entry */
  1675. if (!pvmw.pte) {
  1676. subpage = folio_page(folio,
  1677. pmd_pfn(*pvmw.pmd) - folio_pfn(folio));
  1678. VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
  1679. !folio_test_pmd_mappable(folio), folio);
  1680. if (set_pmd_migration_entry(&pvmw, subpage)) {
  1681. ret = false;
  1682. page_vma_mapped_walk_done(&pvmw);
  1683. break;
  1684. }
  1685. continue;
  1686. }
  1687. #endif
  1688. /* Unexpected PMD-mapped THP? */
  1689. VM_BUG_ON_FOLIO(!pvmw.pte, folio);
  1690. if (folio_is_zone_device(folio)) {
  1691. /*
  1692. * Our PTE is a non-present device exclusive entry and
  1693. * calculating the subpage as for the common case would
  1694. * result in an invalid pointer.
  1695. *
  1696. * Since only PAGE_SIZE pages can currently be
  1697. * migrated, just set it to page. This will need to be
  1698. * changed when hugepage migrations to device private
  1699. * memory are supported.
  1700. */
  1701. VM_BUG_ON_FOLIO(folio_nr_pages(folio) > 1, folio);
  1702. subpage = &folio->page;
  1703. } else {
  1704. subpage = folio_page(folio,
  1705. pte_pfn(*pvmw.pte) - folio_pfn(folio));
  1706. }
  1707. address = pvmw.address;
  1708. anon_exclusive = folio_test_anon(folio) &&
  1709. PageAnonExclusive(subpage);
  1710. if (folio_test_hugetlb(folio)) {
  1711. bool anon = folio_test_anon(folio);
  1712. /*
  1713. * huge_pmd_unshare may unmap an entire PMD page.
  1714. * There is no way of knowing exactly which PMDs may
  1715. * be cached for this mm, so we must flush them all.
  1716. * start/end were already adjusted above to cover this
  1717. * range.
  1718. */
  1719. flush_cache_range(vma, range.start, range.end);
  1720. /*
  1721. * To call huge_pmd_unshare, i_mmap_rwsem must be
  1722. * held in write mode. Caller needs to explicitly
  1723. * do this outside rmap routines.
  1724. *
  1725. * We also must hold hugetlb vma_lock in write mode.
  1726. * Lock order dictates acquiring vma_lock BEFORE
  1727. * i_mmap_rwsem. We can only try lock here and
  1728. * fail if unsuccessful.
  1729. */
  1730. if (!anon) {
  1731. VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
  1732. if (!hugetlb_vma_trylock_write(vma)) {
  1733. page_vma_mapped_walk_done(&pvmw);
  1734. ret = false;
  1735. break;
  1736. }
  1737. if (huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
  1738. hugetlb_vma_unlock_write(vma);
  1739. flush_tlb_range(vma,
  1740. range.start, range.end);
  1741. mmu_notifier_invalidate_range(mm,
  1742. range.start, range.end);
  1743. /*
  1744. * The ref count of the PMD page was
  1745. * dropped which is part of the way map
  1746. * counting is done for shared PMDs.
  1747. * Return 'true' here. When there is
  1748. * no other sharing, huge_pmd_unshare
  1749. * returns false and we will unmap the
  1750. * actual page and drop map count
  1751. * to zero.
  1752. */
  1753. page_vma_mapped_walk_done(&pvmw);
  1754. break;
  1755. }
  1756. hugetlb_vma_unlock_write(vma);
  1757. }
  1758. /* Nuke the hugetlb page table entry */
  1759. pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
  1760. } else {
  1761. flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
  1762. /* Nuke the page table entry. */
  1763. pteval = ptep_clear_flush(vma, address, pvmw.pte);
  1764. }
  1765. /* Set the dirty flag on the folio now the pte is gone. */
  1766. if (pte_dirty(pteval))
  1767. folio_mark_dirty(folio);
  1768. /* Update high watermark before we lower rss */
  1769. update_hiwater_rss(mm);
  1770. if (folio_is_device_private(folio)) {
  1771. unsigned long pfn = folio_pfn(folio);
  1772. swp_entry_t entry;
  1773. pte_t swp_pte;
  1774. if (anon_exclusive)
  1775. BUG_ON(page_try_share_anon_rmap(subpage));
  1776. /*
  1777. * Store the pfn of the page in a special migration
  1778. * pte. do_swap_page() will wait until the migration
  1779. * pte is removed and then restart fault handling.
  1780. */
  1781. entry = pte_to_swp_entry(pteval);
  1782. if (is_writable_device_private_entry(entry))
  1783. entry = make_writable_migration_entry(pfn);
  1784. else if (anon_exclusive)
  1785. entry = make_readable_exclusive_migration_entry(pfn);
  1786. else
  1787. entry = make_readable_migration_entry(pfn);
  1788. swp_pte = swp_entry_to_pte(entry);
  1789. /*
  1790. * pteval maps a zone device page and is therefore
  1791. * a swap pte.
  1792. */
  1793. if (pte_swp_soft_dirty(pteval))
  1794. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  1795. if (pte_swp_uffd_wp(pteval))
  1796. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  1797. set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
  1798. trace_set_migration_pte(pvmw.address, pte_val(swp_pte),
  1799. compound_order(&folio->page));
  1800. /*
  1801. * No need to invalidate here it will synchronize on
  1802. * against the special swap migration pte.
  1803. */
  1804. } else if (PageHWPoison(subpage)) {
  1805. pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
  1806. if (folio_test_hugetlb(folio)) {
  1807. hugetlb_count_sub(folio_nr_pages(folio), mm);
  1808. set_huge_pte_at(mm, address, pvmw.pte, pteval);
  1809. } else {
  1810. dec_mm_counter(mm, mm_counter(&folio->page));
  1811. set_pte_at(mm, address, pvmw.pte, pteval);
  1812. }
  1813. } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
  1814. /*
  1815. * The guest indicated that the page content is of no
  1816. * interest anymore. Simply discard the pte, vmscan
  1817. * will take care of the rest.
  1818. * A future reference will then fault in a new zero
  1819. * page. When userfaultfd is active, we must not drop
  1820. * this page though, as its main user (postcopy
  1821. * migration) will not expect userfaults on already
  1822. * copied pages.
  1823. */
  1824. dec_mm_counter(mm, mm_counter(&folio->page));
  1825. /* We have to invalidate as we cleared the pte */
  1826. mmu_notifier_invalidate_range(mm, address,
  1827. address + PAGE_SIZE);
  1828. } else {
  1829. swp_entry_t entry;
  1830. pte_t swp_pte;
  1831. if (arch_unmap_one(mm, vma, address, pteval) < 0) {
  1832. if (folio_test_hugetlb(folio))
  1833. set_huge_pte_at(mm, address, pvmw.pte, pteval);
  1834. else
  1835. set_pte_at(mm, address, pvmw.pte, pteval);
  1836. ret = false;
  1837. page_vma_mapped_walk_done(&pvmw);
  1838. break;
  1839. }
  1840. VM_BUG_ON_PAGE(pte_write(pteval) && folio_test_anon(folio) &&
  1841. !anon_exclusive, subpage);
  1842. /* See page_try_share_anon_rmap(): clear PTE first. */
  1843. if (anon_exclusive &&
  1844. page_try_share_anon_rmap(subpage)) {
  1845. if (folio_test_hugetlb(folio))
  1846. set_huge_pte_at(mm, address, pvmw.pte, pteval);
  1847. else
  1848. set_pte_at(mm, address, pvmw.pte, pteval);
  1849. ret = false;
  1850. page_vma_mapped_walk_done(&pvmw);
  1851. break;
  1852. }
  1853. /*
  1854. * Store the pfn of the page in a special migration
  1855. * pte. do_swap_page() will wait until the migration
  1856. * pte is removed and then restart fault handling.
  1857. */
  1858. if (pte_write(pteval))
  1859. entry = make_writable_migration_entry(
  1860. page_to_pfn(subpage));
  1861. else if (anon_exclusive)
  1862. entry = make_readable_exclusive_migration_entry(
  1863. page_to_pfn(subpage));
  1864. else
  1865. entry = make_readable_migration_entry(
  1866. page_to_pfn(subpage));
  1867. if (pte_young(pteval))
  1868. entry = make_migration_entry_young(entry);
  1869. if (pte_dirty(pteval))
  1870. entry = make_migration_entry_dirty(entry);
  1871. swp_pte = swp_entry_to_pte(entry);
  1872. if (pte_soft_dirty(pteval))
  1873. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  1874. if (pte_uffd_wp(pteval))
  1875. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  1876. if (folio_test_hugetlb(folio))
  1877. set_huge_pte_at(mm, address, pvmw.pte, swp_pte);
  1878. else
  1879. set_pte_at(mm, address, pvmw.pte, swp_pte);
  1880. trace_set_migration_pte(address, pte_val(swp_pte),
  1881. compound_order(&folio->page));
  1882. /*
  1883. * No need to invalidate here it will synchronize on
  1884. * against the special swap migration pte.
  1885. */
  1886. }
  1887. /*
  1888. * No need to call mmu_notifier_invalidate_range() it has be
  1889. * done above for all cases requiring it to happen under page
  1890. * table lock before mmu_notifier_invalidate_range_end()
  1891. *
  1892. * See Documentation/mm/mmu_notifier.rst
  1893. */
  1894. page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
  1895. if (vma->vm_flags & VM_LOCKED)
  1896. mlock_page_drain_local();
  1897. folio_put(folio);
  1898. }
  1899. mmu_notifier_invalidate_range_end(&range);
  1900. return ret;
  1901. }
  1902. /**
  1903. * try_to_migrate - try to replace all page table mappings with swap entries
  1904. * @folio: the folio to replace page table entries for
  1905. * @flags: action and flags
  1906. *
  1907. * Tries to remove all the page table entries which are mapping this folio and
  1908. * replace them with special swap entries. Caller must hold the folio lock.
  1909. */
  1910. void try_to_migrate(struct folio *folio, enum ttu_flags flags)
  1911. {
  1912. struct rmap_walk_control rwc = {
  1913. .rmap_one = try_to_migrate_one,
  1914. .arg = (void *)flags,
  1915. .done = page_not_mapped,
  1916. .anon_lock = folio_lock_anon_vma_read,
  1917. };
  1918. /*
  1919. * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
  1920. * TTU_SPLIT_HUGE_PMD and TTU_SYNC flags.
  1921. */
  1922. if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
  1923. TTU_SYNC)))
  1924. return;
  1925. if (folio_is_zone_device(folio) &&
  1926. (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
  1927. return;
  1928. /*
  1929. * During exec, a temporary VMA is setup and later moved.
  1930. * The VMA is moved under the anon_vma lock but not the
  1931. * page tables leading to a race where migration cannot
  1932. * find the migration ptes. Rather than increasing the
  1933. * locking requirements of exec(), migration skips
  1934. * temporary VMAs until after exec() completes.
  1935. */
  1936. if (!folio_test_ksm(folio) && folio_test_anon(folio))
  1937. rwc.invalid_vma = invalid_migration_vma;
  1938. if (flags & TTU_RMAP_LOCKED)
  1939. rmap_walk_locked(folio, &rwc);
  1940. else
  1941. rmap_walk(folio, &rwc);
  1942. }
  1943. #ifdef CONFIG_DEVICE_PRIVATE
  1944. struct make_exclusive_args {
  1945. struct mm_struct *mm;
  1946. unsigned long address;
  1947. void *owner;
  1948. bool valid;
  1949. };
  1950. static bool page_make_device_exclusive_one(struct folio *folio,
  1951. struct vm_area_struct *vma, unsigned long address, void *priv)
  1952. {
  1953. struct mm_struct *mm = vma->vm_mm;
  1954. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
  1955. struct make_exclusive_args *args = priv;
  1956. pte_t pteval;
  1957. struct page *subpage;
  1958. bool ret = true;
  1959. struct mmu_notifier_range range;
  1960. swp_entry_t entry;
  1961. pte_t swp_pte;
  1962. mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
  1963. vma->vm_mm, address, min(vma->vm_end,
  1964. address + folio_size(folio)),
  1965. args->owner);
  1966. mmu_notifier_invalidate_range_start(&range);
  1967. while (page_vma_mapped_walk(&pvmw)) {
  1968. /* Unexpected PMD-mapped THP? */
  1969. VM_BUG_ON_FOLIO(!pvmw.pte, folio);
  1970. if (!pte_present(*pvmw.pte)) {
  1971. ret = false;
  1972. page_vma_mapped_walk_done(&pvmw);
  1973. break;
  1974. }
  1975. subpage = folio_page(folio,
  1976. pte_pfn(*pvmw.pte) - folio_pfn(folio));
  1977. address = pvmw.address;
  1978. /* Nuke the page table entry. */
  1979. flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
  1980. pteval = ptep_clear_flush(vma, address, pvmw.pte);
  1981. /* Set the dirty flag on the folio now the pte is gone. */
  1982. if (pte_dirty(pteval))
  1983. folio_mark_dirty(folio);
  1984. /*
  1985. * Check that our target page is still mapped at the expected
  1986. * address.
  1987. */
  1988. if (args->mm == mm && args->address == address &&
  1989. pte_write(pteval))
  1990. args->valid = true;
  1991. /*
  1992. * Store the pfn of the page in a special migration
  1993. * pte. do_swap_page() will wait until the migration
  1994. * pte is removed and then restart fault handling.
  1995. */
  1996. if (pte_write(pteval))
  1997. entry = make_writable_device_exclusive_entry(
  1998. page_to_pfn(subpage));
  1999. else
  2000. entry = make_readable_device_exclusive_entry(
  2001. page_to_pfn(subpage));
  2002. swp_pte = swp_entry_to_pte(entry);
  2003. if (pte_soft_dirty(pteval))
  2004. swp_pte = pte_swp_mksoft_dirty(swp_pte);
  2005. if (pte_uffd_wp(pteval))
  2006. swp_pte = pte_swp_mkuffd_wp(swp_pte);
  2007. set_pte_at(mm, address, pvmw.pte, swp_pte);
  2008. /*
  2009. * There is a reference on the page for the swap entry which has
  2010. * been removed, so shouldn't take another.
  2011. */
  2012. page_remove_rmap(subpage, vma, false);
  2013. }
  2014. mmu_notifier_invalidate_range_end(&range);
  2015. return ret;
  2016. }
  2017. /**
  2018. * folio_make_device_exclusive - Mark the folio exclusively owned by a device.
  2019. * @folio: The folio to replace page table entries for.
  2020. * @mm: The mm_struct where the folio is expected to be mapped.
  2021. * @address: Address where the folio is expected to be mapped.
  2022. * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
  2023. *
  2024. * Tries to remove all the page table entries which are mapping this
  2025. * folio and replace them with special device exclusive swap entries to
  2026. * grant a device exclusive access to the folio.
  2027. *
  2028. * Context: Caller must hold the folio lock.
  2029. * Return: false if the page is still mapped, or if it could not be unmapped
  2030. * from the expected address. Otherwise returns true (success).
  2031. */
  2032. static bool folio_make_device_exclusive(struct folio *folio,
  2033. struct mm_struct *mm, unsigned long address, void *owner)
  2034. {
  2035. struct make_exclusive_args args = {
  2036. .mm = mm,
  2037. .address = address,
  2038. .owner = owner,
  2039. .valid = false,
  2040. };
  2041. struct rmap_walk_control rwc = {
  2042. .rmap_one = page_make_device_exclusive_one,
  2043. .done = page_not_mapped,
  2044. .anon_lock = folio_lock_anon_vma_read,
  2045. .arg = &args,
  2046. };
  2047. /*
  2048. * Restrict to anonymous folios for now to avoid potential writeback
  2049. * issues.
  2050. */
  2051. if (!folio_test_anon(folio))
  2052. return false;
  2053. rmap_walk(folio, &rwc);
  2054. return args.valid && !folio_mapcount(folio);
  2055. }
  2056. /**
  2057. * make_device_exclusive_range() - Mark a range for exclusive use by a device
  2058. * @mm: mm_struct of associated target process
  2059. * @start: start of the region to mark for exclusive device access
  2060. * @end: end address of region
  2061. * @pages: returns the pages which were successfully marked for exclusive access
  2062. * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
  2063. *
  2064. * Returns: number of pages found in the range by GUP. A page is marked for
  2065. * exclusive access only if the page pointer is non-NULL.
  2066. *
  2067. * This function finds ptes mapping page(s) to the given address range, locks
  2068. * them and replaces mappings with special swap entries preventing userspace CPU
  2069. * access. On fault these entries are replaced with the original mapping after
  2070. * calling MMU notifiers.
  2071. *
  2072. * A driver using this to program access from a device must use a mmu notifier
  2073. * critical section to hold a device specific lock during programming. Once
  2074. * programming is complete it should drop the page lock and reference after
  2075. * which point CPU access to the page will revoke the exclusive access.
  2076. */
  2077. int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
  2078. unsigned long end, struct page **pages,
  2079. void *owner)
  2080. {
  2081. long npages = (end - start) >> PAGE_SHIFT;
  2082. long i;
  2083. npages = get_user_pages_remote(mm, start, npages,
  2084. FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
  2085. pages, NULL, NULL);
  2086. if (npages < 0)
  2087. return npages;
  2088. for (i = 0; i < npages; i++, start += PAGE_SIZE) {
  2089. struct folio *folio = page_folio(pages[i]);
  2090. if (PageTail(pages[i]) || !folio_trylock(folio)) {
  2091. folio_put(folio);
  2092. pages[i] = NULL;
  2093. continue;
  2094. }
  2095. if (!folio_make_device_exclusive(folio, mm, start, owner)) {
  2096. folio_unlock(folio);
  2097. folio_put(folio);
  2098. pages[i] = NULL;
  2099. }
  2100. }
  2101. return npages;
  2102. }
  2103. EXPORT_SYMBOL_GPL(make_device_exclusive_range);
  2104. #endif
  2105. void __put_anon_vma(struct anon_vma *anon_vma)
  2106. {
  2107. struct anon_vma *root = anon_vma->root;
  2108. anon_vma_free(anon_vma);
  2109. if (root != anon_vma && atomic_dec_and_test(&root->refcount))
  2110. anon_vma_free(root);
  2111. }
  2112. static struct anon_vma *rmap_walk_anon_lock(struct folio *folio,
  2113. struct rmap_walk_control *rwc)
  2114. {
  2115. struct anon_vma *anon_vma;
  2116. if (rwc->anon_lock)
  2117. return rwc->anon_lock(folio, rwc);
  2118. /*
  2119. * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
  2120. * because that depends on page_mapped(); but not all its usages
  2121. * are holding mmap_lock. Users without mmap_lock are required to
  2122. * take a reference count to prevent the anon_vma disappearing
  2123. */
  2124. anon_vma = folio_anon_vma(folio);
  2125. if (!anon_vma)
  2126. return NULL;
  2127. if (anon_vma_trylock_read(anon_vma))
  2128. goto out;
  2129. if (rwc->try_lock) {
  2130. anon_vma = NULL;
  2131. rwc->contended = true;
  2132. goto out;
  2133. }
  2134. anon_vma_lock_read(anon_vma);
  2135. out:
  2136. return anon_vma;
  2137. }
  2138. /*
  2139. * rmap_walk_anon - do something to anonymous page using the object-based
  2140. * rmap method
  2141. * @page: the page to be handled
  2142. * @rwc: control variable according to each walk type
  2143. *
  2144. * Find all the mappings of a page using the mapping pointer and the vma chains
  2145. * contained in the anon_vma struct it points to.
  2146. */
  2147. static void rmap_walk_anon(struct folio *folio,
  2148. struct rmap_walk_control *rwc, bool locked)
  2149. {
  2150. struct anon_vma *anon_vma;
  2151. pgoff_t pgoff_start, pgoff_end;
  2152. struct anon_vma_chain *avc;
  2153. if (locked) {
  2154. anon_vma = folio_anon_vma(folio);
  2155. /* anon_vma disappear under us? */
  2156. VM_BUG_ON_FOLIO(!anon_vma, folio);
  2157. } else {
  2158. anon_vma = rmap_walk_anon_lock(folio, rwc);
  2159. }
  2160. if (!anon_vma)
  2161. return;
  2162. pgoff_start = folio_pgoff(folio);
  2163. pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
  2164. anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
  2165. pgoff_start, pgoff_end) {
  2166. struct vm_area_struct *vma = avc->vma;
  2167. unsigned long address = vma_address(&folio->page, vma);
  2168. VM_BUG_ON_VMA(address == -EFAULT, vma);
  2169. cond_resched();
  2170. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2171. continue;
  2172. if (!rwc->rmap_one(folio, vma, address, rwc->arg))
  2173. break;
  2174. if (rwc->done && rwc->done(folio))
  2175. break;
  2176. }
  2177. if (!locked)
  2178. anon_vma_unlock_read(anon_vma);
  2179. }
  2180. /*
  2181. * rmap_walk_file - do something to file page using the object-based rmap method
  2182. * @page: the page to be handled
  2183. * @rwc: control variable according to each walk type
  2184. *
  2185. * Find all the mappings of a page using the mapping pointer and the vma chains
  2186. * contained in the address_space struct it points to.
  2187. */
  2188. static void rmap_walk_file(struct folio *folio,
  2189. struct rmap_walk_control *rwc, bool locked)
  2190. {
  2191. struct address_space *mapping = folio_mapping(folio);
  2192. pgoff_t pgoff_start, pgoff_end;
  2193. struct vm_area_struct *vma;
  2194. /*
  2195. * The page lock not only makes sure that page->mapping cannot
  2196. * suddenly be NULLified by truncation, it makes sure that the
  2197. * structure at mapping cannot be freed and reused yet,
  2198. * so we can safely take mapping->i_mmap_rwsem.
  2199. */
  2200. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2201. if (!mapping)
  2202. return;
  2203. pgoff_start = folio_pgoff(folio);
  2204. pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
  2205. if (!locked) {
  2206. if (i_mmap_trylock_read(mapping))
  2207. goto lookup;
  2208. if (rwc->try_lock) {
  2209. rwc->contended = true;
  2210. return;
  2211. }
  2212. i_mmap_lock_read(mapping);
  2213. }
  2214. lookup:
  2215. vma_interval_tree_foreach(vma, &mapping->i_mmap,
  2216. pgoff_start, pgoff_end) {
  2217. unsigned long address = vma_address(&folio->page, vma);
  2218. VM_BUG_ON_VMA(address == -EFAULT, vma);
  2219. cond_resched();
  2220. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2221. continue;
  2222. if (!rwc->rmap_one(folio, vma, address, rwc->arg))
  2223. goto done;
  2224. if (rwc->done && rwc->done(folio))
  2225. goto done;
  2226. }
  2227. done:
  2228. if (!locked)
  2229. i_mmap_unlock_read(mapping);
  2230. }
  2231. void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
  2232. {
  2233. if (unlikely(folio_test_ksm(folio)))
  2234. rmap_walk_ksm(folio, rwc);
  2235. else if (folio_test_anon(folio))
  2236. rmap_walk_anon(folio, rwc, false);
  2237. else
  2238. rmap_walk_file(folio, rwc, false);
  2239. }
  2240. /* Like rmap_walk, but caller holds relevant rmap lock */
  2241. void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
  2242. {
  2243. /* no ksm support for now */
  2244. VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
  2245. if (folio_test_anon(folio))
  2246. rmap_walk_anon(folio, rwc, true);
  2247. else
  2248. rmap_walk_file(folio, rwc, true);
  2249. }
  2250. #ifdef CONFIG_HUGETLB_PAGE
  2251. /*
  2252. * The following two functions are for anonymous (private mapped) hugepages.
  2253. * Unlike common anonymous pages, anonymous hugepages have no accounting code
  2254. * and no lru code, because we handle hugepages differently from common pages.
  2255. *
  2256. * RMAP_COMPOUND is ignored.
  2257. */
  2258. void hugepage_add_anon_rmap(struct page *page, struct vm_area_struct *vma,
  2259. unsigned long address, rmap_t flags)
  2260. {
  2261. struct anon_vma *anon_vma = vma->anon_vma;
  2262. int first;
  2263. BUG_ON(!PageLocked(page));
  2264. BUG_ON(!anon_vma);
  2265. /* address might be in next vma when migration races vma_adjust */
  2266. first = atomic_inc_and_test(compound_mapcount_ptr(page));
  2267. VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
  2268. VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
  2269. if (first)
  2270. __page_set_anon_rmap(page, vma, address,
  2271. !!(flags & RMAP_EXCLUSIVE));
  2272. }
  2273. void hugepage_add_new_anon_rmap(struct page *page,
  2274. struct vm_area_struct *vma, unsigned long address)
  2275. {
  2276. BUG_ON(address < vma->vm_start || address >= vma->vm_end);
  2277. atomic_set(compound_mapcount_ptr(page), 0);
  2278. atomic_set(compound_pincount_ptr(page), 0);
  2279. __page_set_anon_rmap(page, vma, address, 1);
  2280. }
  2281. #endif /* CONFIG_HUGETLB_PAGE */