mmap.c 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm/mmap.c
  4. *
  5. * Written by obz.
  6. *
  7. * Address space accounting code <[email protected]>
  8. */
  9. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  10. #include <linux/kernel.h>
  11. #include <linux/slab.h>
  12. #include <linux/backing-dev.h>
  13. #include <linux/mm.h>
  14. #include <linux/mm_inline.h>
  15. #include <linux/shm.h>
  16. #include <linux/mman.h>
  17. #include <linux/pagemap.h>
  18. #include <linux/swap.h>
  19. #include <linux/syscalls.h>
  20. #include <linux/capability.h>
  21. #include <linux/init.h>
  22. #include <linux/file.h>
  23. #include <linux/fs.h>
  24. #include <linux/personality.h>
  25. #include <linux/security.h>
  26. #include <linux/hugetlb.h>
  27. #include <linux/shmem_fs.h>
  28. #include <linux/profile.h>
  29. #include <linux/export.h>
  30. #include <linux/mount.h>
  31. #include <linux/mempolicy.h>
  32. #include <linux/rmap.h>
  33. #include <linux/mmu_notifier.h>
  34. #include <linux/mmdebug.h>
  35. #include <linux/perf_event.h>
  36. #include <linux/audit.h>
  37. #include <linux/khugepaged.h>
  38. #include <linux/uprobes.h>
  39. #include <linux/notifier.h>
  40. #include <linux/memory.h>
  41. #include <linux/printk.h>
  42. #include <linux/userfaultfd_k.h>
  43. #include <linux/moduleparam.h>
  44. #include <linux/pkeys.h>
  45. #include <linux/oom.h>
  46. #include <linux/sched/mm.h>
  47. #include <linux/uaccess.h>
  48. #include <asm/cacheflush.h>
  49. #include <asm/tlb.h>
  50. #include <asm/mmu_context.h>
  51. #define CREATE_TRACE_POINTS
  52. #include <trace/events/mmap.h>
  53. #undef CREATE_TRACE_POINTS
  54. #include <trace/hooks/mm.h>
  55. #include "internal.h"
  56. #ifndef arch_mmap_check
  57. #define arch_mmap_check(addr, len, flags) (0)
  58. #endif
  59. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
  60. const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
  61. const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
  62. int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
  63. #endif
  64. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
  65. const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
  66. const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
  67. int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
  68. #endif
  69. static bool ignore_rlimit_data;
  70. core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
  71. static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
  72. struct vm_area_struct *vma, struct vm_area_struct *prev,
  73. struct vm_area_struct *next, unsigned long start,
  74. unsigned long end, unsigned long start_t, unsigned long end_t,
  75. bool mm_wr_locked);
  76. static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
  77. {
  78. return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
  79. }
  80. /* Update vma->vm_page_prot to reflect vma->vm_flags. */
  81. void vma_set_page_prot(struct vm_area_struct *vma)
  82. {
  83. unsigned long vm_flags = vma->vm_flags;
  84. pgprot_t vm_page_prot;
  85. vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
  86. if (vma_wants_writenotify(vma, vm_page_prot)) {
  87. vm_flags &= ~VM_SHARED;
  88. vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
  89. }
  90. /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
  91. WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
  92. }
  93. /*
  94. * Requires inode->i_mapping->i_mmap_rwsem
  95. */
  96. static void __remove_shared_vm_struct(struct vm_area_struct *vma,
  97. struct file *file, struct address_space *mapping)
  98. {
  99. if (vma->vm_flags & VM_SHARED)
  100. mapping_unmap_writable(mapping);
  101. flush_dcache_mmap_lock(mapping);
  102. vma_interval_tree_remove(vma, &mapping->i_mmap);
  103. flush_dcache_mmap_unlock(mapping);
  104. }
  105. /*
  106. * Unlink a file-based vm structure from its interval tree, to hide
  107. * vma from rmap and vmtruncate before freeing its page tables.
  108. */
  109. void unlink_file_vma(struct vm_area_struct *vma)
  110. {
  111. struct file *file = vma->vm_file;
  112. if (file) {
  113. struct address_space *mapping = file->f_mapping;
  114. i_mmap_lock_write(mapping);
  115. __remove_shared_vm_struct(vma, file, mapping);
  116. i_mmap_unlock_write(mapping);
  117. }
  118. }
  119. /*
  120. * Close a vm structure and free it.
  121. */
  122. static void remove_vma(struct vm_area_struct *vma, bool unreachable)
  123. {
  124. might_sleep();
  125. if (vma->vm_ops && vma->vm_ops->close)
  126. vma->vm_ops->close(vma);
  127. if (vma->vm_file)
  128. fput(vma->vm_file);
  129. mpol_put(vma_policy(vma));
  130. if (unreachable)
  131. __vm_area_free(vma);
  132. else
  133. vm_area_free(vma);
  134. }
  135. /*
  136. * check_brk_limits() - Use platform specific check of range & verify mlock
  137. * limits.
  138. * @addr: The address to check
  139. * @len: The size of increase.
  140. *
  141. * Return: 0 on success.
  142. */
  143. static int check_brk_limits(unsigned long addr, unsigned long len)
  144. {
  145. unsigned long mapped_addr;
  146. mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
  147. if (IS_ERR_VALUE(mapped_addr))
  148. return mapped_addr;
  149. return mlock_future_check(current->mm, current->mm->def_flags, len);
  150. }
  151. static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
  152. unsigned long newbrk, unsigned long oldbrk,
  153. struct list_head *uf);
  154. static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *brkvma,
  155. unsigned long addr, unsigned long request, unsigned long flags);
  156. SYSCALL_DEFINE1(brk, unsigned long, brk)
  157. {
  158. unsigned long newbrk, oldbrk, origbrk;
  159. struct mm_struct *mm = current->mm;
  160. struct vm_area_struct *brkvma, *next = NULL;
  161. unsigned long min_brk;
  162. bool populate;
  163. bool downgraded = false;
  164. LIST_HEAD(uf);
  165. MA_STATE(mas, &mm->mm_mt, 0, 0);
  166. if (mmap_write_lock_killable(mm))
  167. return -EINTR;
  168. origbrk = mm->brk;
  169. #ifdef CONFIG_COMPAT_BRK
  170. /*
  171. * CONFIG_COMPAT_BRK can still be overridden by setting
  172. * randomize_va_space to 2, which will still cause mm->start_brk
  173. * to be arbitrarily shifted
  174. */
  175. if (current->brk_randomized)
  176. min_brk = mm->start_brk;
  177. else
  178. min_brk = mm->end_data;
  179. #else
  180. min_brk = mm->start_brk;
  181. #endif
  182. if (brk < min_brk)
  183. goto out;
  184. /*
  185. * Check against rlimit here. If this check is done later after the test
  186. * of oldbrk with newbrk then it can escape the test and let the data
  187. * segment grow beyond its set limit the in case where the limit is
  188. * not page aligned -Ram Gupta
  189. */
  190. if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
  191. mm->end_data, mm->start_data))
  192. goto out;
  193. newbrk = PAGE_ALIGN(brk);
  194. oldbrk = PAGE_ALIGN(mm->brk);
  195. if (oldbrk == newbrk) {
  196. mm->brk = brk;
  197. goto success;
  198. }
  199. /*
  200. * Always allow shrinking brk.
  201. * do_brk_munmap() may downgrade mmap_lock to read.
  202. */
  203. if (brk <= mm->brk) {
  204. int ret;
  205. /* Search one past newbrk */
  206. mas_set(&mas, newbrk);
  207. brkvma = mas_find(&mas, oldbrk);
  208. if (!brkvma || brkvma->vm_start >= oldbrk)
  209. goto out; /* mapping intersects with an existing non-brk vma. */
  210. /*
  211. * mm->brk must be protected by write mmap_lock.
  212. * do_brk_munmap() may downgrade the lock, so update it
  213. * before calling do_brk_munmap().
  214. */
  215. mm->brk = brk;
  216. ret = do_brk_munmap(&mas, brkvma, newbrk, oldbrk, &uf);
  217. if (ret == 1) {
  218. downgraded = true;
  219. goto success;
  220. } else if (!ret)
  221. goto success;
  222. mm->brk = origbrk;
  223. goto out;
  224. }
  225. if (check_brk_limits(oldbrk, newbrk - oldbrk))
  226. goto out;
  227. /*
  228. * Only check if the next VMA is within the stack_guard_gap of the
  229. * expansion area
  230. */
  231. mas_set(&mas, oldbrk);
  232. next = mas_find(&mas, newbrk - 1 + PAGE_SIZE + stack_guard_gap);
  233. if (next) {
  234. vma_start_write(next);
  235. if (newbrk + PAGE_SIZE > vm_start_gap(next))
  236. goto out;
  237. }
  238. brkvma = mas_prev(&mas, mm->start_brk);
  239. /* Ok, looks good - let it rip. */
  240. if (do_brk_flags(&mas, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
  241. goto out;
  242. mm->brk = brk;
  243. success:
  244. populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
  245. if (downgraded)
  246. mmap_read_unlock(mm);
  247. else
  248. mmap_write_unlock(mm);
  249. userfaultfd_unmap_complete(mm, &uf);
  250. if (populate)
  251. mm_populate(oldbrk, newbrk - oldbrk);
  252. return brk;
  253. out:
  254. mmap_write_unlock(mm);
  255. return origbrk;
  256. }
  257. #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
  258. extern void mt_validate(struct maple_tree *mt);
  259. extern void mt_dump(const struct maple_tree *mt);
  260. /* Validate the maple tree */
  261. static void validate_mm_mt(struct mm_struct *mm)
  262. {
  263. struct maple_tree *mt = &mm->mm_mt;
  264. struct vm_area_struct *vma_mt;
  265. MA_STATE(mas, mt, 0, 0);
  266. mt_validate(&mm->mm_mt);
  267. mas_for_each(&mas, vma_mt, ULONG_MAX) {
  268. if ((vma_mt->vm_start != mas.index) ||
  269. (vma_mt->vm_end - 1 != mas.last)) {
  270. pr_emerg("issue in %s\n", current->comm);
  271. dump_stack();
  272. dump_vma(vma_mt);
  273. pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
  274. mas.index, mas.last);
  275. pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
  276. vma_mt->vm_start, vma_mt->vm_end);
  277. mt_dump(mas.tree);
  278. if (vma_mt->vm_end != mas.last + 1) {
  279. pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
  280. mm, vma_mt->vm_start, vma_mt->vm_end,
  281. mas.index, mas.last);
  282. mt_dump(mas.tree);
  283. }
  284. VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
  285. if (vma_mt->vm_start != mas.index) {
  286. pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
  287. mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
  288. mt_dump(mas.tree);
  289. }
  290. VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
  291. }
  292. }
  293. }
  294. static void validate_mm(struct mm_struct *mm)
  295. {
  296. int bug = 0;
  297. int i = 0;
  298. struct vm_area_struct *vma;
  299. MA_STATE(mas, &mm->mm_mt, 0, 0);
  300. validate_mm_mt(mm);
  301. mas_for_each(&mas, vma, ULONG_MAX) {
  302. #ifdef CONFIG_DEBUG_VM_RB
  303. struct anon_vma *anon_vma = vma->anon_vma;
  304. struct anon_vma_chain *avc;
  305. if (anon_vma) {
  306. anon_vma_lock_read(anon_vma);
  307. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  308. anon_vma_interval_tree_verify(avc);
  309. anon_vma_unlock_read(anon_vma);
  310. }
  311. #endif
  312. i++;
  313. }
  314. if (i != mm->map_count) {
  315. pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
  316. bug = 1;
  317. }
  318. VM_BUG_ON_MM(bug, mm);
  319. }
  320. #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
  321. #define validate_mm_mt(root) do { } while (0)
  322. #define validate_mm(mm) do { } while (0)
  323. #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
  324. /*
  325. * vma has some anon_vma assigned, and is already inserted on that
  326. * anon_vma's interval trees.
  327. *
  328. * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
  329. * vma must be removed from the anon_vma's interval trees using
  330. * anon_vma_interval_tree_pre_update_vma().
  331. *
  332. * After the update, the vma will be reinserted using
  333. * anon_vma_interval_tree_post_update_vma().
  334. *
  335. * The entire update must be protected by exclusive mmap_lock and by
  336. * the root anon_vma's mutex.
  337. */
  338. static inline void
  339. anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
  340. {
  341. struct anon_vma_chain *avc;
  342. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  343. anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
  344. }
  345. static inline void
  346. anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
  347. {
  348. struct anon_vma_chain *avc;
  349. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  350. anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
  351. }
  352. static unsigned long count_vma_pages_range(struct mm_struct *mm,
  353. unsigned long addr, unsigned long end)
  354. {
  355. VMA_ITERATOR(vmi, mm, addr);
  356. struct vm_area_struct *vma;
  357. unsigned long nr_pages = 0;
  358. for_each_vma_range(vmi, vma, end) {
  359. unsigned long vm_start = max(addr, vma->vm_start);
  360. unsigned long vm_end = min(end, vma->vm_end);
  361. nr_pages += PHYS_PFN(vm_end - vm_start);
  362. }
  363. return nr_pages;
  364. }
  365. static void __vma_link_file(struct vm_area_struct *vma,
  366. struct address_space *mapping)
  367. {
  368. if (vma->vm_flags & VM_SHARED)
  369. mapping_allow_writable(mapping);
  370. flush_dcache_mmap_lock(mapping);
  371. vma_interval_tree_insert(vma, &mapping->i_mmap);
  372. flush_dcache_mmap_unlock(mapping);
  373. }
  374. /*
  375. * vma_mas_store() - Store a VMA in the maple tree.
  376. * @vma: The vm_area_struct
  377. * @mas: The maple state
  378. *
  379. * Efficient way to store a VMA in the maple tree when the @mas has already
  380. * walked to the correct location.
  381. *
  382. * Note: the end address is inclusive in the maple tree.
  383. */
  384. void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
  385. {
  386. trace_vma_store(mas->tree, vma);
  387. mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
  388. mas_store_prealloc(mas, vma);
  389. }
  390. /*
  391. * vma_mas_remove() - Remove a VMA from the maple tree.
  392. * @vma: The vm_area_struct
  393. * @mas: The maple state
  394. *
  395. * Efficient way to remove a VMA from the maple tree when the @mas has already
  396. * been established and points to the correct location.
  397. * Note: the end address is inclusive in the maple tree.
  398. */
  399. void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
  400. {
  401. trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
  402. mas->index = vma->vm_start;
  403. mas->last = vma->vm_end - 1;
  404. mas_store_prealloc(mas, NULL);
  405. }
  406. /*
  407. * vma_mas_szero() - Set a given range to zero. Used when modifying a
  408. * vm_area_struct start or end.
  409. *
  410. * @mas: The maple tree ma_state
  411. * @start: The start address to zero
  412. * @end: The end address to zero.
  413. */
  414. static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
  415. unsigned long end)
  416. {
  417. trace_vma_mas_szero(mas->tree, start, end - 1);
  418. mas_set_range(mas, start, end - 1);
  419. mas_store_prealloc(mas, NULL);
  420. }
  421. static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
  422. {
  423. MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_end - 1);
  424. struct address_space *mapping = NULL;
  425. if (mas_preallocate(&mas, vma, GFP_KERNEL))
  426. return -ENOMEM;
  427. vma_start_write(vma);
  428. if (vma->vm_file) {
  429. mapping = vma->vm_file->f_mapping;
  430. i_mmap_lock_write(mapping);
  431. }
  432. vma_mas_store(vma, &mas);
  433. if (mapping) {
  434. __vma_link_file(vma, mapping);
  435. i_mmap_unlock_write(mapping);
  436. }
  437. mm->map_count++;
  438. validate_mm(mm);
  439. return 0;
  440. }
  441. /*
  442. * vma_expand - Expand an existing VMA
  443. *
  444. * @mas: The maple state
  445. * @vma: The vma to expand
  446. * @start: The start of the vma
  447. * @end: The exclusive end of the vma
  448. * @pgoff: The page offset of vma
  449. * @next: The current of next vma.
  450. *
  451. * Expand @vma to @start and @end. Can expand off the start and end. Will
  452. * expand over @next if it's different from @vma and @end == @next->vm_end.
  453. * Checking if the @vma can expand and merge with @next needs to be handled by
  454. * the caller.
  455. *
  456. * Returns: 0 on success
  457. */
  458. inline int vma_expand(struct ma_state *mas, struct vm_area_struct *vma,
  459. unsigned long start, unsigned long end, pgoff_t pgoff,
  460. struct vm_area_struct *next)
  461. {
  462. struct mm_struct *mm = vma->vm_mm;
  463. struct address_space *mapping = NULL;
  464. struct rb_root_cached *root = NULL;
  465. struct anon_vma *anon_vma = vma->anon_vma;
  466. struct file *file = vma->vm_file;
  467. bool remove_next = false;
  468. struct vm_area_struct *anon_dup = NULL;
  469. vma_start_write(vma);
  470. if (next && (vma != next) && (end == next->vm_end)) {
  471. remove_next = true;
  472. /* Lock the VMA before removing it */
  473. vma_start_write(next);
  474. if (next->anon_vma && !vma->anon_vma) {
  475. int error;
  476. anon_vma = next->anon_vma;
  477. vma->anon_vma = anon_vma;
  478. error = anon_vma_clone(vma, next);
  479. if (error)
  480. return error;
  481. anon_dup = vma;
  482. }
  483. }
  484. /* Not merging but overwriting any part of next is not handled. */
  485. VM_BUG_ON(next && !remove_next && next != vma && end > next->vm_start);
  486. /* Only handles expanding */
  487. VM_BUG_ON(vma->vm_start < start || vma->vm_end > end);
  488. mas_set_range(mas, start, end - 1);
  489. if (mas_preallocate(mas, vma, GFP_KERNEL))
  490. goto nomem;
  491. vma_adjust_trans_huge(vma, start, end, 0);
  492. if (file) {
  493. mapping = file->f_mapping;
  494. root = &mapping->i_mmap;
  495. uprobe_munmap(vma, vma->vm_start, vma->vm_end);
  496. i_mmap_lock_write(mapping);
  497. }
  498. if (anon_vma) {
  499. anon_vma_lock_write(anon_vma);
  500. anon_vma_interval_tree_pre_update_vma(vma);
  501. }
  502. if (file) {
  503. flush_dcache_mmap_lock(mapping);
  504. vma_interval_tree_remove(vma, root);
  505. }
  506. vma->vm_start = start;
  507. vma->vm_end = end;
  508. vma->vm_pgoff = pgoff;
  509. /* Note: mas must be pointing to the expanding VMA */
  510. vma_mas_store(vma, mas);
  511. if (remove_next)
  512. vma_mark_detached(next, true);
  513. if (file) {
  514. vma_interval_tree_insert(vma, root);
  515. flush_dcache_mmap_unlock(mapping);
  516. }
  517. /* Expanding over the next vma */
  518. if (remove_next && file) {
  519. __remove_shared_vm_struct(next, file, mapping);
  520. }
  521. if (anon_vma) {
  522. anon_vma_interval_tree_post_update_vma(vma);
  523. anon_vma_unlock_write(anon_vma);
  524. }
  525. if (file) {
  526. i_mmap_unlock_write(mapping);
  527. uprobe_mmap(vma);
  528. }
  529. if (remove_next) {
  530. if (file) {
  531. uprobe_munmap(next, next->vm_start, next->vm_end);
  532. fput(file);
  533. }
  534. if (next->anon_vma)
  535. anon_vma_merge(vma, next);
  536. mm->map_count--;
  537. mpol_put(vma_policy(next));
  538. vm_area_free(next);
  539. }
  540. validate_mm(mm);
  541. return 0;
  542. nomem:
  543. if (anon_dup)
  544. unlink_anon_vmas(anon_dup);
  545. return -ENOMEM;
  546. }
  547. /*
  548. * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
  549. * is already present in an i_mmap tree without adjusting the tree.
  550. * The following helper function should be used when such adjustments
  551. * are necessary. The "insert" vma (if any) is to be inserted
  552. * before we drop the necessary locks.
  553. * 'expand' vma is always locked before it's passed to __vma_adjust()
  554. * from vma_merge() because vma should not change from the moment
  555. * can_vma_merge_{before|after} decision is made.
  556. * 'insert' vma is used only by __split_vma() and it's always a brand
  557. * new vma which is not yet added into mm's vma tree, therefore no need
  558. * to lock it.
  559. */
  560. int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
  561. unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
  562. struct vm_area_struct *expand)
  563. {
  564. struct mm_struct *mm = vma->vm_mm;
  565. struct vm_area_struct *next_next = NULL; /* uninit var warning */
  566. struct vm_area_struct *next = find_vma(mm, vma->vm_end);
  567. struct vm_area_struct *orig_vma = vma;
  568. struct address_space *mapping = NULL;
  569. struct rb_root_cached *root = NULL;
  570. struct anon_vma *anon_vma = NULL;
  571. struct file *file = vma->vm_file;
  572. bool vma_changed = false;
  573. long adjust_next = 0;
  574. int remove_next = 0;
  575. MA_STATE(mas, &mm->mm_mt, start, end - 1);
  576. struct vm_area_struct *exporter = NULL, *importer = NULL;
  577. struct vm_area_struct *anon_dup = NULL;
  578. vma_start_write(vma);
  579. if (next)
  580. vma_start_write(next);
  581. if (next && !insert) {
  582. if (end >= next->vm_end) {
  583. /*
  584. * vma expands, overlapping all the next, and
  585. * perhaps the one after too (mprotect case 6).
  586. * The only other cases that gets here are
  587. * case 1, case 7 and case 8.
  588. */
  589. if (next == expand) {
  590. /*
  591. * The only case where we don't expand "vma"
  592. * and we expand "next" instead is case 8.
  593. */
  594. VM_WARN_ON(end != next->vm_end);
  595. /*
  596. * remove_next == 3 means we're
  597. * removing "vma" and that to do so we
  598. * swapped "vma" and "next".
  599. */
  600. remove_next = 3;
  601. VM_WARN_ON(file != next->vm_file);
  602. swap(vma, next);
  603. } else {
  604. VM_WARN_ON(expand != vma);
  605. /*
  606. * case 1, 6, 7, remove_next == 2 is case 6,
  607. * remove_next == 1 is case 1 or 7.
  608. */
  609. remove_next = 1 + (end > next->vm_end);
  610. if (remove_next == 2) {
  611. next_next = find_vma(mm, next->vm_end);
  612. if (next_next)
  613. vma_start_write(next_next);
  614. }
  615. VM_WARN_ON(remove_next == 2 &&
  616. end != next_next->vm_end);
  617. }
  618. exporter = next;
  619. importer = vma;
  620. /*
  621. * If next doesn't have anon_vma, import from vma after
  622. * next, if the vma overlaps with it.
  623. */
  624. if (remove_next == 2 && !next->anon_vma)
  625. exporter = next_next;
  626. } else if (end > next->vm_start) {
  627. /*
  628. * vma expands, overlapping part of the next:
  629. * mprotect case 5 shifting the boundary up.
  630. */
  631. adjust_next = (end - next->vm_start);
  632. exporter = next;
  633. importer = vma;
  634. VM_WARN_ON(expand != importer);
  635. } else if (end < vma->vm_end) {
  636. /*
  637. * vma shrinks, and !insert tells it's not
  638. * split_vma inserting another: so it must be
  639. * mprotect case 4 shifting the boundary down.
  640. */
  641. adjust_next = -(vma->vm_end - end);
  642. exporter = vma;
  643. importer = next;
  644. VM_WARN_ON(expand != importer);
  645. }
  646. /*
  647. * Easily overlooked: when mprotect shifts the boundary,
  648. * make sure the expanding vma has anon_vma set if the
  649. * shrinking vma had, to cover any anon pages imported.
  650. */
  651. if (exporter && exporter->anon_vma && !importer->anon_vma) {
  652. int error;
  653. importer->anon_vma = exporter->anon_vma;
  654. error = anon_vma_clone(importer, exporter);
  655. if (error)
  656. return error;
  657. anon_dup = importer;
  658. }
  659. }
  660. if (adjust_next < 0)
  661. mas_set_range(&mas, next->vm_start + adjust_next,
  662. next->vm_end - 1);
  663. else if (insert) {
  664. vma_start_write(insert);
  665. mas_set_range(&mas, insert->vm_start, insert->vm_end - 1);
  666. }
  667. if (mas_preallocate(&mas, vma, GFP_KERNEL)) {
  668. if (anon_dup)
  669. unlink_anon_vmas(anon_dup);
  670. return -ENOMEM;
  671. }
  672. vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
  673. if (file) {
  674. mapping = file->f_mapping;
  675. root = &mapping->i_mmap;
  676. uprobe_munmap(vma, vma->vm_start, vma->vm_end);
  677. if (adjust_next)
  678. uprobe_munmap(next, next->vm_start, next->vm_end);
  679. i_mmap_lock_write(mapping);
  680. if (insert && insert->vm_file) {
  681. /*
  682. * Put into interval tree now, so instantiated pages
  683. * are visible to arm/parisc __flush_dcache_page
  684. * throughout; but we cannot insert into address
  685. * space until vma start or end is updated.
  686. */
  687. __vma_link_file(insert, insert->vm_file->f_mapping);
  688. }
  689. }
  690. anon_vma = vma->anon_vma;
  691. if (!anon_vma && adjust_next)
  692. anon_vma = next->anon_vma;
  693. if (anon_vma) {
  694. VM_WARN_ON(adjust_next && next->anon_vma &&
  695. anon_vma != next->anon_vma);
  696. anon_vma_lock_write(anon_vma);
  697. anon_vma_interval_tree_pre_update_vma(vma);
  698. if (adjust_next)
  699. anon_vma_interval_tree_pre_update_vma(next);
  700. }
  701. if (file) {
  702. flush_dcache_mmap_lock(mapping);
  703. vma_interval_tree_remove(vma, root);
  704. if (adjust_next)
  705. vma_interval_tree_remove(next, root);
  706. }
  707. if (start != vma->vm_start) {
  708. if ((vma->vm_start < start) && !insert) {
  709. vma_mas_szero(&mas, vma->vm_start, start);
  710. VM_WARN_ON(insert && insert->vm_start > vma->vm_start);
  711. } else if (!insert) {
  712. vma_changed = true;
  713. }
  714. vma->vm_start = start;
  715. }
  716. if (end != vma->vm_end) {
  717. if (vma->vm_end > end) {
  718. if ((vma->vm_end + adjust_next != end) &&
  719. (!insert || (insert->vm_start != end))) {
  720. vma_mas_szero(&mas, end, vma->vm_end);
  721. mas_reset(&mas);
  722. VM_WARN_ON(insert &&
  723. insert->vm_end < vma->vm_end);
  724. }
  725. } else if (!insert) {
  726. vma_changed = true;
  727. }
  728. vma->vm_end = end;
  729. }
  730. if (vma_changed)
  731. vma_mas_store(vma, &mas);
  732. vma->vm_pgoff = pgoff;
  733. if (adjust_next) {
  734. next->vm_start += adjust_next;
  735. next->vm_pgoff += adjust_next >> PAGE_SHIFT;
  736. vma_mas_store(next, &mas);
  737. }
  738. if (file) {
  739. if (adjust_next)
  740. vma_interval_tree_insert(next, root);
  741. vma_interval_tree_insert(vma, root);
  742. flush_dcache_mmap_unlock(mapping);
  743. }
  744. if (remove_next && file) {
  745. __remove_shared_vm_struct(next, file, mapping);
  746. if (remove_next == 2)
  747. __remove_shared_vm_struct(next_next, file, mapping);
  748. } else if (insert) {
  749. /*
  750. * split_vma has split insert from vma, and needs
  751. * us to insert it before dropping the locks
  752. * (it may either follow vma or precede it).
  753. */
  754. mas_reset(&mas);
  755. vma_start_write(insert);
  756. vma_mas_store(insert, &mas);
  757. mm->map_count++;
  758. }
  759. if (anon_vma) {
  760. anon_vma_interval_tree_post_update_vma(vma);
  761. if (adjust_next)
  762. anon_vma_interval_tree_post_update_vma(next);
  763. anon_vma_unlock_write(anon_vma);
  764. }
  765. if (file) {
  766. i_mmap_unlock_write(mapping);
  767. uprobe_mmap(vma);
  768. if (adjust_next)
  769. uprobe_mmap(next);
  770. }
  771. if (remove_next) {
  772. again:
  773. vma_mark_detached(next, true);
  774. if (file) {
  775. uprobe_munmap(next, next->vm_start, next->vm_end);
  776. fput(file);
  777. }
  778. if (next->anon_vma)
  779. anon_vma_merge(vma, next);
  780. mm->map_count--;
  781. mpol_put(vma_policy(next));
  782. if (remove_next != 2)
  783. BUG_ON(vma->vm_end < next->vm_end);
  784. vm_area_free(next);
  785. /*
  786. * In mprotect's case 6 (see comments on vma_merge),
  787. * we must remove next_next too.
  788. */
  789. if (remove_next == 2) {
  790. remove_next = 1;
  791. next = next_next;
  792. goto again;
  793. }
  794. }
  795. if (insert && file)
  796. uprobe_mmap(insert);
  797. mas_destroy(&mas);
  798. validate_mm(mm);
  799. return 0;
  800. }
  801. /*
  802. * If the vma has a ->close operation then the driver probably needs to release
  803. * per-vma resources, so we don't attempt to merge those.
  804. */
  805. static inline int is_mergeable_vma(struct vm_area_struct *vma,
  806. struct file *file, unsigned long vm_flags,
  807. struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
  808. struct anon_vma_name *anon_name)
  809. {
  810. /*
  811. * VM_SOFTDIRTY should not prevent from VMA merging, if we
  812. * match the flags but dirty bit -- the caller should mark
  813. * merged VMA as dirty. If dirty bit won't be excluded from
  814. * comparison, we increase pressure on the memory system forcing
  815. * the kernel to generate new VMAs when old one could be
  816. * extended instead.
  817. */
  818. if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
  819. return 0;
  820. if (vma->vm_file != file)
  821. return 0;
  822. if (vma->vm_ops && vma->vm_ops->close)
  823. return 0;
  824. if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
  825. return 0;
  826. if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
  827. return 0;
  828. return 1;
  829. }
  830. static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
  831. struct anon_vma *anon_vma2,
  832. struct vm_area_struct *vma)
  833. {
  834. /*
  835. * The list_is_singular() test is to avoid merging VMA cloned from
  836. * parents. This can improve scalability caused by anon_vma lock.
  837. */
  838. if ((!anon_vma1 || !anon_vma2) && (!vma ||
  839. list_is_singular(&vma->anon_vma_chain)))
  840. return 1;
  841. return anon_vma1 == anon_vma2;
  842. }
  843. /*
  844. * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
  845. * in front of (at a lower virtual address and file offset than) the vma.
  846. *
  847. * We cannot merge two vmas if they have differently assigned (non-NULL)
  848. * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
  849. *
  850. * We don't check here for the merged mmap wrapping around the end of pagecache
  851. * indices (16TB on ia32) because do_mmap() does not permit mmap's which
  852. * wrap, nor mmaps which cover the final page at index -1UL.
  853. */
  854. static int
  855. can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
  856. struct anon_vma *anon_vma, struct file *file,
  857. pgoff_t vm_pgoff,
  858. struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
  859. struct anon_vma_name *anon_name)
  860. {
  861. if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
  862. is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
  863. if (vma->vm_pgoff == vm_pgoff)
  864. return 1;
  865. }
  866. return 0;
  867. }
  868. /*
  869. * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
  870. * beyond (at a higher virtual address and file offset than) the vma.
  871. *
  872. * We cannot merge two vmas if they have differently assigned (non-NULL)
  873. * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
  874. */
  875. static int
  876. can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
  877. struct anon_vma *anon_vma, struct file *file,
  878. pgoff_t vm_pgoff,
  879. struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
  880. struct anon_vma_name *anon_name)
  881. {
  882. if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
  883. is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
  884. pgoff_t vm_pglen;
  885. vm_pglen = vma_pages(vma);
  886. if (vma->vm_pgoff + vm_pglen == vm_pgoff)
  887. return 1;
  888. }
  889. return 0;
  890. }
  891. /*
  892. * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
  893. * figure out whether that can be merged with its predecessor or its
  894. * successor. Or both (it neatly fills a hole).
  895. *
  896. * In most cases - when called for mmap, brk or mremap - [addr,end) is
  897. * certain not to be mapped by the time vma_merge is called; but when
  898. * called for mprotect, it is certain to be already mapped (either at
  899. * an offset within prev, or at the start of next), and the flags of
  900. * this area are about to be changed to vm_flags - and the no-change
  901. * case has already been eliminated.
  902. *
  903. * The following mprotect cases have to be considered, where AAAA is
  904. * the area passed down from mprotect_fixup, never extending beyond one
  905. * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
  906. *
  907. * AAAA AAAA AAAA
  908. * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN
  909. * cannot merge might become might become
  910. * PPNNNNNNNNNN PPPPPPPPPPNN
  911. * mmap, brk or case 4 below case 5 below
  912. * mremap move:
  913. * AAAA AAAA
  914. * PPPP NNNN PPPPNNNNXXXX
  915. * might become might become
  916. * PPPPPPPPPPPP 1 or PPPPPPPPPPPP 6 or
  917. * PPPPPPPPNNNN 2 or PPPPPPPPXXXX 7 or
  918. * PPPPNNNNNNNN 3 PPPPXXXXXXXX 8
  919. *
  920. * It is important for case 8 that the vma NNNN overlapping the
  921. * region AAAA is never going to extended over XXXX. Instead XXXX must
  922. * be extended in region AAAA and NNNN must be removed. This way in
  923. * all cases where vma_merge succeeds, the moment vma_adjust drops the
  924. * rmap_locks, the properties of the merged vma will be already
  925. * correct for the whole merged range. Some of those properties like
  926. * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
  927. * be correct for the whole merged range immediately after the
  928. * rmap_locks are released. Otherwise if XXXX would be removed and
  929. * NNNN would be extended over the XXXX range, remove_migration_ptes
  930. * or other rmap walkers (if working on addresses beyond the "end"
  931. * parameter) may establish ptes with the wrong permissions of NNNN
  932. * instead of the right permissions of XXXX.
  933. */
  934. struct vm_area_struct *vma_merge(struct mm_struct *mm,
  935. struct vm_area_struct *prev, unsigned long addr,
  936. unsigned long end, unsigned long vm_flags,
  937. struct anon_vma *anon_vma, struct file *file,
  938. pgoff_t pgoff, struct mempolicy *policy,
  939. struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
  940. struct anon_vma_name *anon_name)
  941. {
  942. pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
  943. struct vm_area_struct *mid, *next, *res;
  944. int err = -1;
  945. bool merge_prev = false;
  946. bool merge_next = false;
  947. /*
  948. * We later require that vma->vm_flags == vm_flags,
  949. * so this tests vma->vm_flags & VM_SPECIAL, too.
  950. */
  951. if (vm_flags & VM_SPECIAL)
  952. return NULL;
  953. if (prev)
  954. vma_start_write(prev);
  955. next = find_vma(mm, prev ? prev->vm_end : 0);
  956. if (next)
  957. vma_start_write(next);
  958. mid = next;
  959. if (next && next->vm_end == end) { /* cases 6, 7, 8 */
  960. next = find_vma(mm, next->vm_end);
  961. if (next)
  962. vma_start_write(next);
  963. }
  964. /* verify some invariant that must be enforced by the caller */
  965. VM_WARN_ON(prev && addr <= prev->vm_start);
  966. VM_WARN_ON(mid && end > mid->vm_end);
  967. VM_WARN_ON(addr >= end);
  968. /* Can we merge the predecessor? */
  969. if (prev && prev->vm_end == addr &&
  970. mpol_equal(vma_policy(prev), policy) &&
  971. can_vma_merge_after(prev, vm_flags,
  972. anon_vma, file, pgoff,
  973. vm_userfaultfd_ctx, anon_name)) {
  974. merge_prev = true;
  975. }
  976. /* Can we merge the successor? */
  977. if (next && end == next->vm_start &&
  978. mpol_equal(policy, vma_policy(next)) &&
  979. can_vma_merge_before(next, vm_flags,
  980. anon_vma, file, pgoff+pglen,
  981. vm_userfaultfd_ctx, anon_name)) {
  982. merge_next = true;
  983. }
  984. /* Can we merge both the predecessor and the successor? */
  985. if (merge_prev && merge_next &&
  986. is_mergeable_anon_vma(prev->anon_vma,
  987. next->anon_vma, NULL)) { /* cases 1, 6 */
  988. err = __vma_adjust(prev, prev->vm_start,
  989. next->vm_end, prev->vm_pgoff, NULL,
  990. prev);
  991. res = prev;
  992. } else if (merge_prev) { /* cases 2, 5, 7 */
  993. err = __vma_adjust(prev, prev->vm_start,
  994. end, prev->vm_pgoff, NULL, prev);
  995. res = prev;
  996. } else if (merge_next) {
  997. if (prev && addr < prev->vm_end) /* case 4 */
  998. err = __vma_adjust(prev, prev->vm_start,
  999. addr, prev->vm_pgoff, NULL, next);
  1000. else /* cases 3, 8 */
  1001. err = __vma_adjust(mid, addr, next->vm_end,
  1002. next->vm_pgoff - pglen, NULL, next);
  1003. res = next;
  1004. }
  1005. /*
  1006. * Cannot merge with predecessor or successor or error in __vma_adjust?
  1007. */
  1008. if (err)
  1009. return NULL;
  1010. khugepaged_enter_vma(res, vm_flags);
  1011. return res;
  1012. }
  1013. /*
  1014. * Rough compatibility check to quickly see if it's even worth looking
  1015. * at sharing an anon_vma.
  1016. *
  1017. * They need to have the same vm_file, and the flags can only differ
  1018. * in things that mprotect may change.
  1019. *
  1020. * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
  1021. * we can merge the two vma's. For example, we refuse to merge a vma if
  1022. * there is a vm_ops->close() function, because that indicates that the
  1023. * driver is doing some kind of reference counting. But that doesn't
  1024. * really matter for the anon_vma sharing case.
  1025. */
  1026. static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
  1027. {
  1028. return a->vm_end == b->vm_start &&
  1029. mpol_equal(vma_policy(a), vma_policy(b)) &&
  1030. a->vm_file == b->vm_file &&
  1031. !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
  1032. b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
  1033. }
  1034. /*
  1035. * Do some basic sanity checking to see if we can re-use the anon_vma
  1036. * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
  1037. * the same as 'old', the other will be the new one that is trying
  1038. * to share the anon_vma.
  1039. *
  1040. * NOTE! This runs with mmap_lock held for reading, so it is possible that
  1041. * the anon_vma of 'old' is concurrently in the process of being set up
  1042. * by another page fault trying to merge _that_. But that's ok: if it
  1043. * is being set up, that automatically means that it will be a singleton
  1044. * acceptable for merging, so we can do all of this optimistically. But
  1045. * we do that READ_ONCE() to make sure that we never re-load the pointer.
  1046. *
  1047. * IOW: that the "list_is_singular()" test on the anon_vma_chain only
  1048. * matters for the 'stable anon_vma' case (ie the thing we want to avoid
  1049. * is to return an anon_vma that is "complex" due to having gone through
  1050. * a fork).
  1051. *
  1052. * We also make sure that the two vma's are compatible (adjacent,
  1053. * and with the same memory policies). That's all stable, even with just
  1054. * a read lock on the mmap_lock.
  1055. */
  1056. static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
  1057. {
  1058. if (anon_vma_compatible(a, b)) {
  1059. struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
  1060. if (anon_vma && list_is_singular(&old->anon_vma_chain))
  1061. return anon_vma;
  1062. }
  1063. return NULL;
  1064. }
  1065. /*
  1066. * find_mergeable_anon_vma is used by anon_vma_prepare, to check
  1067. * neighbouring vmas for a suitable anon_vma, before it goes off
  1068. * to allocate a new anon_vma. It checks because a repetitive
  1069. * sequence of mprotects and faults may otherwise lead to distinct
  1070. * anon_vmas being allocated, preventing vma merge in subsequent
  1071. * mprotect.
  1072. */
  1073. struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
  1074. {
  1075. MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
  1076. struct anon_vma *anon_vma = NULL;
  1077. struct vm_area_struct *prev, *next;
  1078. /* Try next first. */
  1079. next = mas_walk(&mas);
  1080. if (next) {
  1081. anon_vma = reusable_anon_vma(next, vma, next);
  1082. if (anon_vma)
  1083. return anon_vma;
  1084. }
  1085. prev = mas_prev(&mas, 0);
  1086. VM_BUG_ON_VMA(prev != vma, vma);
  1087. prev = mas_prev(&mas, 0);
  1088. /* Try prev next. */
  1089. if (prev)
  1090. anon_vma = reusable_anon_vma(prev, prev, vma);
  1091. /*
  1092. * We might reach here with anon_vma == NULL if we can't find
  1093. * any reusable anon_vma.
  1094. * There's no absolute need to look only at touching neighbours:
  1095. * we could search further afield for "compatible" anon_vmas.
  1096. * But it would probably just be a waste of time searching,
  1097. * or lead to too many vmas hanging off the same anon_vma.
  1098. * We're trying to allow mprotect remerging later on,
  1099. * not trying to minimize memory used for anon_vmas.
  1100. */
  1101. return anon_vma;
  1102. }
  1103. /*
  1104. * If a hint addr is less than mmap_min_addr change hint to be as
  1105. * low as possible but still greater than mmap_min_addr
  1106. */
  1107. static inline unsigned long round_hint_to_min(unsigned long hint)
  1108. {
  1109. hint &= PAGE_MASK;
  1110. if (((void *)hint != NULL) &&
  1111. (hint < mmap_min_addr))
  1112. return PAGE_ALIGN(mmap_min_addr);
  1113. return hint;
  1114. }
  1115. int mlock_future_check(struct mm_struct *mm, unsigned long flags,
  1116. unsigned long len)
  1117. {
  1118. unsigned long locked, lock_limit;
  1119. /* mlock MCL_FUTURE? */
  1120. if (flags & VM_LOCKED) {
  1121. locked = len >> PAGE_SHIFT;
  1122. locked += mm->locked_vm;
  1123. lock_limit = rlimit(RLIMIT_MEMLOCK);
  1124. lock_limit >>= PAGE_SHIFT;
  1125. if (locked > lock_limit && !capable(CAP_IPC_LOCK))
  1126. return -EAGAIN;
  1127. }
  1128. return 0;
  1129. }
  1130. static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
  1131. {
  1132. if (S_ISREG(inode->i_mode))
  1133. return MAX_LFS_FILESIZE;
  1134. if (S_ISBLK(inode->i_mode))
  1135. return MAX_LFS_FILESIZE;
  1136. if (S_ISSOCK(inode->i_mode))
  1137. return MAX_LFS_FILESIZE;
  1138. /* Special "we do even unsigned file positions" case */
  1139. if (file->f_mode & FMODE_UNSIGNED_OFFSET)
  1140. return 0;
  1141. /* Yes, random drivers might want more. But I'm tired of buggy drivers */
  1142. return ULONG_MAX;
  1143. }
  1144. static inline bool file_mmap_ok(struct file *file, struct inode *inode,
  1145. unsigned long pgoff, unsigned long len)
  1146. {
  1147. u64 maxsize = file_mmap_size_max(file, inode);
  1148. if (maxsize && len > maxsize)
  1149. return false;
  1150. maxsize -= len;
  1151. if (pgoff > maxsize >> PAGE_SHIFT)
  1152. return false;
  1153. return true;
  1154. }
  1155. /*
  1156. * The caller must write-lock current->mm->mmap_lock.
  1157. */
  1158. unsigned long do_mmap(struct file *file, unsigned long addr,
  1159. unsigned long len, unsigned long prot,
  1160. unsigned long flags, unsigned long pgoff,
  1161. unsigned long *populate, struct list_head *uf)
  1162. {
  1163. struct mm_struct *mm = current->mm;
  1164. vm_flags_t vm_flags;
  1165. int pkey = 0;
  1166. validate_mm(mm);
  1167. *populate = 0;
  1168. if (!len)
  1169. return -EINVAL;
  1170. /*
  1171. * Does the application expect PROT_READ to imply PROT_EXEC?
  1172. *
  1173. * (the exception is when the underlying filesystem is noexec
  1174. * mounted, in which case we dont add PROT_EXEC.)
  1175. */
  1176. if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
  1177. if (!(file && path_noexec(&file->f_path)))
  1178. prot |= PROT_EXEC;
  1179. /* force arch specific MAP_FIXED handling in get_unmapped_area */
  1180. if (flags & MAP_FIXED_NOREPLACE)
  1181. flags |= MAP_FIXED;
  1182. if (!(flags & MAP_FIXED))
  1183. addr = round_hint_to_min(addr);
  1184. /* Careful about overflows.. */
  1185. len = PAGE_ALIGN(len);
  1186. if (!len)
  1187. return -ENOMEM;
  1188. /* offset overflow? */
  1189. if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
  1190. return -EOVERFLOW;
  1191. /* Too many mappings? */
  1192. if (mm->map_count > sysctl_max_map_count)
  1193. return -ENOMEM;
  1194. /* Obtain the address to map to. we verify (or select) it and ensure
  1195. * that it represents a valid section of the address space.
  1196. */
  1197. addr = get_unmapped_area(file, addr, len, pgoff, flags);
  1198. if (IS_ERR_VALUE(addr))
  1199. return addr;
  1200. if (flags & MAP_FIXED_NOREPLACE) {
  1201. if (find_vma_intersection(mm, addr, addr + len))
  1202. return -EEXIST;
  1203. }
  1204. if (prot == PROT_EXEC) {
  1205. pkey = execute_only_pkey(mm);
  1206. if (pkey < 0)
  1207. pkey = 0;
  1208. }
  1209. /* Do simple checking here so the lower-level routines won't have
  1210. * to. we assume access permissions have been handled by the open
  1211. * of the memory object, so we don't do any here.
  1212. */
  1213. vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
  1214. mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
  1215. if (flags & MAP_LOCKED)
  1216. if (!can_do_mlock())
  1217. return -EPERM;
  1218. if (mlock_future_check(mm, vm_flags, len))
  1219. return -EAGAIN;
  1220. if (file) {
  1221. struct inode *inode = file_inode(file);
  1222. unsigned long flags_mask;
  1223. if (!file_mmap_ok(file, inode, pgoff, len))
  1224. return -EOVERFLOW;
  1225. flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
  1226. switch (flags & MAP_TYPE) {
  1227. case MAP_SHARED:
  1228. /*
  1229. * Force use of MAP_SHARED_VALIDATE with non-legacy
  1230. * flags. E.g. MAP_SYNC is dangerous to use with
  1231. * MAP_SHARED as you don't know which consistency model
  1232. * you will get. We silently ignore unsupported flags
  1233. * with MAP_SHARED to preserve backward compatibility.
  1234. */
  1235. flags &= LEGACY_MAP_MASK;
  1236. fallthrough;
  1237. case MAP_SHARED_VALIDATE:
  1238. if (flags & ~flags_mask)
  1239. return -EOPNOTSUPP;
  1240. if (prot & PROT_WRITE) {
  1241. if (!(file->f_mode & FMODE_WRITE))
  1242. return -EACCES;
  1243. if (IS_SWAPFILE(file->f_mapping->host))
  1244. return -ETXTBSY;
  1245. }
  1246. /*
  1247. * Make sure we don't allow writing to an append-only
  1248. * file..
  1249. */
  1250. if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
  1251. return -EACCES;
  1252. vm_flags |= VM_SHARED | VM_MAYSHARE;
  1253. if (!(file->f_mode & FMODE_WRITE))
  1254. vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
  1255. fallthrough;
  1256. case MAP_PRIVATE:
  1257. if (!(file->f_mode & FMODE_READ))
  1258. return -EACCES;
  1259. if (path_noexec(&file->f_path)) {
  1260. if (vm_flags & VM_EXEC)
  1261. return -EPERM;
  1262. vm_flags &= ~VM_MAYEXEC;
  1263. }
  1264. if (!file->f_op->mmap)
  1265. return -ENODEV;
  1266. if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
  1267. return -EINVAL;
  1268. break;
  1269. default:
  1270. return -EINVAL;
  1271. }
  1272. } else {
  1273. switch (flags & MAP_TYPE) {
  1274. case MAP_SHARED:
  1275. if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
  1276. return -EINVAL;
  1277. /*
  1278. * Ignore pgoff.
  1279. */
  1280. pgoff = 0;
  1281. vm_flags |= VM_SHARED | VM_MAYSHARE;
  1282. break;
  1283. case MAP_PRIVATE:
  1284. /*
  1285. * Set pgoff according to addr for anon_vma.
  1286. */
  1287. pgoff = addr >> PAGE_SHIFT;
  1288. break;
  1289. default:
  1290. return -EINVAL;
  1291. }
  1292. }
  1293. /*
  1294. * Set 'VM_NORESERVE' if we should not account for the
  1295. * memory use of this mapping.
  1296. */
  1297. if (flags & MAP_NORESERVE) {
  1298. /* We honor MAP_NORESERVE if allowed to overcommit */
  1299. if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
  1300. vm_flags |= VM_NORESERVE;
  1301. /* hugetlb applies strict overcommit unless MAP_NORESERVE */
  1302. if (file && is_file_hugepages(file))
  1303. vm_flags |= VM_NORESERVE;
  1304. }
  1305. addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
  1306. if (!IS_ERR_VALUE(addr) &&
  1307. ((vm_flags & VM_LOCKED) ||
  1308. (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
  1309. *populate = len;
  1310. return addr;
  1311. }
  1312. unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
  1313. unsigned long prot, unsigned long flags,
  1314. unsigned long fd, unsigned long pgoff)
  1315. {
  1316. struct file *file = NULL;
  1317. unsigned long retval;
  1318. if (!(flags & MAP_ANONYMOUS)) {
  1319. audit_mmap_fd(fd, flags);
  1320. file = fget(fd);
  1321. if (!file)
  1322. return -EBADF;
  1323. if (is_file_hugepages(file)) {
  1324. len = ALIGN(len, huge_page_size(hstate_file(file)));
  1325. } else if (unlikely(flags & MAP_HUGETLB)) {
  1326. retval = -EINVAL;
  1327. goto out_fput;
  1328. }
  1329. } else if (flags & MAP_HUGETLB) {
  1330. struct hstate *hs;
  1331. hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
  1332. if (!hs)
  1333. return -EINVAL;
  1334. len = ALIGN(len, huge_page_size(hs));
  1335. /*
  1336. * VM_NORESERVE is used because the reservations will be
  1337. * taken when vm_ops->mmap() is called
  1338. */
  1339. file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
  1340. VM_NORESERVE,
  1341. HUGETLB_ANONHUGE_INODE,
  1342. (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
  1343. if (IS_ERR(file))
  1344. return PTR_ERR(file);
  1345. }
  1346. retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
  1347. out_fput:
  1348. if (file)
  1349. fput(file);
  1350. return retval;
  1351. }
  1352. SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
  1353. unsigned long, prot, unsigned long, flags,
  1354. unsigned long, fd, unsigned long, pgoff)
  1355. {
  1356. return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
  1357. }
  1358. #ifdef __ARCH_WANT_SYS_OLD_MMAP
  1359. struct mmap_arg_struct {
  1360. unsigned long addr;
  1361. unsigned long len;
  1362. unsigned long prot;
  1363. unsigned long flags;
  1364. unsigned long fd;
  1365. unsigned long offset;
  1366. };
  1367. SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
  1368. {
  1369. struct mmap_arg_struct a;
  1370. if (copy_from_user(&a, arg, sizeof(a)))
  1371. return -EFAULT;
  1372. if (offset_in_page(a.offset))
  1373. return -EINVAL;
  1374. return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
  1375. a.offset >> PAGE_SHIFT);
  1376. }
  1377. #endif /* __ARCH_WANT_SYS_OLD_MMAP */
  1378. /*
  1379. * Some shared mappings will want the pages marked read-only
  1380. * to track write events. If so, we'll downgrade vm_page_prot
  1381. * to the private version (using protection_map[] without the
  1382. * VM_SHARED bit).
  1383. */
  1384. int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
  1385. {
  1386. vm_flags_t vm_flags = vma->vm_flags;
  1387. const struct vm_operations_struct *vm_ops = vma->vm_ops;
  1388. /* If it was private or non-writable, the write bit is already clear */
  1389. if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
  1390. return 0;
  1391. /* The backer wishes to know when pages are first written to? */
  1392. if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
  1393. return 1;
  1394. /* The open routine did something to the protections that pgprot_modify
  1395. * won't preserve? */
  1396. if (pgprot_val(vm_page_prot) !=
  1397. pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
  1398. return 0;
  1399. /*
  1400. * Do we need to track softdirty? hugetlb does not support softdirty
  1401. * tracking yet.
  1402. */
  1403. if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
  1404. return 1;
  1405. /* Do we need write faults for uffd-wp tracking? */
  1406. if (userfaultfd_wp(vma))
  1407. return 1;
  1408. /* Specialty mapping? */
  1409. if (vm_flags & VM_PFNMAP)
  1410. return 0;
  1411. /* Can the mapping track the dirty pages? */
  1412. return vma->vm_file && vma->vm_file->f_mapping &&
  1413. mapping_can_writeback(vma->vm_file->f_mapping);
  1414. }
  1415. /*
  1416. * We account for memory if it's a private writeable mapping,
  1417. * not hugepages and VM_NORESERVE wasn't set.
  1418. */
  1419. static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
  1420. {
  1421. /*
  1422. * hugetlb has its own accounting separate from the core VM
  1423. * VM_HUGETLB may not be set yet so we cannot check for that flag.
  1424. */
  1425. if (file && is_file_hugepages(file))
  1426. return 0;
  1427. return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
  1428. }
  1429. /**
  1430. * unmapped_area() - Find an area between the low_limit and the high_limit with
  1431. * the correct alignment and offset, all from @info. Note: current->mm is used
  1432. * for the search.
  1433. *
  1434. * @info: The unmapped area information including the range (low_limit -
  1435. * hight_limit), the alignment offset and mask.
  1436. *
  1437. * Return: A memory address or -ENOMEM.
  1438. */
  1439. static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
  1440. {
  1441. unsigned long length, gap, low_limit;
  1442. struct vm_area_struct *tmp;
  1443. MA_STATE(mas, &current->mm->mm_mt, 0, 0);
  1444. /* Adjust search length to account for worst case alignment overhead */
  1445. length = info->length + info->align_mask;
  1446. if (length < info->length)
  1447. return -ENOMEM;
  1448. low_limit = info->low_limit;
  1449. retry:
  1450. if (mas_empty_area(&mas, low_limit, info->high_limit - 1, length))
  1451. return -ENOMEM;
  1452. gap = mas.index;
  1453. gap += (info->align_offset - gap) & info->align_mask;
  1454. tmp = mas_next(&mas, ULONG_MAX);
  1455. if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
  1456. if (vm_start_gap(tmp) < gap + length - 1) {
  1457. low_limit = tmp->vm_end;
  1458. mas_reset(&mas);
  1459. goto retry;
  1460. }
  1461. } else {
  1462. tmp = mas_prev(&mas, 0);
  1463. if (tmp && vm_end_gap(tmp) > gap) {
  1464. low_limit = vm_end_gap(tmp);
  1465. mas_reset(&mas);
  1466. goto retry;
  1467. }
  1468. }
  1469. return gap;
  1470. }
  1471. /**
  1472. * unmapped_area_topdown() - Find an area between the low_limit and the
  1473. * high_limit with * the correct alignment and offset at the highest available
  1474. * address, all from @info. Note: current->mm is used for the search.
  1475. *
  1476. * @info: The unmapped area information including the range (low_limit -
  1477. * hight_limit), the alignment offset and mask.
  1478. *
  1479. * Return: A memory address or -ENOMEM.
  1480. */
  1481. static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
  1482. {
  1483. unsigned long length, gap, high_limit, gap_end;
  1484. struct vm_area_struct *tmp;
  1485. MA_STATE(mas, &current->mm->mm_mt, 0, 0);
  1486. /* Adjust search length to account for worst case alignment overhead */
  1487. length = info->length + info->align_mask;
  1488. if (length < info->length)
  1489. return -ENOMEM;
  1490. high_limit = info->high_limit;
  1491. retry:
  1492. if (mas_empty_area_rev(&mas, info->low_limit, high_limit - 1,
  1493. length))
  1494. return -ENOMEM;
  1495. gap = mas.last + 1 - info->length;
  1496. gap -= (gap - info->align_offset) & info->align_mask;
  1497. gap_end = mas.last;
  1498. tmp = mas_next(&mas, ULONG_MAX);
  1499. if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
  1500. if (vm_start_gap(tmp) <= gap_end) {
  1501. high_limit = vm_start_gap(tmp);
  1502. mas_reset(&mas);
  1503. goto retry;
  1504. }
  1505. } else {
  1506. tmp = mas_prev(&mas, 0);
  1507. if (tmp && vm_end_gap(tmp) > gap) {
  1508. high_limit = tmp->vm_start;
  1509. mas_reset(&mas);
  1510. goto retry;
  1511. }
  1512. }
  1513. return gap;
  1514. }
  1515. /*
  1516. * Search for an unmapped address range.
  1517. *
  1518. * We are looking for a range that:
  1519. * - does not intersect with any VMA;
  1520. * - is contained within the [low_limit, high_limit) interval;
  1521. * - is at least the desired size.
  1522. * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
  1523. */
  1524. unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
  1525. {
  1526. unsigned long addr;
  1527. if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
  1528. addr = unmapped_area_topdown(info);
  1529. else
  1530. addr = unmapped_area(info);
  1531. trace_vm_unmapped_area(addr, info);
  1532. return addr;
  1533. }
  1534. EXPORT_SYMBOL_GPL(vm_unmapped_area);
  1535. /* Get an address range which is currently unmapped.
  1536. * For shmat() with addr=0.
  1537. *
  1538. * Ugly calling convention alert:
  1539. * Return value with the low bits set means error value,
  1540. * ie
  1541. * if (ret & ~PAGE_MASK)
  1542. * error = ret;
  1543. *
  1544. * This function "knows" that -ENOMEM has the bits set.
  1545. */
  1546. unsigned long
  1547. generic_get_unmapped_area(struct file *filp, unsigned long addr,
  1548. unsigned long len, unsigned long pgoff,
  1549. unsigned long flags)
  1550. {
  1551. struct mm_struct *mm = current->mm;
  1552. struct vm_area_struct *vma, *prev;
  1553. struct vm_unmapped_area_info info;
  1554. const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
  1555. if (len > mmap_end - mmap_min_addr)
  1556. return -ENOMEM;
  1557. if (flags & MAP_FIXED)
  1558. return addr;
  1559. if (addr) {
  1560. addr = PAGE_ALIGN(addr);
  1561. vma = find_vma_prev(mm, addr, &prev);
  1562. if (mmap_end - len >= addr && addr >= mmap_min_addr &&
  1563. (!vma || addr + len <= vm_start_gap(vma)) &&
  1564. (!prev || addr >= vm_end_gap(prev)))
  1565. return addr;
  1566. }
  1567. info.flags = 0;
  1568. info.length = len;
  1569. info.low_limit = mm->mmap_base;
  1570. info.high_limit = mmap_end;
  1571. info.align_mask = 0;
  1572. info.align_offset = 0;
  1573. return vm_unmapped_area(&info);
  1574. }
  1575. #ifndef HAVE_ARCH_UNMAPPED_AREA
  1576. unsigned long
  1577. arch_get_unmapped_area(struct file *filp, unsigned long addr,
  1578. unsigned long len, unsigned long pgoff,
  1579. unsigned long flags)
  1580. {
  1581. return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
  1582. }
  1583. #endif
  1584. /*
  1585. * This mmap-allocator allocates new areas top-down from below the
  1586. * stack's low limit (the base):
  1587. */
  1588. unsigned long
  1589. generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
  1590. unsigned long len, unsigned long pgoff,
  1591. unsigned long flags)
  1592. {
  1593. struct vm_area_struct *vma, *prev;
  1594. struct mm_struct *mm = current->mm;
  1595. struct vm_unmapped_area_info info;
  1596. const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
  1597. /* requested length too big for entire address space */
  1598. if (len > mmap_end - mmap_min_addr)
  1599. return -ENOMEM;
  1600. if (flags & MAP_FIXED)
  1601. return addr;
  1602. /* requesting a specific address */
  1603. if (addr) {
  1604. addr = PAGE_ALIGN(addr);
  1605. vma = find_vma_prev(mm, addr, &prev);
  1606. if (mmap_end - len >= addr && addr >= mmap_min_addr &&
  1607. (!vma || addr + len <= vm_start_gap(vma)) &&
  1608. (!prev || addr >= vm_end_gap(prev)))
  1609. return addr;
  1610. }
  1611. info.flags = VM_UNMAPPED_AREA_TOPDOWN;
  1612. info.length = len;
  1613. info.low_limit = max(PAGE_SIZE, mmap_min_addr);
  1614. info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
  1615. info.align_mask = 0;
  1616. info.align_offset = 0;
  1617. addr = vm_unmapped_area(&info);
  1618. /*
  1619. * A failed mmap() very likely causes application failure,
  1620. * so fall back to the bottom-up function here. This scenario
  1621. * can happen with large stack limits and large mmap()
  1622. * allocations.
  1623. */
  1624. if (offset_in_page(addr)) {
  1625. VM_BUG_ON(addr != -ENOMEM);
  1626. info.flags = 0;
  1627. info.low_limit = TASK_UNMAPPED_BASE;
  1628. info.high_limit = mmap_end;
  1629. addr = vm_unmapped_area(&info);
  1630. }
  1631. return addr;
  1632. }
  1633. #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
  1634. unsigned long
  1635. arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
  1636. unsigned long len, unsigned long pgoff,
  1637. unsigned long flags)
  1638. {
  1639. return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
  1640. }
  1641. #endif
  1642. unsigned long
  1643. get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
  1644. unsigned long pgoff, unsigned long flags)
  1645. {
  1646. unsigned long (*get_area)(struct file *, unsigned long,
  1647. unsigned long, unsigned long, unsigned long);
  1648. unsigned long error = arch_mmap_check(addr, len, flags);
  1649. if (error)
  1650. return error;
  1651. /* Careful about overflows.. */
  1652. if (len > TASK_SIZE)
  1653. return -ENOMEM;
  1654. get_area = current->mm->get_unmapped_area;
  1655. if (file) {
  1656. if (file->f_op->get_unmapped_area)
  1657. get_area = file->f_op->get_unmapped_area;
  1658. } else if (flags & MAP_SHARED) {
  1659. /*
  1660. * mmap_region() will call shmem_zero_setup() to create a file,
  1661. * so use shmem's get_unmapped_area in case it can be huge.
  1662. * do_mmap() will clear pgoff, so match alignment.
  1663. */
  1664. pgoff = 0;
  1665. get_area = shmem_get_unmapped_area;
  1666. }
  1667. addr = get_area(file, addr, len, pgoff, flags);
  1668. if (IS_ERR_VALUE(addr))
  1669. return addr;
  1670. if (addr > TASK_SIZE - len)
  1671. return -ENOMEM;
  1672. if (offset_in_page(addr))
  1673. return -EINVAL;
  1674. error = security_mmap_addr(addr);
  1675. return error ? error : addr;
  1676. }
  1677. EXPORT_SYMBOL(get_unmapped_area);
  1678. /**
  1679. * find_vma_intersection() - Look up the first VMA which intersects the interval
  1680. * @mm: The process address space.
  1681. * @start_addr: The inclusive start user address.
  1682. * @end_addr: The exclusive end user address.
  1683. *
  1684. * Returns: The first VMA within the provided range, %NULL otherwise. Assumes
  1685. * start_addr < end_addr.
  1686. */
  1687. struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
  1688. unsigned long start_addr,
  1689. unsigned long end_addr)
  1690. {
  1691. unsigned long index = start_addr;
  1692. mmap_assert_locked(mm);
  1693. return mt_find(&mm->mm_mt, &index, end_addr - 1);
  1694. }
  1695. EXPORT_SYMBOL(find_vma_intersection);
  1696. /**
  1697. * find_vma() - Find the VMA for a given address, or the next VMA.
  1698. * @mm: The mm_struct to check
  1699. * @addr: The address
  1700. *
  1701. * Returns: The VMA associated with addr, or the next VMA.
  1702. * May return %NULL in the case of no VMA at addr or above.
  1703. */
  1704. struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
  1705. {
  1706. unsigned long index = addr;
  1707. mmap_assert_locked(mm);
  1708. return mt_find(&mm->mm_mt, &index, ULONG_MAX);
  1709. }
  1710. EXPORT_SYMBOL(find_vma);
  1711. /**
  1712. * find_vma_prev() - Find the VMA for a given address, or the next vma and
  1713. * set %pprev to the previous VMA, if any.
  1714. * @mm: The mm_struct to check
  1715. * @addr: The address
  1716. * @pprev: The pointer to set to the previous VMA
  1717. *
  1718. * Note that RCU lock is missing here since the external mmap_lock() is used
  1719. * instead.
  1720. *
  1721. * Returns: The VMA associated with @addr, or the next vma.
  1722. * May return %NULL in the case of no vma at addr or above.
  1723. */
  1724. struct vm_area_struct *
  1725. find_vma_prev(struct mm_struct *mm, unsigned long addr,
  1726. struct vm_area_struct **pprev)
  1727. {
  1728. struct vm_area_struct *vma;
  1729. MA_STATE(mas, &mm->mm_mt, addr, addr);
  1730. vma = mas_walk(&mas);
  1731. *pprev = mas_prev(&mas, 0);
  1732. if (!vma)
  1733. vma = mas_next(&mas, ULONG_MAX);
  1734. return vma;
  1735. }
  1736. /*
  1737. * Verify that the stack growth is acceptable and
  1738. * update accounting. This is shared with both the
  1739. * grow-up and grow-down cases.
  1740. */
  1741. static int acct_stack_growth(struct vm_area_struct *vma,
  1742. unsigned long size, unsigned long grow)
  1743. {
  1744. struct mm_struct *mm = vma->vm_mm;
  1745. unsigned long new_start;
  1746. /* address space limit tests */
  1747. if (!may_expand_vm(mm, vma->vm_flags, grow))
  1748. return -ENOMEM;
  1749. /* Stack limit test */
  1750. if (size > rlimit(RLIMIT_STACK))
  1751. return -ENOMEM;
  1752. /* mlock limit tests */
  1753. if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
  1754. return -ENOMEM;
  1755. /* Check to ensure the stack will not grow into a hugetlb-only region */
  1756. new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
  1757. vma->vm_end - size;
  1758. if (is_hugepage_only_range(vma->vm_mm, new_start, size))
  1759. return -EFAULT;
  1760. /*
  1761. * Overcommit.. This must be the final test, as it will
  1762. * update security statistics.
  1763. */
  1764. if (security_vm_enough_memory_mm(mm, grow))
  1765. return -ENOMEM;
  1766. return 0;
  1767. }
  1768. #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
  1769. /*
  1770. * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
  1771. * vma is the last one with address > vma->vm_end. Have to extend vma.
  1772. */
  1773. static int expand_upwards(struct vm_area_struct *vma, unsigned long address)
  1774. {
  1775. struct mm_struct *mm = vma->vm_mm;
  1776. struct vm_area_struct *next;
  1777. unsigned long gap_addr;
  1778. int error = 0;
  1779. MA_STATE(mas, &mm->mm_mt, vma->vm_start, address - 1);
  1780. if (!(vma->vm_flags & VM_GROWSUP))
  1781. return -EFAULT;
  1782. /* Guard against exceeding limits of the address space. */
  1783. address &= PAGE_MASK;
  1784. if (address >= (TASK_SIZE & PAGE_MASK))
  1785. return -ENOMEM;
  1786. address += PAGE_SIZE;
  1787. /* Enforce stack_guard_gap */
  1788. gap_addr = address + stack_guard_gap;
  1789. /* Guard against overflow */
  1790. if (gap_addr < address || gap_addr > TASK_SIZE)
  1791. gap_addr = TASK_SIZE;
  1792. next = find_vma_intersection(mm, vma->vm_end, gap_addr);
  1793. if (next && vma_is_accessible(next)) {
  1794. if (!(next->vm_flags & VM_GROWSUP))
  1795. return -ENOMEM;
  1796. /* Check that both stack segments have the same anon_vma? */
  1797. }
  1798. mas->last = address - 1;
  1799. if (mas_preallocate(&mas, vma, GFP_KERNEL))
  1800. return -ENOMEM;
  1801. /* We must make sure the anon_vma is allocated. */
  1802. if (unlikely(anon_vma_prepare(vma))) {
  1803. mas_destroy(&mas);
  1804. return -ENOMEM;
  1805. }
  1806. /* Lock the VMA before expanding to prevent concurrent page faults */
  1807. vma_start_write(vma);
  1808. /*
  1809. * vma->vm_start/vm_end cannot change under us because the caller
  1810. * is required to hold the mmap_lock in read mode. We need the
  1811. * anon_vma lock to serialize against concurrent expand_stacks.
  1812. */
  1813. anon_vma_lock_write(vma->anon_vma);
  1814. /* Somebody else might have raced and expanded it already */
  1815. if (address > vma->vm_end) {
  1816. unsigned long size, grow;
  1817. size = address - vma->vm_start;
  1818. grow = (address - vma->vm_end) >> PAGE_SHIFT;
  1819. error = -ENOMEM;
  1820. if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
  1821. error = acct_stack_growth(vma, size, grow);
  1822. if (!error) {
  1823. /*
  1824. * We only hold a shared mmap_lock lock here, so
  1825. * we need to protect against concurrent vma
  1826. * expansions. anon_vma_lock_write() doesn't
  1827. * help here, as we don't guarantee that all
  1828. * growable vmas in a mm share the same root
  1829. * anon vma. So, we reuse mm->page_table_lock
  1830. * to guard against concurrent vma expansions.
  1831. */
  1832. spin_lock(&mm->page_table_lock);
  1833. if (vma->vm_flags & VM_LOCKED)
  1834. mm->locked_vm += grow;
  1835. vm_stat_account(mm, vma->vm_flags, grow);
  1836. anon_vma_interval_tree_pre_update_vma(vma);
  1837. vma->vm_end = address;
  1838. /* Overwrite old entry in mtree. */
  1839. vma_mas_store(vma, &mas);
  1840. anon_vma_interval_tree_post_update_vma(vma);
  1841. spin_unlock(&mm->page_table_lock);
  1842. perf_event_mmap(vma);
  1843. }
  1844. }
  1845. }
  1846. anon_vma_unlock_write(vma->anon_vma);
  1847. khugepaged_enter_vma(vma, vma->vm_flags);
  1848. mas_destroy(&mas);
  1849. return error;
  1850. }
  1851. #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
  1852. /*
  1853. * vma is the first one with address < vma->vm_start. Have to extend vma.
  1854. * mmap_lock held for writing.
  1855. */
  1856. int expand_downwards(struct vm_area_struct *vma, unsigned long address)
  1857. {
  1858. struct mm_struct *mm = vma->vm_mm;
  1859. MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
  1860. struct vm_area_struct *prev;
  1861. int error = 0;
  1862. if (!(vma->vm_flags & VM_GROWSDOWN))
  1863. return -EFAULT;
  1864. address &= PAGE_MASK;
  1865. if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
  1866. return -EPERM;
  1867. /* Enforce stack_guard_gap */
  1868. prev = mas_prev(&mas, 0);
  1869. /* Check that both stack segments have the same anon_vma? */
  1870. if (prev) {
  1871. if (!(prev->vm_flags & VM_GROWSDOWN) &&
  1872. vma_is_accessible(prev) &&
  1873. (address - prev->vm_end < stack_guard_gap))
  1874. return -ENOMEM;
  1875. }
  1876. mas_set_range(&mas, address, vma->vm_end - 1);
  1877. if (mas_preallocate(&mas, vma, GFP_KERNEL))
  1878. return -ENOMEM;
  1879. /* We must make sure the anon_vma is allocated. */
  1880. if (unlikely(anon_vma_prepare(vma))) {
  1881. mas_destroy(&mas);
  1882. return -ENOMEM;
  1883. }
  1884. /* Lock the VMA before expanding to prevent concurrent page faults */
  1885. vma_start_write(vma);
  1886. /*
  1887. * vma->vm_start/vm_end cannot change under us because the caller
  1888. * is required to hold the mmap_lock in read mode. We need the
  1889. * anon_vma lock to serialize against concurrent expand_stacks.
  1890. */
  1891. anon_vma_lock_write(vma->anon_vma);
  1892. /* Somebody else might have raced and expanded it already */
  1893. if (address < vma->vm_start) {
  1894. unsigned long size, grow;
  1895. size = vma->vm_end - address;
  1896. grow = (vma->vm_start - address) >> PAGE_SHIFT;
  1897. error = -ENOMEM;
  1898. if (grow <= vma->vm_pgoff) {
  1899. error = acct_stack_growth(vma, size, grow);
  1900. if (!error) {
  1901. /*
  1902. * We only hold a shared mmap_lock lock here, so
  1903. * we need to protect against concurrent vma
  1904. * expansions. anon_vma_lock_write() doesn't
  1905. * help here, as we don't guarantee that all
  1906. * growable vmas in a mm share the same root
  1907. * anon vma. So, we reuse mm->page_table_lock
  1908. * to guard against concurrent vma expansions.
  1909. */
  1910. spin_lock(&mm->page_table_lock);
  1911. if (vma->vm_flags & VM_LOCKED)
  1912. mm->locked_vm += grow;
  1913. vm_stat_account(mm, vma->vm_flags, grow);
  1914. anon_vma_interval_tree_pre_update_vma(vma);
  1915. vma->vm_start = address;
  1916. vma->vm_pgoff -= grow;
  1917. /* Overwrite old entry in mtree. */
  1918. vma_mas_store(vma, &mas);
  1919. anon_vma_interval_tree_post_update_vma(vma);
  1920. spin_unlock(&mm->page_table_lock);
  1921. perf_event_mmap(vma);
  1922. }
  1923. }
  1924. }
  1925. anon_vma_unlock_write(vma->anon_vma);
  1926. khugepaged_enter_vma(vma, vma->vm_flags);
  1927. mas_destroy(&mas);
  1928. return error;
  1929. }
  1930. /* enforced gap between the expanding stack and other mappings. */
  1931. unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
  1932. static int __init cmdline_parse_stack_guard_gap(char *p)
  1933. {
  1934. unsigned long val;
  1935. char *endptr;
  1936. val = simple_strtoul(p, &endptr, 10);
  1937. if (!*endptr)
  1938. stack_guard_gap = val << PAGE_SHIFT;
  1939. return 1;
  1940. }
  1941. __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
  1942. #ifdef CONFIG_STACK_GROWSUP
  1943. int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
  1944. {
  1945. return expand_upwards(vma, address);
  1946. }
  1947. struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
  1948. {
  1949. struct vm_area_struct *vma, *prev;
  1950. addr &= PAGE_MASK;
  1951. vma = find_vma_prev(mm, addr, &prev);
  1952. if (vma && (vma->vm_start <= addr))
  1953. return vma;
  1954. if (!prev)
  1955. return NULL;
  1956. if (expand_stack_locked(prev, addr))
  1957. return NULL;
  1958. if (prev->vm_flags & VM_LOCKED)
  1959. populate_vma_page_range(prev, addr, prev->vm_end, NULL);
  1960. return prev;
  1961. }
  1962. #else
  1963. int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
  1964. {
  1965. if (unlikely(!(vma->vm_flags & VM_GROWSDOWN)))
  1966. return -EINVAL;
  1967. return expand_downwards(vma, address);
  1968. }
  1969. struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
  1970. {
  1971. struct vm_area_struct *vma;
  1972. unsigned long start;
  1973. addr &= PAGE_MASK;
  1974. vma = find_vma(mm, addr);
  1975. if (!vma)
  1976. return NULL;
  1977. if (vma->vm_start <= addr)
  1978. return vma;
  1979. start = vma->vm_start;
  1980. if (expand_stack_locked(vma, addr))
  1981. return NULL;
  1982. if (vma->vm_flags & VM_LOCKED)
  1983. populate_vma_page_range(vma, addr, start, NULL);
  1984. return vma;
  1985. }
  1986. #endif
  1987. /*
  1988. * ANDROID: Reintroduce find_extend_vma() as it's still used by some external
  1989. * modules. It was removed in commit 8d7071af8907 ("mm: always expand the
  1990. * stack with the mmap write lock held")
  1991. * In the future, everyone should just move to use the correct function instead
  1992. * of this old, legacy one.
  1993. */
  1994. struct vm_area_struct *find_extend_vma(struct mm_struct *mm,
  1995. unsigned long addr)
  1996. {
  1997. return find_extend_vma_locked(mm, addr);
  1998. }
  1999. EXPORT_SYMBOL_GPL(find_extend_vma);
  2000. /*
  2001. * IA64 has some horrid mapping rules: it can expand both up and down,
  2002. * but with various special rules.
  2003. *
  2004. * We'll get rid of this architecture eventually, so the ugliness is
  2005. * temporary.
  2006. */
  2007. #ifdef CONFIG_IA64
  2008. static inline bool vma_expand_ok(struct vm_area_struct *vma, unsigned long addr)
  2009. {
  2010. return REGION_NUMBER(addr) == REGION_NUMBER(vma->vm_start) &&
  2011. REGION_OFFSET(addr) < RGN_MAP_LIMIT;
  2012. }
  2013. /*
  2014. * IA64 stacks grow down, but there's a special register backing store
  2015. * that can grow up. Only sequentially, though, so the new address must
  2016. * match vm_end.
  2017. */
  2018. static inline int vma_expand_up(struct vm_area_struct *vma, unsigned long addr)
  2019. {
  2020. if (!vma_expand_ok(vma, addr))
  2021. return -EFAULT;
  2022. if (vma->vm_end != (addr & PAGE_MASK))
  2023. return -EFAULT;
  2024. return expand_upwards(vma, addr);
  2025. }
  2026. static inline bool vma_expand_down(struct vm_area_struct *vma, unsigned long addr)
  2027. {
  2028. if (!vma_expand_ok(vma, addr))
  2029. return -EFAULT;
  2030. return expand_downwards(vma, addr);
  2031. }
  2032. #elif defined(CONFIG_STACK_GROWSUP)
  2033. #define vma_expand_up(vma,addr) expand_upwards(vma, addr)
  2034. #define vma_expand_down(vma, addr) (-EFAULT)
  2035. #else
  2036. #define vma_expand_up(vma,addr) (-EFAULT)
  2037. #define vma_expand_down(vma, addr) expand_downwards(vma, addr)
  2038. #endif
  2039. /*
  2040. * expand_stack(): legacy interface for page faulting. Don't use unless
  2041. * you have to.
  2042. *
  2043. * This is called with the mm locked for reading, drops the lock, takes
  2044. * the lock for writing, tries to look up a vma again, expands it if
  2045. * necessary, and downgrades the lock to reading again.
  2046. *
  2047. * If no vma is found or it can't be expanded, it returns NULL and has
  2048. * dropped the lock.
  2049. */
  2050. struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
  2051. {
  2052. struct vm_area_struct *vma, *prev;
  2053. mmap_read_unlock(mm);
  2054. if (mmap_write_lock_killable(mm))
  2055. return NULL;
  2056. vma = find_vma_prev(mm, addr, &prev);
  2057. if (vma && vma->vm_start <= addr)
  2058. goto success;
  2059. if (prev && !vma_expand_up(prev, addr)) {
  2060. vma = prev;
  2061. goto success;
  2062. }
  2063. if (vma && !vma_expand_down(vma, addr))
  2064. goto success;
  2065. mmap_write_unlock(mm);
  2066. return NULL;
  2067. success:
  2068. mmap_write_downgrade(mm);
  2069. return vma;
  2070. }
  2071. /*
  2072. * Ok - we have the memory areas we should free on a maple tree so release them,
  2073. * and do the vma updates.
  2074. *
  2075. * Called with the mm semaphore held.
  2076. */
  2077. static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
  2078. {
  2079. unsigned long nr_accounted = 0;
  2080. struct vm_area_struct *vma;
  2081. /* Update high watermark before we lower total_vm */
  2082. update_hiwater_vm(mm);
  2083. mas_for_each(mas, vma, ULONG_MAX) {
  2084. long nrpages = vma_pages(vma);
  2085. if (vma->vm_flags & VM_ACCOUNT)
  2086. nr_accounted += nrpages;
  2087. vm_stat_account(mm, vma->vm_flags, -nrpages);
  2088. remove_vma(vma, false);
  2089. }
  2090. vm_unacct_memory(nr_accounted);
  2091. validate_mm(mm);
  2092. }
  2093. /*
  2094. * Get rid of page table information in the indicated region.
  2095. *
  2096. * Called with the mm semaphore held.
  2097. */
  2098. static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
  2099. struct vm_area_struct *vma, struct vm_area_struct *prev,
  2100. struct vm_area_struct *next, unsigned long start,
  2101. unsigned long end, unsigned long start_t, unsigned long end_t,
  2102. bool mm_wr_locked)
  2103. {
  2104. struct mmu_gather tlb;
  2105. lru_add_drain();
  2106. tlb_gather_mmu(&tlb, mm);
  2107. update_hiwater_rss(mm);
  2108. unmap_vmas(&tlb, mt, vma, start, end, start_t, end_t, mm_wr_locked);
  2109. free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
  2110. next ? next->vm_start : USER_PGTABLES_CEILING, start_t,
  2111. mm_wr_locked);
  2112. tlb_finish_mmu(&tlb);
  2113. }
  2114. /*
  2115. * __split_vma() bypasses sysctl_max_map_count checking. We use this where it
  2116. * has already been checked or doesn't make sense to fail.
  2117. */
  2118. int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
  2119. unsigned long addr, int new_below)
  2120. {
  2121. struct vm_area_struct *new;
  2122. int err;
  2123. validate_mm_mt(mm);
  2124. vma_start_write(vma);
  2125. if (vma->vm_ops && vma->vm_ops->may_split) {
  2126. err = vma->vm_ops->may_split(vma, addr);
  2127. if (err)
  2128. return err;
  2129. }
  2130. new = vm_area_dup(vma);
  2131. if (!new)
  2132. return -ENOMEM;
  2133. if (new_below)
  2134. new->vm_end = addr;
  2135. else {
  2136. new->vm_start = addr;
  2137. new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
  2138. }
  2139. err = vma_dup_policy(vma, new);
  2140. if (err)
  2141. goto out_free_vma;
  2142. err = anon_vma_clone(new, vma);
  2143. if (err)
  2144. goto out_free_mpol;
  2145. if (new->vm_file)
  2146. get_file(new->vm_file);
  2147. if (new->vm_ops && new->vm_ops->open)
  2148. new->vm_ops->open(new);
  2149. vma_start_write(vma);
  2150. vma_start_write(new);
  2151. if (new_below)
  2152. err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
  2153. ((addr - new->vm_start) >> PAGE_SHIFT), new);
  2154. else
  2155. err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
  2156. /* Success. */
  2157. if (!err)
  2158. return 0;
  2159. /* Avoid vm accounting in close() operation */
  2160. new->vm_start = new->vm_end;
  2161. new->vm_pgoff = 0;
  2162. /* Clean everything up if vma_adjust failed. */
  2163. if (new->vm_ops && new->vm_ops->close)
  2164. new->vm_ops->close(new);
  2165. if (new->vm_file)
  2166. fput(new->vm_file);
  2167. unlink_anon_vmas(new);
  2168. out_free_mpol:
  2169. mpol_put(vma_policy(new));
  2170. out_free_vma:
  2171. vm_area_free(new);
  2172. validate_mm_mt(mm);
  2173. return err;
  2174. }
  2175. /*
  2176. * Split a vma into two pieces at address 'addr', a new vma is allocated
  2177. * either for the first part or the tail.
  2178. */
  2179. int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
  2180. unsigned long addr, int new_below)
  2181. {
  2182. if (mm->map_count >= sysctl_max_map_count)
  2183. return -ENOMEM;
  2184. return __split_vma(mm, vma, addr, new_below);
  2185. }
  2186. /*
  2187. * do_mas_align_munmap() - munmap the aligned region from @start to @end.
  2188. * @mas: The maple_state, ideally set up to alter the correct tree location.
  2189. * @vma: The starting vm_area_struct
  2190. * @mm: The mm_struct
  2191. * @start: The aligned start address to munmap.
  2192. * @end: The aligned end address to munmap.
  2193. * @uf: The userfaultfd list_head
  2194. * @downgrade: Set to true to attempt a write downgrade of the mmap_sem
  2195. *
  2196. * If @downgrade is true, check return code for potential release of the lock.
  2197. */
  2198. static int
  2199. do_mas_align_munmap(struct ma_state *mas, struct vm_area_struct *vma,
  2200. struct mm_struct *mm, unsigned long start,
  2201. unsigned long end, struct list_head *uf, bool downgrade)
  2202. {
  2203. struct vm_area_struct *prev, *next = NULL;
  2204. struct maple_tree mt_detach;
  2205. int count = 0;
  2206. int error = -ENOMEM;
  2207. unsigned long locked_vm = 0;
  2208. MA_STATE(mas_detach, &mt_detach, 0, 0);
  2209. mt_init_flags(&mt_detach, mas->tree->ma_flags & MT_FLAGS_LOCK_MASK);
  2210. mt_set_external_lock(&mt_detach, &mm->mmap_lock);
  2211. mas->last = end - 1;
  2212. /*
  2213. * If we need to split any vma, do it now to save pain later.
  2214. *
  2215. * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
  2216. * unmapped vm_area_struct will remain in use: so lower split_vma
  2217. * places tmp vma above, and higher split_vma places tmp vma below.
  2218. */
  2219. /* Does it split the first one? */
  2220. if (start > vma->vm_start) {
  2221. /*
  2222. * Make sure that map_count on return from munmap() will
  2223. * not exceed its limit; but let map_count go just above
  2224. * its limit temporarily, to help free resources as expected.
  2225. */
  2226. if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
  2227. goto map_count_exceeded;
  2228. /*
  2229. * mas_pause() is not needed since mas->index needs to be set
  2230. * differently than vma->vm_end anyways.
  2231. */
  2232. error = __split_vma(mm, vma, start, 0);
  2233. if (error)
  2234. goto start_split_failed;
  2235. mas_set(mas, start);
  2236. vma = mas_walk(mas);
  2237. }
  2238. prev = mas_prev(mas, 0);
  2239. if (unlikely((!prev)))
  2240. mas_set(mas, start);
  2241. /*
  2242. * Detach a range of VMAs from the mm. Using next as a temp variable as
  2243. * it is always overwritten.
  2244. */
  2245. mas_for_each(mas, next, end - 1) {
  2246. /* Does it split the end? */
  2247. if (next->vm_end > end) {
  2248. struct vm_area_struct *split;
  2249. error = __split_vma(mm, next, end, 1);
  2250. if (error)
  2251. goto end_split_failed;
  2252. mas_set(mas, end);
  2253. split = mas_prev(mas, 0);
  2254. vma_start_write(split);
  2255. mas_set(&mas_detach, count);
  2256. error = mas_store_gfp(&mas_detach, split, GFP_KERNEL);
  2257. if (error)
  2258. goto munmap_gather_failed;
  2259. vma_mark_detached(split, true);
  2260. if (split->vm_flags & VM_LOCKED)
  2261. locked_vm += vma_pages(split);
  2262. count++;
  2263. if (vma == next)
  2264. vma = split;
  2265. break;
  2266. }
  2267. vma_start_write(next);
  2268. mas_set(&mas_detach, count);
  2269. error = mas_store_gfp(&mas_detach, next, GFP_KERNEL);
  2270. if (error)
  2271. goto munmap_gather_failed;
  2272. vma_mark_detached(next, true);
  2273. if (next->vm_flags & VM_LOCKED)
  2274. locked_vm += vma_pages(next);
  2275. count++;
  2276. if (unlikely(uf)) {
  2277. /*
  2278. * If userfaultfd_unmap_prep returns an error the vmas
  2279. * will remain split, but userland will get a
  2280. * highly unexpected error anyway. This is no
  2281. * different than the case where the first of the two
  2282. * __split_vma fails, but we don't undo the first
  2283. * split, despite we could. This is unlikely enough
  2284. * failure that it's not worth optimizing it for.
  2285. */
  2286. error = userfaultfd_unmap_prep(next, start, end, uf);
  2287. if (error)
  2288. goto userfaultfd_error;
  2289. }
  2290. #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
  2291. BUG_ON(next->vm_start < start);
  2292. BUG_ON(next->vm_start > end);
  2293. #endif
  2294. }
  2295. if (mas->last >= end)
  2296. next = mas_walk(mas);
  2297. if (!next)
  2298. next = mas_next(mas, ULONG_MAX);
  2299. #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
  2300. /* Make sure no VMAs are about to be lost. */
  2301. {
  2302. MA_STATE(test, &mt_detach, 0, 0);
  2303. struct vm_area_struct *vma_mas, *vma_test;
  2304. int test_count = 0;
  2305. unsigned long s, e;
  2306. mas_set_range(mas, start, end - 1);
  2307. rcu_read_lock();
  2308. vma_test = mas_find(&test, count - 1);
  2309. mas_for_each(mas, vma_mas, end - 1) {
  2310. if (!test_count)
  2311. s = vma_mas->vm_start;
  2312. BUG_ON(vma_mas != vma_test);
  2313. test_count++;
  2314. if (test_count == count)
  2315. e = vma_mas->vm_end;
  2316. vma_test = mas_next(&test, count - 1);
  2317. }
  2318. rcu_read_unlock();
  2319. BUG_ON(count != test_count);
  2320. }
  2321. #endif
  2322. /* Point of no return */
  2323. mas_set_range(mas, start, end - 1);
  2324. if (mas_store_gfp(mas, NULL, GFP_KERNEL))
  2325. return -ENOMEM;
  2326. mm->locked_vm -= locked_vm;
  2327. mm->map_count -= count;
  2328. /*
  2329. * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
  2330. * VM_GROWSUP VMA. Such VMAs can change their size under
  2331. * down_read(mmap_lock) and collide with the VMA we are about to unmap.
  2332. */
  2333. if (downgrade) {
  2334. if (next && (next->vm_flags & VM_GROWSDOWN))
  2335. downgrade = false;
  2336. else if (prev && (prev->vm_flags & VM_GROWSUP))
  2337. downgrade = false;
  2338. else
  2339. mmap_write_downgrade(mm);
  2340. }
  2341. /*
  2342. * We can free page tables without write-locking mmap_lock because VMAs
  2343. * were isolated before we downgraded mmap_lock.
  2344. */
  2345. unmap_region(mm, &mt_detach, vma, prev, next, start, end, 1, count,
  2346. !downgrade);
  2347. /* Statistics and freeing VMAs */
  2348. mas_set(&mas_detach, 0);
  2349. remove_mt(mm, &mas_detach);
  2350. __mt_destroy(&mt_detach);
  2351. validate_mm(mm);
  2352. return downgrade ? 1 : 0;
  2353. userfaultfd_error:
  2354. munmap_gather_failed:
  2355. end_split_failed:
  2356. __mt_destroy(&mt_detach);
  2357. start_split_failed:
  2358. map_count_exceeded:
  2359. return error;
  2360. }
  2361. /*
  2362. * do_mas_munmap() - munmap a given range.
  2363. * @mas: The maple state
  2364. * @mm: The mm_struct
  2365. * @start: The start address to munmap
  2366. * @len: The length of the range to munmap
  2367. * @uf: The userfaultfd list_head
  2368. * @downgrade: set to true if the user wants to attempt to write_downgrade the
  2369. * mmap_sem
  2370. *
  2371. * This function takes a @mas that is either pointing to the previous VMA or set
  2372. * to MA_START and sets it up to remove the mapping(s). The @len will be
  2373. * aligned and any arch_unmap work will be preformed.
  2374. *
  2375. * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
  2376. */
  2377. int do_mas_munmap(struct ma_state *mas, struct mm_struct *mm,
  2378. unsigned long start, size_t len, struct list_head *uf,
  2379. bool downgrade)
  2380. {
  2381. unsigned long end;
  2382. struct vm_area_struct *vma;
  2383. if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
  2384. return -EINVAL;
  2385. end = start + PAGE_ALIGN(len);
  2386. if (end == start)
  2387. return -EINVAL;
  2388. /* arch_unmap() might do unmaps itself. */
  2389. arch_unmap(mm, start, end);
  2390. /* Find the first overlapping VMA */
  2391. vma = mas_find(mas, end - 1);
  2392. if (!vma)
  2393. return 0;
  2394. return do_mas_align_munmap(mas, vma, mm, start, end, uf, downgrade);
  2395. }
  2396. /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
  2397. * @mm: The mm_struct
  2398. * @start: The start address to munmap
  2399. * @len: The length to be munmapped.
  2400. * @uf: The userfaultfd list_head
  2401. */
  2402. int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
  2403. struct list_head *uf)
  2404. {
  2405. MA_STATE(mas, &mm->mm_mt, start, start);
  2406. return do_mas_munmap(&mas, mm, start, len, uf, false);
  2407. }
  2408. unsigned long mmap_region(struct file *file, unsigned long addr,
  2409. unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
  2410. struct list_head *uf)
  2411. {
  2412. struct mm_struct *mm = current->mm;
  2413. struct vm_area_struct *vma = NULL;
  2414. struct vm_area_struct *next, *prev, *merge;
  2415. pgoff_t pglen = len >> PAGE_SHIFT;
  2416. unsigned long charged = 0;
  2417. unsigned long end = addr + len;
  2418. unsigned long merge_start = addr, merge_end = end;
  2419. pgoff_t vm_pgoff;
  2420. int error;
  2421. MA_STATE(mas, &mm->mm_mt, addr, end - 1);
  2422. /* Check against address space limit. */
  2423. if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
  2424. unsigned long nr_pages;
  2425. /*
  2426. * MAP_FIXED may remove pages of mappings that intersects with
  2427. * requested mapping. Account for the pages it would unmap.
  2428. */
  2429. nr_pages = count_vma_pages_range(mm, addr, end);
  2430. if (!may_expand_vm(mm, vm_flags,
  2431. (len >> PAGE_SHIFT) - nr_pages))
  2432. return -ENOMEM;
  2433. }
  2434. /* Unmap any existing mapping in the area */
  2435. if (do_mas_munmap(&mas, mm, addr, len, uf, false))
  2436. return -ENOMEM;
  2437. /*
  2438. * Private writable mapping: check memory availability
  2439. */
  2440. if (accountable_mapping(file, vm_flags)) {
  2441. charged = len >> PAGE_SHIFT;
  2442. if (security_vm_enough_memory_mm(mm, charged))
  2443. return -ENOMEM;
  2444. vm_flags |= VM_ACCOUNT;
  2445. }
  2446. next = mas_next(&mas, ULONG_MAX);
  2447. prev = mas_prev(&mas, 0);
  2448. if (vm_flags & VM_SPECIAL)
  2449. goto cannot_expand;
  2450. /* Attempt to expand an old mapping */
  2451. /* Check next */
  2452. if (next)
  2453. vma_start_write(next);
  2454. if (next && next->vm_start == end && !vma_policy(next) &&
  2455. can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
  2456. NULL_VM_UFFD_CTX, NULL)) {
  2457. merge_end = next->vm_end;
  2458. vma = next;
  2459. vm_pgoff = next->vm_pgoff - pglen;
  2460. }
  2461. /* Check prev */
  2462. if (prev)
  2463. vma_start_write(prev);
  2464. if (prev && prev->vm_end == addr && !vma_policy(prev) &&
  2465. (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
  2466. pgoff, vma->vm_userfaultfd_ctx, NULL) :
  2467. can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
  2468. NULL_VM_UFFD_CTX, NULL))) {
  2469. merge_start = prev->vm_start;
  2470. vma = prev;
  2471. vm_pgoff = prev->vm_pgoff;
  2472. }
  2473. /* Actually expand, if possible */
  2474. if (vma &&
  2475. !vma_expand(&mas, vma, merge_start, merge_end, vm_pgoff, next)) {
  2476. khugepaged_enter_vma(vma, vm_flags);
  2477. goto expanded;
  2478. }
  2479. cannot_expand:
  2480. if (prev)
  2481. mas_next_range(&mas, ULONG_MAX);
  2482. BUG_ON(mas.last < addr);
  2483. BUG_ON(mas.index > end - 1);
  2484. mas.index = addr;
  2485. mas.last = end - 1;
  2486. /*
  2487. * Determine the object being mapped and call the appropriate
  2488. * specific mapper. the address has already been validated, but
  2489. * not unmapped, but the maps are removed from the list.
  2490. */
  2491. vma = vm_area_alloc(mm);
  2492. if (!vma) {
  2493. error = -ENOMEM;
  2494. goto unacct_error;
  2495. }
  2496. vma->vm_start = addr;
  2497. vma->vm_end = end;
  2498. vm_flags_init(vma, vm_flags);
  2499. vma->vm_page_prot = vm_get_page_prot(vm_flags);
  2500. vma->vm_pgoff = pgoff;
  2501. if (file) {
  2502. if (vm_flags & VM_SHARED) {
  2503. error = mapping_map_writable(file->f_mapping);
  2504. if (error)
  2505. goto free_vma;
  2506. }
  2507. vma->vm_file = get_file(file);
  2508. error = call_mmap(file, vma);
  2509. if (error)
  2510. goto unmap_and_free_vma;
  2511. /*
  2512. * Expansion is handled above, merging is handled below.
  2513. * Drivers should not alter the address of the VMA.
  2514. */
  2515. if (WARN_ON((addr != vma->vm_start))) {
  2516. error = -EINVAL;
  2517. goto close_and_free_vma;
  2518. }
  2519. mas_reset(&mas);
  2520. /*
  2521. * If vm_flags changed after call_mmap(), we should try merge
  2522. * vma again as we may succeed this time.
  2523. */
  2524. if (unlikely(vm_flags != vma->vm_flags && prev)) {
  2525. merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
  2526. NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
  2527. if (merge) {
  2528. /*
  2529. * ->mmap() can change vma->vm_file and fput
  2530. * the original file. So fput the vma->vm_file
  2531. * here or we would add an extra fput for file
  2532. * and cause general protection fault
  2533. * ultimately.
  2534. */
  2535. fput(vma->vm_file);
  2536. vm_area_free(vma);
  2537. vma = merge;
  2538. /* Update vm_flags to pick up the change. */
  2539. vm_flags = vma->vm_flags;
  2540. goto unmap_writable;
  2541. }
  2542. }
  2543. vm_flags = vma->vm_flags;
  2544. } else if (vm_flags & VM_SHARED) {
  2545. error = shmem_zero_setup(vma);
  2546. if (error)
  2547. goto free_vma;
  2548. } else {
  2549. vma_set_anonymous(vma);
  2550. }
  2551. /* Allow architectures to sanity-check the vm_flags */
  2552. if (!arch_validate_flags(vma->vm_flags)) {
  2553. error = -EINVAL;
  2554. if (file)
  2555. goto close_and_free_vma;
  2556. else if (vma->vm_file)
  2557. goto unmap_and_free_vma;
  2558. else
  2559. goto free_vma;
  2560. }
  2561. if (mas_preallocate(&mas, vma, GFP_KERNEL)) {
  2562. error = -ENOMEM;
  2563. if (file)
  2564. goto close_and_free_vma;
  2565. else if (vma->vm_file)
  2566. goto unmap_and_free_vma;
  2567. else
  2568. goto free_vma;
  2569. }
  2570. /* Lock the VMA since it is modified after insertion into VMA tree */
  2571. vma_start_write(vma);
  2572. if (vma->vm_file)
  2573. i_mmap_lock_write(vma->vm_file->f_mapping);
  2574. mas_store_prealloc(&mas, vma);
  2575. mm->map_count++;
  2576. if (vma->vm_file) {
  2577. if (vma->vm_flags & VM_SHARED)
  2578. mapping_allow_writable(vma->vm_file->f_mapping);
  2579. flush_dcache_mmap_lock(vma->vm_file->f_mapping);
  2580. vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
  2581. flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
  2582. i_mmap_unlock_write(vma->vm_file->f_mapping);
  2583. }
  2584. /*
  2585. * vma_merge() calls khugepaged_enter_vma() either, the below
  2586. * call covers the non-merge case.
  2587. */
  2588. khugepaged_enter_vma(vma, vma->vm_flags);
  2589. /* Once vma denies write, undo our temporary denial count */
  2590. unmap_writable:
  2591. if (file && vm_flags & VM_SHARED)
  2592. mapping_unmap_writable(file->f_mapping);
  2593. file = vma->vm_file;
  2594. expanded:
  2595. perf_event_mmap(vma);
  2596. vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
  2597. if (vm_flags & VM_LOCKED) {
  2598. if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
  2599. is_vm_hugetlb_page(vma) ||
  2600. vma == get_gate_vma(current->mm))
  2601. vm_flags_clear(vma, VM_LOCKED_MASK);
  2602. else
  2603. mm->locked_vm += (len >> PAGE_SHIFT);
  2604. }
  2605. if (file)
  2606. uprobe_mmap(vma);
  2607. /*
  2608. * New (or expanded) vma always get soft dirty status.
  2609. * Otherwise user-space soft-dirty page tracker won't
  2610. * be able to distinguish situation when vma area unmapped,
  2611. * then new mapped in-place (which must be aimed as
  2612. * a completely new data area).
  2613. */
  2614. vm_flags_set(vma, VM_SOFTDIRTY);
  2615. vma_set_page_prot(vma);
  2616. trace_android_vh_mmap_region(vma, addr);
  2617. validate_mm(mm);
  2618. return addr;
  2619. close_and_free_vma:
  2620. if (vma->vm_ops && vma->vm_ops->close)
  2621. vma->vm_ops->close(vma);
  2622. unmap_and_free_vma:
  2623. fput(vma->vm_file);
  2624. vma->vm_file = NULL;
  2625. /* Undo any partial mapping done by a device driver. */
  2626. unmap_region(mm, mas.tree, vma, prev, next, vma->vm_start, vma->vm_end,
  2627. vma->vm_end, vma->vm_end, true);
  2628. if (file && (vm_flags & VM_SHARED))
  2629. mapping_unmap_writable(file->f_mapping);
  2630. free_vma:
  2631. vm_area_free(vma);
  2632. unacct_error:
  2633. if (charged)
  2634. vm_unacct_memory(charged);
  2635. validate_mm(mm);
  2636. return error;
  2637. }
  2638. static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
  2639. {
  2640. int ret;
  2641. struct mm_struct *mm = current->mm;
  2642. LIST_HEAD(uf);
  2643. MA_STATE(mas, &mm->mm_mt, start, start + len);
  2644. if (mmap_write_lock_killable(mm))
  2645. return -EINTR;
  2646. ret = do_mas_munmap(&mas, mm, start, len, &uf, downgrade);
  2647. /*
  2648. * Returning 1 indicates mmap_lock is downgraded.
  2649. * But 1 is not legal return value of vm_munmap() and munmap(), reset
  2650. * it to 0 before return.
  2651. */
  2652. if (ret == 1) {
  2653. mmap_read_unlock(mm);
  2654. ret = 0;
  2655. } else
  2656. mmap_write_unlock(mm);
  2657. userfaultfd_unmap_complete(mm, &uf);
  2658. return ret;
  2659. }
  2660. int vm_munmap(unsigned long start, size_t len)
  2661. {
  2662. return __vm_munmap(start, len, false);
  2663. }
  2664. EXPORT_SYMBOL(vm_munmap);
  2665. SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
  2666. {
  2667. addr = untagged_addr(addr);
  2668. profile_munmap(addr);
  2669. return __vm_munmap(addr, len, true);
  2670. }
  2671. /*
  2672. * Emulation of deprecated remap_file_pages() syscall.
  2673. */
  2674. SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
  2675. unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
  2676. {
  2677. struct mm_struct *mm = current->mm;
  2678. struct vm_area_struct *vma;
  2679. unsigned long populate = 0;
  2680. unsigned long ret = -EINVAL;
  2681. struct file *file;
  2682. pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
  2683. current->comm, current->pid);
  2684. if (prot)
  2685. return ret;
  2686. start = start & PAGE_MASK;
  2687. size = size & PAGE_MASK;
  2688. if (start + size <= start)
  2689. return ret;
  2690. /* Does pgoff wrap? */
  2691. if (pgoff + (size >> PAGE_SHIFT) < pgoff)
  2692. return ret;
  2693. if (mmap_write_lock_killable(mm))
  2694. return -EINTR;
  2695. vma = vma_lookup(mm, start);
  2696. if (!vma || !(vma->vm_flags & VM_SHARED))
  2697. goto out;
  2698. if (start + size > vma->vm_end) {
  2699. VMA_ITERATOR(vmi, mm, vma->vm_end);
  2700. struct vm_area_struct *next, *prev = vma;
  2701. for_each_vma_range(vmi, next, start + size) {
  2702. /* hole between vmas ? */
  2703. if (next->vm_start != prev->vm_end)
  2704. goto out;
  2705. if (next->vm_file != vma->vm_file)
  2706. goto out;
  2707. if (next->vm_flags != vma->vm_flags)
  2708. goto out;
  2709. if (start + size <= next->vm_end)
  2710. break;
  2711. prev = next;
  2712. }
  2713. if (!next)
  2714. goto out;
  2715. }
  2716. prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
  2717. prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
  2718. prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
  2719. flags &= MAP_NONBLOCK;
  2720. flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
  2721. if (vma->vm_flags & VM_LOCKED)
  2722. flags |= MAP_LOCKED;
  2723. file = get_file(vma->vm_file);
  2724. ret = do_mmap(vma->vm_file, start, size,
  2725. prot, flags, pgoff, &populate, NULL);
  2726. fput(file);
  2727. out:
  2728. mmap_write_unlock(mm);
  2729. if (populate)
  2730. mm_populate(ret, populate);
  2731. if (!IS_ERR_VALUE(ret))
  2732. ret = 0;
  2733. return ret;
  2734. }
  2735. /*
  2736. * brk_munmap() - Unmap a parital vma.
  2737. * @mas: The maple tree state.
  2738. * @vma: The vma to be modified
  2739. * @newbrk: the start of the address to unmap
  2740. * @oldbrk: The end of the address to unmap
  2741. * @uf: The userfaultfd list_head
  2742. *
  2743. * Returns: 1 on success.
  2744. * unmaps a partial VMA mapping. Does not handle alignment, downgrades lock if
  2745. * possible.
  2746. */
  2747. static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
  2748. unsigned long newbrk, unsigned long oldbrk,
  2749. struct list_head *uf)
  2750. {
  2751. struct mm_struct *mm = vma->vm_mm;
  2752. int ret;
  2753. arch_unmap(mm, newbrk, oldbrk);
  2754. ret = do_mas_align_munmap(mas, vma, mm, newbrk, oldbrk, uf, true);
  2755. validate_mm_mt(mm);
  2756. return ret;
  2757. }
  2758. /*
  2759. * do_brk_flags() - Increase the brk vma if the flags match.
  2760. * @mas: The maple tree state.
  2761. * @addr: The start address
  2762. * @len: The length of the increase
  2763. * @vma: The vma,
  2764. * @flags: The VMA Flags
  2765. *
  2766. * Extend the brk VMA from addr to addr + len. If the VMA is NULL or the flags
  2767. * do not match then create a new anonymous VMA. Eventually we may be able to
  2768. * do some brk-specific accounting here.
  2769. */
  2770. static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *vma,
  2771. unsigned long addr, unsigned long len, unsigned long flags)
  2772. {
  2773. struct mm_struct *mm = current->mm;
  2774. validate_mm_mt(mm);
  2775. /*
  2776. * Check against address space limits by the changed size
  2777. * Note: This happens *after* clearing old mappings in some code paths.
  2778. */
  2779. flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
  2780. if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
  2781. return -ENOMEM;
  2782. if (mm->map_count > sysctl_max_map_count)
  2783. return -ENOMEM;
  2784. if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
  2785. return -ENOMEM;
  2786. if (vma)
  2787. vma_start_write(vma);
  2788. /*
  2789. * Expand the existing vma if possible; Note that singular lists do not
  2790. * occur after forking, so the expand will only happen on new VMAs.
  2791. */
  2792. if (vma && vma->vm_end == addr && !vma_policy(vma) &&
  2793. can_vma_merge_after(vma, flags, NULL, NULL,
  2794. addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
  2795. mas_set_range(mas, vma->vm_start, addr + len - 1);
  2796. if (mas_preallocate(mas, vma, GFP_KERNEL))
  2797. return -ENOMEM;
  2798. /* Set flags first to implicitly lock the VMA before updates */
  2799. vm_flags_set(vma, VM_SOFTDIRTY);
  2800. vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
  2801. if (vma->anon_vma) {
  2802. anon_vma_lock_write(vma->anon_vma);
  2803. anon_vma_interval_tree_pre_update_vma(vma);
  2804. }
  2805. vma->vm_end = addr + len;
  2806. mas_store_prealloc(mas, vma);
  2807. if (vma->anon_vma) {
  2808. anon_vma_interval_tree_post_update_vma(vma);
  2809. anon_vma_unlock_write(vma->anon_vma);
  2810. }
  2811. khugepaged_enter_vma(vma, flags);
  2812. goto out;
  2813. }
  2814. /* create a vma struct for an anonymous mapping */
  2815. vma = vm_area_alloc(mm);
  2816. if (!vma)
  2817. goto vma_alloc_fail;
  2818. vma_set_anonymous(vma);
  2819. vma->vm_start = addr;
  2820. vma->vm_end = addr + len;
  2821. vma->vm_pgoff = addr >> PAGE_SHIFT;
  2822. vm_flags_init(vma, flags);
  2823. vma->vm_page_prot = vm_get_page_prot(flags);
  2824. vma_start_write(vma);
  2825. mas_set_range(mas, vma->vm_start, addr + len - 1);
  2826. if (mas_store_gfp(mas, vma, GFP_KERNEL))
  2827. goto mas_store_fail;
  2828. mm->map_count++;
  2829. out:
  2830. perf_event_mmap(vma);
  2831. mm->total_vm += len >> PAGE_SHIFT;
  2832. mm->data_vm += len >> PAGE_SHIFT;
  2833. if (flags & VM_LOCKED)
  2834. mm->locked_vm += (len >> PAGE_SHIFT);
  2835. vm_flags_set(vma, VM_SOFTDIRTY);
  2836. validate_mm(mm);
  2837. return 0;
  2838. mas_store_fail:
  2839. vm_area_free(vma);
  2840. vma_alloc_fail:
  2841. vm_unacct_memory(len >> PAGE_SHIFT);
  2842. return -ENOMEM;
  2843. }
  2844. int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
  2845. {
  2846. struct mm_struct *mm = current->mm;
  2847. struct vm_area_struct *vma = NULL;
  2848. unsigned long len;
  2849. int ret;
  2850. bool populate;
  2851. LIST_HEAD(uf);
  2852. MA_STATE(mas, &mm->mm_mt, addr, addr);
  2853. len = PAGE_ALIGN(request);
  2854. if (len < request)
  2855. return -ENOMEM;
  2856. if (!len)
  2857. return 0;
  2858. /* Until we need other flags, refuse anything except VM_EXEC. */
  2859. if ((flags & (~VM_EXEC)) != 0)
  2860. return -EINVAL;
  2861. if (mmap_write_lock_killable(mm))
  2862. return -EINTR;
  2863. ret = check_brk_limits(addr, len);
  2864. if (ret)
  2865. goto limits_failed;
  2866. ret = do_mas_munmap(&mas, mm, addr, len, &uf, 0);
  2867. if (ret)
  2868. goto munmap_failed;
  2869. vma = mas_prev(&mas, 0);
  2870. ret = do_brk_flags(&mas, vma, addr, len, flags);
  2871. populate = ((mm->def_flags & VM_LOCKED) != 0);
  2872. mmap_write_unlock(mm);
  2873. userfaultfd_unmap_complete(mm, &uf);
  2874. if (populate && !ret)
  2875. mm_populate(addr, len);
  2876. return ret;
  2877. munmap_failed:
  2878. limits_failed:
  2879. mmap_write_unlock(mm);
  2880. return ret;
  2881. }
  2882. EXPORT_SYMBOL(vm_brk_flags);
  2883. int vm_brk(unsigned long addr, unsigned long len)
  2884. {
  2885. return vm_brk_flags(addr, len, 0);
  2886. }
  2887. EXPORT_SYMBOL(vm_brk);
  2888. /* Release all mmaps. */
  2889. void exit_mmap(struct mm_struct *mm)
  2890. {
  2891. struct mmu_gather tlb;
  2892. struct vm_area_struct *vma;
  2893. unsigned long nr_accounted = 0;
  2894. MA_STATE(mas, &mm->mm_mt, 0, 0);
  2895. int count = 0;
  2896. /* mm's last user has gone, and its about to be pulled down */
  2897. mmu_notifier_release(mm);
  2898. mmap_read_lock(mm);
  2899. arch_exit_mmap(mm);
  2900. vma = mas_find(&mas, ULONG_MAX);
  2901. if (!vma || unlikely(xa_is_zero(vma))) {
  2902. /* Can happen if dup_mmap() received an OOM */
  2903. mmap_read_unlock(mm);
  2904. mmap_write_lock(mm);
  2905. goto destroy;
  2906. }
  2907. lru_add_drain();
  2908. flush_cache_mm(mm);
  2909. tlb_gather_mmu_fullmm(&tlb, mm);
  2910. /* update_hiwater_rss(mm) here? but nobody should be looking */
  2911. /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
  2912. unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX, vma->vm_end, ULONG_MAX, false);
  2913. mmap_read_unlock(mm);
  2914. /*
  2915. * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
  2916. * because the memory has been already freed.
  2917. */
  2918. set_bit(MMF_OOM_SKIP, &mm->flags);
  2919. mmap_write_lock(mm);
  2920. mt_clear_in_rcu(&mm->mm_mt);
  2921. free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
  2922. USER_PGTABLES_CEILING, vma->vm_end, true);
  2923. tlb_finish_mmu(&tlb);
  2924. /*
  2925. * Walk the list again, actually closing and freeing it, with preemption
  2926. * enabled, without holding any MM locks besides the unreachable
  2927. * mmap_write_lock.
  2928. */
  2929. do {
  2930. if (vma->vm_flags & VM_ACCOUNT)
  2931. nr_accounted += vma_pages(vma);
  2932. remove_vma(vma, true);
  2933. count++;
  2934. cond_resched();
  2935. vma = mas_find(&mas, ULONG_MAX);
  2936. } while (vma && likely(!xa_is_zero(vma)));
  2937. BUG_ON(count != mm->map_count);
  2938. trace_exit_mmap(mm);
  2939. destroy:
  2940. __mt_destroy(&mm->mm_mt);
  2941. mmap_write_unlock(mm);
  2942. vm_unacct_memory(nr_accounted);
  2943. }
  2944. /* Insert vm structure into process list sorted by address
  2945. * and into the inode's i_mmap tree. If vm_file is non-NULL
  2946. * then i_mmap_rwsem is taken here.
  2947. */
  2948. int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
  2949. {
  2950. unsigned long charged = vma_pages(vma);
  2951. if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
  2952. return -ENOMEM;
  2953. if ((vma->vm_flags & VM_ACCOUNT) &&
  2954. security_vm_enough_memory_mm(mm, charged))
  2955. return -ENOMEM;
  2956. /*
  2957. * The vm_pgoff of a purely anonymous vma should be irrelevant
  2958. * until its first write fault, when page's anon_vma and index
  2959. * are set. But now set the vm_pgoff it will almost certainly
  2960. * end up with (unless mremap moves it elsewhere before that
  2961. * first wfault), so /proc/pid/maps tells a consistent story.
  2962. *
  2963. * By setting it to reflect the virtual start address of the
  2964. * vma, merges and splits can happen in a seamless way, just
  2965. * using the existing file pgoff checks and manipulations.
  2966. * Similarly in do_mmap and in do_brk_flags.
  2967. */
  2968. if (vma_is_anonymous(vma)) {
  2969. BUG_ON(vma->anon_vma);
  2970. vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
  2971. }
  2972. if (vma_link(mm, vma)) {
  2973. vm_unacct_memory(charged);
  2974. return -ENOMEM;
  2975. }
  2976. return 0;
  2977. }
  2978. /*
  2979. * Copy the vma structure to a new location in the same mm,
  2980. * prior to moving page table entries, to effect an mremap move.
  2981. */
  2982. struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
  2983. unsigned long addr, unsigned long len, pgoff_t pgoff,
  2984. bool *need_rmap_locks)
  2985. {
  2986. struct vm_area_struct *vma = *vmap;
  2987. unsigned long vma_start = vma->vm_start;
  2988. struct mm_struct *mm = vma->vm_mm;
  2989. struct vm_area_struct *new_vma, *prev;
  2990. bool faulted_in_anon_vma = true;
  2991. validate_mm_mt(mm);
  2992. /*
  2993. * If anonymous vma has not yet been faulted, update new pgoff
  2994. * to match new location, to increase its chance of merging.
  2995. */
  2996. if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
  2997. pgoff = addr >> PAGE_SHIFT;
  2998. faulted_in_anon_vma = false;
  2999. }
  3000. new_vma = find_vma_prev(mm, addr, &prev);
  3001. if (new_vma && new_vma->vm_start < addr + len)
  3002. return NULL; /* should never get here */
  3003. new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
  3004. vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
  3005. vma->vm_userfaultfd_ctx, anon_vma_name(vma));
  3006. if (new_vma) {
  3007. /*
  3008. * Source vma may have been merged into new_vma
  3009. */
  3010. if (unlikely(vma_start >= new_vma->vm_start &&
  3011. vma_start < new_vma->vm_end)) {
  3012. /*
  3013. * The only way we can get a vma_merge with
  3014. * self during an mremap is if the vma hasn't
  3015. * been faulted in yet and we were allowed to
  3016. * reset the dst vma->vm_pgoff to the
  3017. * destination address of the mremap to allow
  3018. * the merge to happen. mremap must change the
  3019. * vm_pgoff linearity between src and dst vmas
  3020. * (in turn preventing a vma_merge) to be
  3021. * safe. It is only safe to keep the vm_pgoff
  3022. * linear if there are no pages mapped yet.
  3023. */
  3024. VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
  3025. *vmap = vma = new_vma;
  3026. }
  3027. *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
  3028. } else {
  3029. new_vma = vm_area_dup(vma);
  3030. if (!new_vma)
  3031. goto out;
  3032. new_vma->vm_start = addr;
  3033. new_vma->vm_end = addr + len;
  3034. new_vma->vm_pgoff = pgoff;
  3035. if (vma_dup_policy(vma, new_vma))
  3036. goto out_free_vma;
  3037. if (anon_vma_clone(new_vma, vma))
  3038. goto out_free_mempol;
  3039. if (new_vma->vm_file)
  3040. get_file(new_vma->vm_file);
  3041. if (new_vma->vm_ops && new_vma->vm_ops->open)
  3042. new_vma->vm_ops->open(new_vma);
  3043. if (vma_link(mm, new_vma))
  3044. goto out_vma_link;
  3045. *need_rmap_locks = false;
  3046. }
  3047. validate_mm_mt(mm);
  3048. return new_vma;
  3049. out_vma_link:
  3050. if (new_vma->vm_ops && new_vma->vm_ops->close)
  3051. new_vma->vm_ops->close(new_vma);
  3052. if (new_vma->vm_file)
  3053. fput(new_vma->vm_file);
  3054. unlink_anon_vmas(new_vma);
  3055. out_free_mempol:
  3056. mpol_put(vma_policy(new_vma));
  3057. out_free_vma:
  3058. vm_area_free(new_vma);
  3059. out:
  3060. validate_mm_mt(mm);
  3061. return NULL;
  3062. }
  3063. /*
  3064. * Return true if the calling process may expand its vm space by the passed
  3065. * number of pages
  3066. */
  3067. bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
  3068. {
  3069. if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
  3070. return false;
  3071. if (is_data_mapping(flags) &&
  3072. mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
  3073. /* Workaround for Valgrind */
  3074. if (rlimit(RLIMIT_DATA) == 0 &&
  3075. mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
  3076. return true;
  3077. pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
  3078. current->comm, current->pid,
  3079. (mm->data_vm + npages) << PAGE_SHIFT,
  3080. rlimit(RLIMIT_DATA),
  3081. ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
  3082. if (!ignore_rlimit_data)
  3083. return false;
  3084. }
  3085. return true;
  3086. }
  3087. void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
  3088. {
  3089. WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
  3090. if (is_exec_mapping(flags))
  3091. mm->exec_vm += npages;
  3092. else if (is_stack_mapping(flags))
  3093. mm->stack_vm += npages;
  3094. else if (is_data_mapping(flags))
  3095. mm->data_vm += npages;
  3096. }
  3097. static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
  3098. /*
  3099. * Having a close hook prevents vma merging regardless of flags.
  3100. */
  3101. static void special_mapping_close(struct vm_area_struct *vma)
  3102. {
  3103. }
  3104. static const char *special_mapping_name(struct vm_area_struct *vma)
  3105. {
  3106. return ((struct vm_special_mapping *)vma->vm_private_data)->name;
  3107. }
  3108. static int special_mapping_mremap(struct vm_area_struct *new_vma)
  3109. {
  3110. struct vm_special_mapping *sm = new_vma->vm_private_data;
  3111. if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
  3112. return -EFAULT;
  3113. if (sm->mremap)
  3114. return sm->mremap(sm, new_vma);
  3115. return 0;
  3116. }
  3117. static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
  3118. {
  3119. /*
  3120. * Forbid splitting special mappings - kernel has expectations over
  3121. * the number of pages in mapping. Together with VM_DONTEXPAND
  3122. * the size of vma should stay the same over the special mapping's
  3123. * lifetime.
  3124. */
  3125. return -EINVAL;
  3126. }
  3127. static const struct vm_operations_struct special_mapping_vmops = {
  3128. .close = special_mapping_close,
  3129. .fault = special_mapping_fault,
  3130. .mremap = special_mapping_mremap,
  3131. .name = special_mapping_name,
  3132. /* vDSO code relies that VVAR can't be accessed remotely */
  3133. .access = NULL,
  3134. .may_split = special_mapping_split,
  3135. };
  3136. static const struct vm_operations_struct legacy_special_mapping_vmops = {
  3137. .close = special_mapping_close,
  3138. .fault = special_mapping_fault,
  3139. };
  3140. static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
  3141. {
  3142. struct vm_area_struct *vma = vmf->vma;
  3143. pgoff_t pgoff;
  3144. struct page **pages;
  3145. if (vma->vm_ops == &legacy_special_mapping_vmops) {
  3146. pages = vma->vm_private_data;
  3147. } else {
  3148. struct vm_special_mapping *sm = vma->vm_private_data;
  3149. if (sm->fault)
  3150. return sm->fault(sm, vmf->vma, vmf);
  3151. pages = sm->pages;
  3152. }
  3153. for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
  3154. pgoff--;
  3155. if (*pages) {
  3156. struct page *page = *pages;
  3157. get_page(page);
  3158. vmf->page = page;
  3159. return 0;
  3160. }
  3161. return VM_FAULT_SIGBUS;
  3162. }
  3163. static struct vm_area_struct *__install_special_mapping(
  3164. struct mm_struct *mm,
  3165. unsigned long addr, unsigned long len,
  3166. unsigned long vm_flags, void *priv,
  3167. const struct vm_operations_struct *ops)
  3168. {
  3169. int ret;
  3170. struct vm_area_struct *vma;
  3171. validate_mm_mt(mm);
  3172. vma = vm_area_alloc(mm);
  3173. if (unlikely(vma == NULL))
  3174. return ERR_PTR(-ENOMEM);
  3175. vma->vm_start = addr;
  3176. vma->vm_end = addr + len;
  3177. vm_flags_init(vma, (vm_flags | mm->def_flags |
  3178. VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
  3179. vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
  3180. vma->vm_ops = ops;
  3181. vma->vm_private_data = priv;
  3182. ret = insert_vm_struct(mm, vma);
  3183. if (ret)
  3184. goto out;
  3185. vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
  3186. perf_event_mmap(vma);
  3187. validate_mm_mt(mm);
  3188. return vma;
  3189. out:
  3190. vm_area_free(vma);
  3191. validate_mm_mt(mm);
  3192. return ERR_PTR(ret);
  3193. }
  3194. bool vma_is_special_mapping(const struct vm_area_struct *vma,
  3195. const struct vm_special_mapping *sm)
  3196. {
  3197. return vma->vm_private_data == sm &&
  3198. (vma->vm_ops == &special_mapping_vmops ||
  3199. vma->vm_ops == &legacy_special_mapping_vmops);
  3200. }
  3201. /*
  3202. * Called with mm->mmap_lock held for writing.
  3203. * Insert a new vma covering the given region, with the given flags.
  3204. * Its pages are supplied by the given array of struct page *.
  3205. * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
  3206. * The region past the last page supplied will always produce SIGBUS.
  3207. * The array pointer and the pages it points to are assumed to stay alive
  3208. * for as long as this mapping might exist.
  3209. */
  3210. struct vm_area_struct *_install_special_mapping(
  3211. struct mm_struct *mm,
  3212. unsigned long addr, unsigned long len,
  3213. unsigned long vm_flags, const struct vm_special_mapping *spec)
  3214. {
  3215. return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
  3216. &special_mapping_vmops);
  3217. }
  3218. int install_special_mapping(struct mm_struct *mm,
  3219. unsigned long addr, unsigned long len,
  3220. unsigned long vm_flags, struct page **pages)
  3221. {
  3222. struct vm_area_struct *vma = __install_special_mapping(
  3223. mm, addr, len, vm_flags, (void *)pages,
  3224. &legacy_special_mapping_vmops);
  3225. return PTR_ERR_OR_ZERO(vma);
  3226. }
  3227. static DEFINE_MUTEX(mm_all_locks_mutex);
  3228. static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
  3229. {
  3230. if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
  3231. /*
  3232. * The LSB of head.next can't change from under us
  3233. * because we hold the mm_all_locks_mutex.
  3234. */
  3235. down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
  3236. /*
  3237. * We can safely modify head.next after taking the
  3238. * anon_vma->root->rwsem. If some other vma in this mm shares
  3239. * the same anon_vma we won't take it again.
  3240. *
  3241. * No need of atomic instructions here, head.next
  3242. * can't change from under us thanks to the
  3243. * anon_vma->root->rwsem.
  3244. */
  3245. if (__test_and_set_bit(0, (unsigned long *)
  3246. &anon_vma->root->rb_root.rb_root.rb_node))
  3247. BUG();
  3248. }
  3249. }
  3250. static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
  3251. {
  3252. if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
  3253. /*
  3254. * AS_MM_ALL_LOCKS can't change from under us because
  3255. * we hold the mm_all_locks_mutex.
  3256. *
  3257. * Operations on ->flags have to be atomic because
  3258. * even if AS_MM_ALL_LOCKS is stable thanks to the
  3259. * mm_all_locks_mutex, there may be other cpus
  3260. * changing other bitflags in parallel to us.
  3261. */
  3262. if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
  3263. BUG();
  3264. down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
  3265. }
  3266. }
  3267. /*
  3268. * This operation locks against the VM for all pte/vma/mm related
  3269. * operations that could ever happen on a certain mm. This includes
  3270. * vmtruncate, try_to_unmap, and all page faults.
  3271. *
  3272. * The caller must take the mmap_lock in write mode before calling
  3273. * mm_take_all_locks(). The caller isn't allowed to release the
  3274. * mmap_lock until mm_drop_all_locks() returns.
  3275. *
  3276. * mmap_lock in write mode is required in order to block all operations
  3277. * that could modify pagetables and free pages without need of
  3278. * altering the vma layout. It's also needed in write mode to avoid new
  3279. * anon_vmas to be associated with existing vmas.
  3280. *
  3281. * A single task can't take more than one mm_take_all_locks() in a row
  3282. * or it would deadlock.
  3283. *
  3284. * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
  3285. * mapping->flags avoid to take the same lock twice, if more than one
  3286. * vma in this mm is backed by the same anon_vma or address_space.
  3287. *
  3288. * We take locks in following order, accordingly to comment at beginning
  3289. * of mm/rmap.c:
  3290. * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
  3291. * hugetlb mapping);
  3292. * - all vmas marked locked
  3293. * - all i_mmap_rwsem locks;
  3294. * - all anon_vma->rwseml
  3295. *
  3296. * We can take all locks within these types randomly because the VM code
  3297. * doesn't nest them and we protected from parallel mm_take_all_locks() by
  3298. * mm_all_locks_mutex.
  3299. *
  3300. * mm_take_all_locks() and mm_drop_all_locks are expensive operations
  3301. * that may have to take thousand of locks.
  3302. *
  3303. * mm_take_all_locks() can fail if it's interrupted by signals.
  3304. */
  3305. int mm_take_all_locks(struct mm_struct *mm)
  3306. {
  3307. struct vm_area_struct *vma;
  3308. struct anon_vma_chain *avc;
  3309. MA_STATE(mas, &mm->mm_mt, 0, 0);
  3310. mmap_assert_write_locked(mm);
  3311. mutex_lock(&mm_all_locks_mutex);
  3312. /*
  3313. * vma_start_write() does not have a complement in mm_drop_all_locks()
  3314. * because vma_start_write() is always asymmetrical; it marks a VMA as
  3315. * being written to until mmap_write_unlock() or mmap_write_downgrade()
  3316. * is reached.
  3317. */
  3318. mas_for_each(&mas, vma, ULONG_MAX) {
  3319. if (signal_pending(current))
  3320. goto out_unlock;
  3321. vma_start_write(vma);
  3322. }
  3323. mas_set(&mas, 0);
  3324. mas_for_each(&mas, vma, ULONG_MAX) {
  3325. if (signal_pending(current))
  3326. goto out_unlock;
  3327. if (vma->vm_file && vma->vm_file->f_mapping &&
  3328. is_vm_hugetlb_page(vma))
  3329. vm_lock_mapping(mm, vma->vm_file->f_mapping);
  3330. }
  3331. mas_set(&mas, 0);
  3332. mas_for_each(&mas, vma, ULONG_MAX) {
  3333. if (signal_pending(current))
  3334. goto out_unlock;
  3335. if (vma->vm_file && vma->vm_file->f_mapping &&
  3336. !is_vm_hugetlb_page(vma))
  3337. vm_lock_mapping(mm, vma->vm_file->f_mapping);
  3338. }
  3339. mas_set(&mas, 0);
  3340. mas_for_each(&mas, vma, ULONG_MAX) {
  3341. if (signal_pending(current))
  3342. goto out_unlock;
  3343. if (vma->anon_vma)
  3344. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  3345. vm_lock_anon_vma(mm, avc->anon_vma);
  3346. }
  3347. return 0;
  3348. out_unlock:
  3349. mm_drop_all_locks(mm);
  3350. return -EINTR;
  3351. }
  3352. static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
  3353. {
  3354. if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
  3355. /*
  3356. * The LSB of head.next can't change to 0 from under
  3357. * us because we hold the mm_all_locks_mutex.
  3358. *
  3359. * We must however clear the bitflag before unlocking
  3360. * the vma so the users using the anon_vma->rb_root will
  3361. * never see our bitflag.
  3362. *
  3363. * No need of atomic instructions here, head.next
  3364. * can't change from under us until we release the
  3365. * anon_vma->root->rwsem.
  3366. */
  3367. if (!__test_and_clear_bit(0, (unsigned long *)
  3368. &anon_vma->root->rb_root.rb_root.rb_node))
  3369. BUG();
  3370. anon_vma_unlock_write(anon_vma);
  3371. }
  3372. }
  3373. static void vm_unlock_mapping(struct address_space *mapping)
  3374. {
  3375. if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
  3376. /*
  3377. * AS_MM_ALL_LOCKS can't change to 0 from under us
  3378. * because we hold the mm_all_locks_mutex.
  3379. */
  3380. i_mmap_unlock_write(mapping);
  3381. if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
  3382. &mapping->flags))
  3383. BUG();
  3384. }
  3385. }
  3386. /*
  3387. * The mmap_lock cannot be released by the caller until
  3388. * mm_drop_all_locks() returns.
  3389. */
  3390. void mm_drop_all_locks(struct mm_struct *mm)
  3391. {
  3392. struct vm_area_struct *vma;
  3393. struct anon_vma_chain *avc;
  3394. MA_STATE(mas, &mm->mm_mt, 0, 0);
  3395. mmap_assert_write_locked(mm);
  3396. BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
  3397. mas_for_each(&mas, vma, ULONG_MAX) {
  3398. if (vma->anon_vma)
  3399. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  3400. vm_unlock_anon_vma(avc->anon_vma);
  3401. if (vma->vm_file && vma->vm_file->f_mapping)
  3402. vm_unlock_mapping(vma->vm_file->f_mapping);
  3403. }
  3404. mutex_unlock(&mm_all_locks_mutex);
  3405. }
  3406. /*
  3407. * initialise the percpu counter for VM
  3408. */
  3409. void __init mmap_init(void)
  3410. {
  3411. int ret;
  3412. ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
  3413. VM_BUG_ON(ret);
  3414. }
  3415. /*
  3416. * Initialise sysctl_user_reserve_kbytes.
  3417. *
  3418. * This is intended to prevent a user from starting a single memory hogging
  3419. * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
  3420. * mode.
  3421. *
  3422. * The default value is min(3% of free memory, 128MB)
  3423. * 128MB is enough to recover with sshd/login, bash, and top/kill.
  3424. */
  3425. static int init_user_reserve(void)
  3426. {
  3427. unsigned long free_kbytes;
  3428. free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  3429. sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
  3430. return 0;
  3431. }
  3432. subsys_initcall(init_user_reserve);
  3433. /*
  3434. * Initialise sysctl_admin_reserve_kbytes.
  3435. *
  3436. * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
  3437. * to log in and kill a memory hogging process.
  3438. *
  3439. * Systems with more than 256MB will reserve 8MB, enough to recover
  3440. * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
  3441. * only reserve 3% of free pages by default.
  3442. */
  3443. static int init_admin_reserve(void)
  3444. {
  3445. unsigned long free_kbytes;
  3446. free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  3447. sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
  3448. return 0;
  3449. }
  3450. subsys_initcall(init_admin_reserve);
  3451. /*
  3452. * Reinititalise user and admin reserves if memory is added or removed.
  3453. *
  3454. * The default user reserve max is 128MB, and the default max for the
  3455. * admin reserve is 8MB. These are usually, but not always, enough to
  3456. * enable recovery from a memory hogging process using login/sshd, a shell,
  3457. * and tools like top. It may make sense to increase or even disable the
  3458. * reserve depending on the existence of swap or variations in the recovery
  3459. * tools. So, the admin may have changed them.
  3460. *
  3461. * If memory is added and the reserves have been eliminated or increased above
  3462. * the default max, then we'll trust the admin.
  3463. *
  3464. * If memory is removed and there isn't enough free memory, then we
  3465. * need to reset the reserves.
  3466. *
  3467. * Otherwise keep the reserve set by the admin.
  3468. */
  3469. static int reserve_mem_notifier(struct notifier_block *nb,
  3470. unsigned long action, void *data)
  3471. {
  3472. unsigned long tmp, free_kbytes;
  3473. switch (action) {
  3474. case MEM_ONLINE:
  3475. /* Default max is 128MB. Leave alone if modified by operator. */
  3476. tmp = sysctl_user_reserve_kbytes;
  3477. if (0 < tmp && tmp < (1UL << 17))
  3478. init_user_reserve();
  3479. /* Default max is 8MB. Leave alone if modified by operator. */
  3480. tmp = sysctl_admin_reserve_kbytes;
  3481. if (0 < tmp && tmp < (1UL << 13))
  3482. init_admin_reserve();
  3483. break;
  3484. case MEM_OFFLINE:
  3485. free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  3486. if (sysctl_user_reserve_kbytes > free_kbytes) {
  3487. init_user_reserve();
  3488. pr_info("vm.user_reserve_kbytes reset to %lu\n",
  3489. sysctl_user_reserve_kbytes);
  3490. }
  3491. if (sysctl_admin_reserve_kbytes > free_kbytes) {
  3492. init_admin_reserve();
  3493. pr_info("vm.admin_reserve_kbytes reset to %lu\n",
  3494. sysctl_admin_reserve_kbytes);
  3495. }
  3496. break;
  3497. default:
  3498. break;
  3499. }
  3500. return NOTIFY_OK;
  3501. }
  3502. static struct notifier_block reserve_mem_nb = {
  3503. .notifier_call = reserve_mem_notifier,
  3504. };
  3505. static int __meminit init_reserve_notifier(void)
  3506. {
  3507. if (register_hotmemory_notifier(&reserve_mem_nb))
  3508. pr_err("Failed registering memory add/remove notifier for admin reserve\n");
  3509. return 0;
  3510. }
  3511. subsys_initcall(init_reserve_notifier);