mmap.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456
  1. /*
  2. * mm/mmap.c
  3. *
  4. * Written by obz.
  5. *
  6. * Address space accounting code <alan@lxorguk.ukuu.org.uk>
  7. */
  8. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  9. #include <linux/kernel.h>
  10. #include <linux/slab.h>
  11. #include <linux/backing-dev.h>
  12. #include <linux/mm.h>
  13. #include <linux/vmacache.h>
  14. #include <linux/shm.h>
  15. #include <linux/mman.h>
  16. #include <linux/pagemap.h>
  17. #include <linux/swap.h>
  18. #include <linux/syscalls.h>
  19. #include <linux/capability.h>
  20. #include <linux/init.h>
  21. #include <linux/file.h>
  22. #include <linux/fs.h>
  23. #include <linux/personality.h>
  24. #include <linux/security.h>
  25. #include <linux/hugetlb.h>
  26. #include <linux/profile.h>
  27. #include <linux/export.h>
  28. #include <linux/mount.h>
  29. #include <linux/mempolicy.h>
  30. #include <linux/rmap.h>
  31. #include <linux/mmu_notifier.h>
  32. #include <linux/mmdebug.h>
  33. #include <linux/perf_event.h>
  34. #include <linux/audit.h>
  35. #include <linux/khugepaged.h>
  36. #include <linux/uprobes.h>
  37. #include <linux/rbtree_augmented.h>
  38. #include <linux/sched/sysctl.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 <asm/uaccess.h>
  45. #include <asm/cacheflush.h>
  46. #include <asm/tlb.h>
  47. #include <asm/mmu_context.h>
  48. #include "internal.h"
  49. #ifndef arch_mmap_check
  50. #define arch_mmap_check(addr, len, flags) (0)
  51. #endif
  52. #ifndef arch_rebalance_pgtables
  53. #define arch_rebalance_pgtables(addr, len) (addr)
  54. #endif
  55. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
  56. const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
  57. const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
  58. int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
  59. #endif
  60. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
  61. const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
  62. const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
  63. int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
  64. #endif
  65. static bool ignore_rlimit_data = true;
  66. core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
  67. static void unmap_region(struct mm_struct *mm,
  68. struct vm_area_struct *vma, struct vm_area_struct *prev,
  69. unsigned long start, unsigned long end);
  70. /* description of effects of mapping type and prot in current implementation.
  71. * this is due to the limited x86 page protection hardware. The expected
  72. * behavior is in parens:
  73. *
  74. * map_type prot
  75. * PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
  76. * MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
  77. * w: (no) no w: (no) no w: (yes) yes w: (no) no
  78. * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
  79. *
  80. * MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
  81. * w: (no) no w: (no) no w: (copy) copy w: (no) no
  82. * x: (no) no x: (no) yes x: (no) yes x: (yes) yes
  83. *
  84. */
  85. pgprot_t protection_map[16] = {
  86. __P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
  87. __S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
  88. };
  89. pgprot_t vm_get_page_prot(unsigned long vm_flags)
  90. {
  91. return __pgprot(pgprot_val(protection_map[vm_flags &
  92. (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
  93. pgprot_val(arch_vm_get_page_prot(vm_flags)));
  94. }
  95. EXPORT_SYMBOL(vm_get_page_prot);
  96. static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
  97. {
  98. return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
  99. }
  100. /* Update vma->vm_page_prot to reflect vma->vm_flags. */
  101. void vma_set_page_prot(struct vm_area_struct *vma)
  102. {
  103. unsigned long vm_flags = vma->vm_flags;
  104. vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
  105. if (vma_wants_writenotify(vma)) {
  106. vm_flags &= ~VM_SHARED;
  107. vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot,
  108. vm_flags);
  109. }
  110. }
  111. int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS; /* heuristic overcommit */
  112. int sysctl_overcommit_ratio __read_mostly = 50; /* default is 50% */
  113. unsigned long sysctl_overcommit_kbytes __read_mostly;
  114. int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
  115. unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
  116. unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
  117. /*
  118. * Make sure vm_committed_as in one cacheline and not cacheline shared with
  119. * other variables. It can be updated by several CPUs frequently.
  120. */
  121. struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
  122. /*
  123. * The global memory commitment made in the system can be a metric
  124. * that can be used to drive ballooning decisions when Linux is hosted
  125. * as a guest. On Hyper-V, the host implements a policy engine for dynamically
  126. * balancing memory across competing virtual machines that are hosted.
  127. * Several metrics drive this policy engine including the guest reported
  128. * memory commitment.
  129. */
  130. unsigned long vm_memory_committed(void)
  131. {
  132. return percpu_counter_read_positive(&vm_committed_as);
  133. }
  134. EXPORT_SYMBOL_GPL(vm_memory_committed);
  135. /*
  136. * Check that a process has enough memory to allocate a new virtual
  137. * mapping. 0 means there is enough memory for the allocation to
  138. * succeed and -ENOMEM implies there is not.
  139. *
  140. * We currently support three overcommit policies, which are set via the
  141. * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
  142. *
  143. * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
  144. * Additional code 2002 Jul 20 by Robert Love.
  145. *
  146. * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
  147. *
  148. * Note this is a helper function intended to be used by LSMs which
  149. * wish to use this logic.
  150. */
  151. int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
  152. {
  153. long free, allowed, reserve;
  154. VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
  155. -(s64)vm_committed_as_batch * num_online_cpus(),
  156. "memory commitment underflow");
  157. vm_acct_memory(pages);
  158. /*
  159. * Sometimes we want to use more memory than we have
  160. */
  161. if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
  162. return 0;
  163. if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
  164. free = global_page_state(NR_FREE_PAGES);
  165. free += global_page_state(NR_FILE_PAGES);
  166. /*
  167. * shmem pages shouldn't be counted as free in this
  168. * case, they can't be purged, only swapped out, and
  169. * that won't affect the overall amount of available
  170. * memory in the system.
  171. */
  172. free -= global_page_state(NR_SHMEM);
  173. free += get_nr_swap_pages();
  174. /*
  175. * Any slabs which are created with the
  176. * SLAB_RECLAIM_ACCOUNT flag claim to have contents
  177. * which are reclaimable, under pressure. The dentry
  178. * cache and most inode caches should fall into this
  179. */
  180. free += global_page_state(NR_SLAB_RECLAIMABLE);
  181. /*
  182. * Leave reserved pages. The pages are not for anonymous pages.
  183. */
  184. if (free <= totalreserve_pages)
  185. goto error;
  186. else
  187. free -= totalreserve_pages;
  188. /*
  189. * Reserve some for root
  190. */
  191. if (!cap_sys_admin)
  192. free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  193. if (free > pages)
  194. return 0;
  195. goto error;
  196. }
  197. allowed = vm_commit_limit();
  198. /*
  199. * Reserve some for root
  200. */
  201. if (!cap_sys_admin)
  202. allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  203. /*
  204. * Don't let a single process grow so big a user can't recover
  205. */
  206. if (mm) {
  207. reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
  208. allowed -= min_t(long, mm->total_vm / 32, reserve);
  209. }
  210. if (percpu_counter_read_positive(&vm_committed_as) < allowed)
  211. return 0;
  212. error:
  213. vm_unacct_memory(pages);
  214. return -ENOMEM;
  215. }
  216. /*
  217. * Requires inode->i_mapping->i_mmap_rwsem
  218. */
  219. static void __remove_shared_vm_struct(struct vm_area_struct *vma,
  220. struct file *file, struct address_space *mapping)
  221. {
  222. if (vma->vm_flags & VM_DENYWRITE)
  223. atomic_inc(&file_inode(file)->i_writecount);
  224. if (vma->vm_flags & VM_SHARED)
  225. mapping_unmap_writable(mapping);
  226. flush_dcache_mmap_lock(mapping);
  227. vma_interval_tree_remove(vma, &mapping->i_mmap);
  228. flush_dcache_mmap_unlock(mapping);
  229. }
  230. /*
  231. * Unlink a file-based vm structure from its interval tree, to hide
  232. * vma from rmap and vmtruncate before freeing its page tables.
  233. */
  234. void unlink_file_vma(struct vm_area_struct *vma)
  235. {
  236. struct file *file = vma->vm_file;
  237. if (file) {
  238. struct address_space *mapping = file->f_mapping;
  239. i_mmap_lock_write(mapping);
  240. __remove_shared_vm_struct(vma, file, mapping);
  241. i_mmap_unlock_write(mapping);
  242. }
  243. }
  244. /*
  245. * Close a vm structure and free it, returning the next.
  246. */
  247. static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
  248. {
  249. struct vm_area_struct *next = vma->vm_next;
  250. might_sleep();
  251. if (vma->vm_ops && vma->vm_ops->close)
  252. vma->vm_ops->close(vma);
  253. if (vma->vm_file)
  254. fput(vma->vm_file);
  255. mpol_put(vma_policy(vma));
  256. kmem_cache_free(vm_area_cachep, vma);
  257. return next;
  258. }
  259. static unsigned long do_brk(unsigned long addr, unsigned long len);
  260. SYSCALL_DEFINE1(brk, unsigned long, brk)
  261. {
  262. unsigned long retval;
  263. unsigned long newbrk, oldbrk;
  264. struct mm_struct *mm = current->mm;
  265. unsigned long min_brk;
  266. bool populate;
  267. down_write(&mm->mmap_sem);
  268. #ifdef CONFIG_COMPAT_BRK
  269. /*
  270. * CONFIG_COMPAT_BRK can still be overridden by setting
  271. * randomize_va_space to 2, which will still cause mm->start_brk
  272. * to be arbitrarily shifted
  273. */
  274. if (current->brk_randomized)
  275. min_brk = mm->start_brk;
  276. else
  277. min_brk = mm->end_data;
  278. #else
  279. min_brk = mm->start_brk;
  280. #endif
  281. if (brk < min_brk)
  282. goto out;
  283. /*
  284. * Check against rlimit here. If this check is done later after the test
  285. * of oldbrk with newbrk then it can escape the test and let the data
  286. * segment grow beyond its set limit the in case where the limit is
  287. * not page aligned -Ram Gupta
  288. */
  289. if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
  290. mm->end_data, mm->start_data))
  291. goto out;
  292. newbrk = PAGE_ALIGN(brk);
  293. oldbrk = PAGE_ALIGN(mm->brk);
  294. if (oldbrk == newbrk)
  295. goto set_brk;
  296. /* Always allow shrinking brk. */
  297. if (brk <= mm->brk) {
  298. if (!do_munmap(mm, newbrk, oldbrk-newbrk))
  299. goto set_brk;
  300. goto out;
  301. }
  302. /* Check against existing mmap mappings. */
  303. if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE))
  304. goto out;
  305. /* Ok, looks good - let it rip. */
  306. if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
  307. goto out;
  308. set_brk:
  309. mm->brk = brk;
  310. populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
  311. up_write(&mm->mmap_sem);
  312. if (populate)
  313. mm_populate(oldbrk, newbrk - oldbrk);
  314. return brk;
  315. out:
  316. retval = mm->brk;
  317. up_write(&mm->mmap_sem);
  318. return retval;
  319. }
  320. static long vma_compute_subtree_gap(struct vm_area_struct *vma)
  321. {
  322. unsigned long max, subtree_gap;
  323. max = vma->vm_start;
  324. if (vma->vm_prev)
  325. max -= vma->vm_prev->vm_end;
  326. if (vma->vm_rb.rb_left) {
  327. subtree_gap = rb_entry(vma->vm_rb.rb_left,
  328. struct vm_area_struct, vm_rb)->rb_subtree_gap;
  329. if (subtree_gap > max)
  330. max = subtree_gap;
  331. }
  332. if (vma->vm_rb.rb_right) {
  333. subtree_gap = rb_entry(vma->vm_rb.rb_right,
  334. struct vm_area_struct, vm_rb)->rb_subtree_gap;
  335. if (subtree_gap > max)
  336. max = subtree_gap;
  337. }
  338. return max;
  339. }
  340. #ifdef CONFIG_DEBUG_VM_RB
  341. static int browse_rb(struct mm_struct *mm)
  342. {
  343. struct rb_root *root = &mm->mm_rb;
  344. int i = 0, j, bug = 0;
  345. struct rb_node *nd, *pn = NULL;
  346. unsigned long prev = 0, pend = 0;
  347. for (nd = rb_first(root); nd; nd = rb_next(nd)) {
  348. struct vm_area_struct *vma;
  349. vma = rb_entry(nd, struct vm_area_struct, vm_rb);
  350. if (vma->vm_start < prev) {
  351. pr_emerg("vm_start %lx < prev %lx\n",
  352. vma->vm_start, prev);
  353. bug = 1;
  354. }
  355. if (vma->vm_start < pend) {
  356. pr_emerg("vm_start %lx < pend %lx\n",
  357. vma->vm_start, pend);
  358. bug = 1;
  359. }
  360. if (vma->vm_start > vma->vm_end) {
  361. pr_emerg("vm_start %lx > vm_end %lx\n",
  362. vma->vm_start, vma->vm_end);
  363. bug = 1;
  364. }
  365. spin_lock(&mm->page_table_lock);
  366. if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
  367. pr_emerg("free gap %lx, correct %lx\n",
  368. vma->rb_subtree_gap,
  369. vma_compute_subtree_gap(vma));
  370. bug = 1;
  371. }
  372. spin_unlock(&mm->page_table_lock);
  373. i++;
  374. pn = nd;
  375. prev = vma->vm_start;
  376. pend = vma->vm_end;
  377. }
  378. j = 0;
  379. for (nd = pn; nd; nd = rb_prev(nd))
  380. j++;
  381. if (i != j) {
  382. pr_emerg("backwards %d, forwards %d\n", j, i);
  383. bug = 1;
  384. }
  385. return bug ? -1 : i;
  386. }
  387. static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
  388. {
  389. struct rb_node *nd;
  390. for (nd = rb_first(root); nd; nd = rb_next(nd)) {
  391. struct vm_area_struct *vma;
  392. vma = rb_entry(nd, struct vm_area_struct, vm_rb);
  393. VM_BUG_ON_VMA(vma != ignore &&
  394. vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
  395. vma);
  396. }
  397. }
  398. static void validate_mm(struct mm_struct *mm)
  399. {
  400. int bug = 0;
  401. int i = 0;
  402. unsigned long highest_address = 0;
  403. struct vm_area_struct *vma = mm->mmap;
  404. while (vma) {
  405. struct anon_vma *anon_vma = vma->anon_vma;
  406. struct anon_vma_chain *avc;
  407. if (anon_vma) {
  408. anon_vma_lock_read(anon_vma);
  409. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  410. anon_vma_interval_tree_verify(avc);
  411. anon_vma_unlock_read(anon_vma);
  412. }
  413. highest_address = vma->vm_end;
  414. vma = vma->vm_next;
  415. i++;
  416. }
  417. if (i != mm->map_count) {
  418. pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
  419. bug = 1;
  420. }
  421. if (highest_address != mm->highest_vm_end) {
  422. pr_emerg("mm->highest_vm_end %lx, found %lx\n",
  423. mm->highest_vm_end, highest_address);
  424. bug = 1;
  425. }
  426. i = browse_rb(mm);
  427. if (i != mm->map_count) {
  428. if (i != -1)
  429. pr_emerg("map_count %d rb %d\n", mm->map_count, i);
  430. bug = 1;
  431. }
  432. VM_BUG_ON_MM(bug, mm);
  433. }
  434. #else
  435. #define validate_mm_rb(root, ignore) do { } while (0)
  436. #define validate_mm(mm) do { } while (0)
  437. #endif
  438. RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
  439. unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
  440. /*
  441. * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
  442. * vma->vm_prev->vm_end values changed, without modifying the vma's position
  443. * in the rbtree.
  444. */
  445. static void vma_gap_update(struct vm_area_struct *vma)
  446. {
  447. /*
  448. * As it turns out, RB_DECLARE_CALLBACKS() already created a callback
  449. * function that does exacltly what we want.
  450. */
  451. vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
  452. }
  453. static inline void vma_rb_insert(struct vm_area_struct *vma,
  454. struct rb_root *root)
  455. {
  456. /* All rb_subtree_gap values must be consistent prior to insertion */
  457. validate_mm_rb(root, NULL);
  458. rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
  459. }
  460. static void vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
  461. {
  462. /*
  463. * All rb_subtree_gap values must be consistent prior to erase,
  464. * with the possible exception of the vma being erased.
  465. */
  466. validate_mm_rb(root, vma);
  467. /*
  468. * Note rb_erase_augmented is a fairly large inline function,
  469. * so make sure we instantiate it only once with our desired
  470. * augmented rbtree callbacks.
  471. */
  472. rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
  473. }
  474. /*
  475. * vma has some anon_vma assigned, and is already inserted on that
  476. * anon_vma's interval trees.
  477. *
  478. * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
  479. * vma must be removed from the anon_vma's interval trees using
  480. * anon_vma_interval_tree_pre_update_vma().
  481. *
  482. * After the update, the vma will be reinserted using
  483. * anon_vma_interval_tree_post_update_vma().
  484. *
  485. * The entire update must be protected by exclusive mmap_sem and by
  486. * the root anon_vma's mutex.
  487. */
  488. static inline void
  489. anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
  490. {
  491. struct anon_vma_chain *avc;
  492. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  493. anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
  494. }
  495. static inline void
  496. anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
  497. {
  498. struct anon_vma_chain *avc;
  499. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  500. anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
  501. }
  502. static int find_vma_links(struct mm_struct *mm, unsigned long addr,
  503. unsigned long end, struct vm_area_struct **pprev,
  504. struct rb_node ***rb_link, struct rb_node **rb_parent)
  505. {
  506. struct rb_node **__rb_link, *__rb_parent, *rb_prev;
  507. __rb_link = &mm->mm_rb.rb_node;
  508. rb_prev = __rb_parent = NULL;
  509. while (*__rb_link) {
  510. struct vm_area_struct *vma_tmp;
  511. __rb_parent = *__rb_link;
  512. vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
  513. if (vma_tmp->vm_end > addr) {
  514. /* Fail if an existing vma overlaps the area */
  515. if (vma_tmp->vm_start < end)
  516. return -ENOMEM;
  517. __rb_link = &__rb_parent->rb_left;
  518. } else {
  519. rb_prev = __rb_parent;
  520. __rb_link = &__rb_parent->rb_right;
  521. }
  522. }
  523. *pprev = NULL;
  524. if (rb_prev)
  525. *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
  526. *rb_link = __rb_link;
  527. *rb_parent = __rb_parent;
  528. return 0;
  529. }
  530. static unsigned long count_vma_pages_range(struct mm_struct *mm,
  531. unsigned long addr, unsigned long end)
  532. {
  533. unsigned long nr_pages = 0;
  534. struct vm_area_struct *vma;
  535. /* Find first overlaping mapping */
  536. vma = find_vma_intersection(mm, addr, end);
  537. if (!vma)
  538. return 0;
  539. nr_pages = (min(end, vma->vm_end) -
  540. max(addr, vma->vm_start)) >> PAGE_SHIFT;
  541. /* Iterate over the rest of the overlaps */
  542. for (vma = vma->vm_next; vma; vma = vma->vm_next) {
  543. unsigned long overlap_len;
  544. if (vma->vm_start > end)
  545. break;
  546. overlap_len = min(end, vma->vm_end) - vma->vm_start;
  547. nr_pages += overlap_len >> PAGE_SHIFT;
  548. }
  549. return nr_pages;
  550. }
  551. void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
  552. struct rb_node **rb_link, struct rb_node *rb_parent)
  553. {
  554. /* Update tracking information for the gap following the new vma. */
  555. if (vma->vm_next)
  556. vma_gap_update(vma->vm_next);
  557. else
  558. mm->highest_vm_end = vma->vm_end;
  559. /*
  560. * vma->vm_prev wasn't known when we followed the rbtree to find the
  561. * correct insertion point for that vma. As a result, we could not
  562. * update the vma vm_rb parents rb_subtree_gap values on the way down.
  563. * So, we first insert the vma with a zero rb_subtree_gap value
  564. * (to be consistent with what we did on the way down), and then
  565. * immediately update the gap to the correct value. Finally we
  566. * rebalance the rbtree after all augmented values have been set.
  567. */
  568. rb_link_node(&vma->vm_rb, rb_parent, rb_link);
  569. vma->rb_subtree_gap = 0;
  570. vma_gap_update(vma);
  571. vma_rb_insert(vma, &mm->mm_rb);
  572. }
  573. static void __vma_link_file(struct vm_area_struct *vma)
  574. {
  575. struct file *file;
  576. file = vma->vm_file;
  577. if (file) {
  578. struct address_space *mapping = file->f_mapping;
  579. if (vma->vm_flags & VM_DENYWRITE)
  580. atomic_dec(&file_inode(file)->i_writecount);
  581. if (vma->vm_flags & VM_SHARED)
  582. atomic_inc(&mapping->i_mmap_writable);
  583. flush_dcache_mmap_lock(mapping);
  584. vma_interval_tree_insert(vma, &mapping->i_mmap);
  585. flush_dcache_mmap_unlock(mapping);
  586. }
  587. }
  588. static void
  589. __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
  590. struct vm_area_struct *prev, struct rb_node **rb_link,
  591. struct rb_node *rb_parent)
  592. {
  593. __vma_link_list(mm, vma, prev, rb_parent);
  594. __vma_link_rb(mm, vma, rb_link, rb_parent);
  595. }
  596. static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
  597. struct vm_area_struct *prev, struct rb_node **rb_link,
  598. struct rb_node *rb_parent)
  599. {
  600. struct address_space *mapping = NULL;
  601. if (vma->vm_file) {
  602. mapping = vma->vm_file->f_mapping;
  603. i_mmap_lock_write(mapping);
  604. }
  605. __vma_link(mm, vma, prev, rb_link, rb_parent);
  606. __vma_link_file(vma);
  607. if (mapping)
  608. i_mmap_unlock_write(mapping);
  609. mm->map_count++;
  610. validate_mm(mm);
  611. }
  612. /*
  613. * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
  614. * mm's list and rbtree. It has already been inserted into the interval tree.
  615. */
  616. static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
  617. {
  618. struct vm_area_struct *prev;
  619. struct rb_node **rb_link, *rb_parent;
  620. if (find_vma_links(mm, vma->vm_start, vma->vm_end,
  621. &prev, &rb_link, &rb_parent))
  622. BUG();
  623. __vma_link(mm, vma, prev, rb_link, rb_parent);
  624. mm->map_count++;
  625. }
  626. static inline void
  627. __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
  628. struct vm_area_struct *prev)
  629. {
  630. struct vm_area_struct *next;
  631. vma_rb_erase(vma, &mm->mm_rb);
  632. prev->vm_next = next = vma->vm_next;
  633. if (next)
  634. next->vm_prev = prev;
  635. /* Kill the cache */
  636. vmacache_invalidate(mm);
  637. }
  638. /*
  639. * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
  640. * is already present in an i_mmap tree without adjusting the tree.
  641. * The following helper function should be used when such adjustments
  642. * are necessary. The "insert" vma (if any) is to be inserted
  643. * before we drop the necessary locks.
  644. */
  645. int vma_adjust(struct vm_area_struct *vma, unsigned long start,
  646. unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
  647. {
  648. struct mm_struct *mm = vma->vm_mm;
  649. struct vm_area_struct *next = vma->vm_next;
  650. struct vm_area_struct *importer = NULL;
  651. struct address_space *mapping = NULL;
  652. struct rb_root *root = NULL;
  653. struct anon_vma *anon_vma = NULL;
  654. struct file *file = vma->vm_file;
  655. bool start_changed = false, end_changed = false;
  656. long adjust_next = 0;
  657. int remove_next = 0;
  658. if (next && !insert) {
  659. struct vm_area_struct *exporter = NULL;
  660. if (end >= next->vm_end) {
  661. /*
  662. * vma expands, overlapping all the next, and
  663. * perhaps the one after too (mprotect case 6).
  664. */
  665. again: remove_next = 1 + (end > next->vm_end);
  666. end = next->vm_end;
  667. exporter = next;
  668. importer = vma;
  669. } else if (end > next->vm_start) {
  670. /*
  671. * vma expands, overlapping part of the next:
  672. * mprotect case 5 shifting the boundary up.
  673. */
  674. adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
  675. exporter = next;
  676. importer = vma;
  677. } else if (end < vma->vm_end) {
  678. /*
  679. * vma shrinks, and !insert tells it's not
  680. * split_vma inserting another: so it must be
  681. * mprotect case 4 shifting the boundary down.
  682. */
  683. adjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);
  684. exporter = vma;
  685. importer = next;
  686. }
  687. /*
  688. * Easily overlooked: when mprotect shifts the boundary,
  689. * make sure the expanding vma has anon_vma set if the
  690. * shrinking vma had, to cover any anon pages imported.
  691. */
  692. if (exporter && exporter->anon_vma && !importer->anon_vma) {
  693. int error;
  694. importer->anon_vma = exporter->anon_vma;
  695. error = anon_vma_clone(importer, exporter);
  696. if (error)
  697. return error;
  698. }
  699. }
  700. if (file) {
  701. mapping = file->f_mapping;
  702. root = &mapping->i_mmap;
  703. uprobe_munmap(vma, vma->vm_start, vma->vm_end);
  704. if (adjust_next)
  705. uprobe_munmap(next, next->vm_start, next->vm_end);
  706. i_mmap_lock_write(mapping);
  707. if (insert) {
  708. /*
  709. * Put into interval tree now, so instantiated pages
  710. * are visible to arm/parisc __flush_dcache_page
  711. * throughout; but we cannot insert into address
  712. * space until vma start or end is updated.
  713. */
  714. __vma_link_file(insert);
  715. }
  716. }
  717. vma_adjust_trans_huge(vma, start, end, adjust_next);
  718. anon_vma = vma->anon_vma;
  719. if (!anon_vma && adjust_next)
  720. anon_vma = next->anon_vma;
  721. if (anon_vma) {
  722. VM_BUG_ON_VMA(adjust_next && next->anon_vma &&
  723. anon_vma != next->anon_vma, next);
  724. anon_vma_lock_write(anon_vma);
  725. anon_vma_interval_tree_pre_update_vma(vma);
  726. if (adjust_next)
  727. anon_vma_interval_tree_pre_update_vma(next);
  728. }
  729. if (root) {
  730. flush_dcache_mmap_lock(mapping);
  731. vma_interval_tree_remove(vma, root);
  732. if (adjust_next)
  733. vma_interval_tree_remove(next, root);
  734. }
  735. if (start != vma->vm_start) {
  736. vma->vm_start = start;
  737. start_changed = true;
  738. }
  739. if (end != vma->vm_end) {
  740. vma->vm_end = end;
  741. end_changed = true;
  742. }
  743. vma->vm_pgoff = pgoff;
  744. if (adjust_next) {
  745. next->vm_start += adjust_next << PAGE_SHIFT;
  746. next->vm_pgoff += adjust_next;
  747. }
  748. if (root) {
  749. if (adjust_next)
  750. vma_interval_tree_insert(next, root);
  751. vma_interval_tree_insert(vma, root);
  752. flush_dcache_mmap_unlock(mapping);
  753. }
  754. if (remove_next) {
  755. /*
  756. * vma_merge has merged next into vma, and needs
  757. * us to remove next before dropping the locks.
  758. */
  759. __vma_unlink(mm, next, vma);
  760. if (file)
  761. __remove_shared_vm_struct(next, file, mapping);
  762. } else if (insert) {
  763. /*
  764. * split_vma has split insert from vma, and needs
  765. * us to insert it before dropping the locks
  766. * (it may either follow vma or precede it).
  767. */
  768. __insert_vm_struct(mm, insert);
  769. } else {
  770. if (start_changed)
  771. vma_gap_update(vma);
  772. if (end_changed) {
  773. if (!next)
  774. mm->highest_vm_end = end;
  775. else if (!adjust_next)
  776. vma_gap_update(next);
  777. }
  778. }
  779. if (anon_vma) {
  780. anon_vma_interval_tree_post_update_vma(vma);
  781. if (adjust_next)
  782. anon_vma_interval_tree_post_update_vma(next);
  783. anon_vma_unlock_write(anon_vma);
  784. }
  785. if (mapping)
  786. i_mmap_unlock_write(mapping);
  787. if (root) {
  788. uprobe_mmap(vma);
  789. if (adjust_next)
  790. uprobe_mmap(next);
  791. }
  792. if (remove_next) {
  793. if (file) {
  794. uprobe_munmap(next, next->vm_start, next->vm_end);
  795. fput(file);
  796. }
  797. if (next->anon_vma)
  798. anon_vma_merge(vma, next);
  799. mm->map_count--;
  800. mpol_put(vma_policy(next));
  801. kmem_cache_free(vm_area_cachep, next);
  802. /*
  803. * In mprotect's case 6 (see comments on vma_merge),
  804. * we must remove another next too. It would clutter
  805. * up the code too much to do both in one go.
  806. */
  807. next = vma->vm_next;
  808. if (remove_next == 2)
  809. goto again;
  810. else if (next)
  811. vma_gap_update(next);
  812. else
  813. mm->highest_vm_end = end;
  814. }
  815. if (insert && file)
  816. uprobe_mmap(insert);
  817. validate_mm(mm);
  818. return 0;
  819. }
  820. /*
  821. * If the vma has a ->close operation then the driver probably needs to release
  822. * per-vma resources, so we don't attempt to merge those.
  823. */
  824. static inline int is_mergeable_vma(struct vm_area_struct *vma,
  825. struct file *file, unsigned long vm_flags,
  826. struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
  827. {
  828. /*
  829. * VM_SOFTDIRTY should not prevent from VMA merging, if we
  830. * match the flags but dirty bit -- the caller should mark
  831. * merged VMA as dirty. If dirty bit won't be excluded from
  832. * comparison, we increase pressue on the memory system forcing
  833. * the kernel to generate new VMAs when old one could be
  834. * extended instead.
  835. */
  836. if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
  837. return 0;
  838. if (vma->vm_file != file)
  839. return 0;
  840. if (vma->vm_ops && vma->vm_ops->close)
  841. return 0;
  842. if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
  843. return 0;
  844. return 1;
  845. }
  846. static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
  847. struct anon_vma *anon_vma2,
  848. struct vm_area_struct *vma)
  849. {
  850. /*
  851. * The list_is_singular() test is to avoid merging VMA cloned from
  852. * parents. This can improve scalability caused by anon_vma lock.
  853. */
  854. if ((!anon_vma1 || !anon_vma2) && (!vma ||
  855. list_is_singular(&vma->anon_vma_chain)))
  856. return 1;
  857. return anon_vma1 == anon_vma2;
  858. }
  859. /*
  860. * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
  861. * in front of (at a lower virtual address and file offset than) the vma.
  862. *
  863. * We cannot merge two vmas if they have differently assigned (non-NULL)
  864. * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
  865. *
  866. * We don't check here for the merged mmap wrapping around the end of pagecache
  867. * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
  868. * wrap, nor mmaps which cover the final page at index -1UL.
  869. */
  870. static int
  871. can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
  872. struct anon_vma *anon_vma, struct file *file,
  873. pgoff_t vm_pgoff,
  874. struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
  875. {
  876. if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
  877. is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
  878. if (vma->vm_pgoff == vm_pgoff)
  879. return 1;
  880. }
  881. return 0;
  882. }
  883. /*
  884. * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
  885. * beyond (at a higher virtual address and file offset than) the vma.
  886. *
  887. * We cannot merge two vmas if they have differently assigned (non-NULL)
  888. * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
  889. */
  890. static int
  891. can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
  892. struct anon_vma *anon_vma, struct file *file,
  893. pgoff_t vm_pgoff,
  894. struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
  895. {
  896. if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
  897. is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
  898. pgoff_t vm_pglen;
  899. vm_pglen = vma_pages(vma);
  900. if (vma->vm_pgoff + vm_pglen == vm_pgoff)
  901. return 1;
  902. }
  903. return 0;
  904. }
  905. /*
  906. * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
  907. * whether that can be merged with its predecessor or its successor.
  908. * Or both (it neatly fills a hole).
  909. *
  910. * In most cases - when called for mmap, brk or mremap - [addr,end) is
  911. * certain not to be mapped by the time vma_merge is called; but when
  912. * called for mprotect, it is certain to be already mapped (either at
  913. * an offset within prev, or at the start of next), and the flags of
  914. * this area are about to be changed to vm_flags - and the no-change
  915. * case has already been eliminated.
  916. *
  917. * The following mprotect cases have to be considered, where AAAA is
  918. * the area passed down from mprotect_fixup, never extending beyond one
  919. * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
  920. *
  921. * AAAA AAAA AAAA AAAA
  922. * PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
  923. * cannot merge might become might become might become
  924. * PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
  925. * mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
  926. * mremap move: PPPPNNNNNNNN 8
  927. * AAAA
  928. * PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
  929. * might become case 1 below case 2 below case 3 below
  930. *
  931. * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
  932. * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
  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. {
  941. pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
  942. struct vm_area_struct *area, *next;
  943. int err;
  944. /*
  945. * We later require that vma->vm_flags == vm_flags,
  946. * so this tests vma->vm_flags & VM_SPECIAL, too.
  947. */
  948. if (vm_flags & VM_SPECIAL)
  949. return NULL;
  950. if (prev)
  951. next = prev->vm_next;
  952. else
  953. next = mm->mmap;
  954. area = next;
  955. if (next && next->vm_end == end) /* cases 6, 7, 8 */
  956. next = next->vm_next;
  957. /*
  958. * Can it merge with the predecessor?
  959. */
  960. if (prev && prev->vm_end == addr &&
  961. mpol_equal(vma_policy(prev), policy) &&
  962. can_vma_merge_after(prev, vm_flags,
  963. anon_vma, file, pgoff,
  964. vm_userfaultfd_ctx)) {
  965. /*
  966. * OK, it can. Can we now merge in the successor as well?
  967. */
  968. if (next && end == next->vm_start &&
  969. mpol_equal(policy, vma_policy(next)) &&
  970. can_vma_merge_before(next, vm_flags,
  971. anon_vma, file,
  972. pgoff+pglen,
  973. vm_userfaultfd_ctx) &&
  974. is_mergeable_anon_vma(prev->anon_vma,
  975. next->anon_vma, NULL)) {
  976. /* cases 1, 6 */
  977. err = vma_adjust(prev, prev->vm_start,
  978. next->vm_end, prev->vm_pgoff, NULL);
  979. } else /* cases 2, 5, 7 */
  980. err = vma_adjust(prev, prev->vm_start,
  981. end, prev->vm_pgoff, NULL);
  982. if (err)
  983. return NULL;
  984. khugepaged_enter_vma_merge(prev, vm_flags);
  985. return prev;
  986. }
  987. /*
  988. * Can this new request be merged in front of next?
  989. */
  990. if (next && end == next->vm_start &&
  991. mpol_equal(policy, vma_policy(next)) &&
  992. can_vma_merge_before(next, vm_flags,
  993. anon_vma, file, pgoff+pglen,
  994. vm_userfaultfd_ctx)) {
  995. if (prev && addr < prev->vm_end) /* case 4 */
  996. err = vma_adjust(prev, prev->vm_start,
  997. addr, prev->vm_pgoff, NULL);
  998. else /* cases 3, 8 */
  999. err = vma_adjust(area, addr, next->vm_end,
  1000. next->vm_pgoff - pglen, NULL);
  1001. if (err)
  1002. return NULL;
  1003. khugepaged_enter_vma_merge(area, vm_flags);
  1004. return area;
  1005. }
  1006. return NULL;
  1007. }
  1008. /*
  1009. * Rough compatbility check to quickly see if it's even worth looking
  1010. * at sharing an anon_vma.
  1011. *
  1012. * They need to have the same vm_file, and the flags can only differ
  1013. * in things that mprotect may change.
  1014. *
  1015. * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
  1016. * we can merge the two vma's. For example, we refuse to merge a vma if
  1017. * there is a vm_ops->close() function, because that indicates that the
  1018. * driver is doing some kind of reference counting. But that doesn't
  1019. * really matter for the anon_vma sharing case.
  1020. */
  1021. static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
  1022. {
  1023. return a->vm_end == b->vm_start &&
  1024. mpol_equal(vma_policy(a), vma_policy(b)) &&
  1025. a->vm_file == b->vm_file &&
  1026. !((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
  1027. b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
  1028. }
  1029. /*
  1030. * Do some basic sanity checking to see if we can re-use the anon_vma
  1031. * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
  1032. * the same as 'old', the other will be the new one that is trying
  1033. * to share the anon_vma.
  1034. *
  1035. * NOTE! This runs with mm_sem held for reading, so it is possible that
  1036. * the anon_vma of 'old' is concurrently in the process of being set up
  1037. * by another page fault trying to merge _that_. But that's ok: if it
  1038. * is being set up, that automatically means that it will be a singleton
  1039. * acceptable for merging, so we can do all of this optimistically. But
  1040. * we do that READ_ONCE() to make sure that we never re-load the pointer.
  1041. *
  1042. * IOW: that the "list_is_singular()" test on the anon_vma_chain only
  1043. * matters for the 'stable anon_vma' case (ie the thing we want to avoid
  1044. * is to return an anon_vma that is "complex" due to having gone through
  1045. * a fork).
  1046. *
  1047. * We also make sure that the two vma's are compatible (adjacent,
  1048. * and with the same memory policies). That's all stable, even with just
  1049. * a read lock on the mm_sem.
  1050. */
  1051. static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
  1052. {
  1053. if (anon_vma_compatible(a, b)) {
  1054. struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
  1055. if (anon_vma && list_is_singular(&old->anon_vma_chain))
  1056. return anon_vma;
  1057. }
  1058. return NULL;
  1059. }
  1060. /*
  1061. * find_mergeable_anon_vma is used by anon_vma_prepare, to check
  1062. * neighbouring vmas for a suitable anon_vma, before it goes off
  1063. * to allocate a new anon_vma. It checks because a repetitive
  1064. * sequence of mprotects and faults may otherwise lead to distinct
  1065. * anon_vmas being allocated, preventing vma merge in subsequent
  1066. * mprotect.
  1067. */
  1068. struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
  1069. {
  1070. struct anon_vma *anon_vma;
  1071. struct vm_area_struct *near;
  1072. near = vma->vm_next;
  1073. if (!near)
  1074. goto try_prev;
  1075. anon_vma = reusable_anon_vma(near, vma, near);
  1076. if (anon_vma)
  1077. return anon_vma;
  1078. try_prev:
  1079. near = vma->vm_prev;
  1080. if (!near)
  1081. goto none;
  1082. anon_vma = reusable_anon_vma(near, near, vma);
  1083. if (anon_vma)
  1084. return anon_vma;
  1085. none:
  1086. /*
  1087. * There's no absolute need to look only at touching neighbours:
  1088. * we could search further afield for "compatible" anon_vmas.
  1089. * But it would probably just be a waste of time searching,
  1090. * or lead to too many vmas hanging off the same anon_vma.
  1091. * We're trying to allow mprotect remerging later on,
  1092. * not trying to minimize memory used for anon_vmas.
  1093. */
  1094. return NULL;
  1095. }
  1096. /*
  1097. * If a hint addr is less than mmap_min_addr change hint to be as
  1098. * low as possible but still greater than mmap_min_addr
  1099. */
  1100. static inline unsigned long round_hint_to_min(unsigned long hint)
  1101. {
  1102. hint &= PAGE_MASK;
  1103. if (((void *)hint != NULL) &&
  1104. (hint < mmap_min_addr))
  1105. return PAGE_ALIGN(mmap_min_addr);
  1106. return hint;
  1107. }
  1108. static inline int mlock_future_check(struct mm_struct *mm,
  1109. unsigned long flags,
  1110. unsigned long len)
  1111. {
  1112. unsigned long locked, lock_limit;
  1113. /* mlock MCL_FUTURE? */
  1114. if (flags & VM_LOCKED) {
  1115. locked = len >> PAGE_SHIFT;
  1116. locked += mm->locked_vm;
  1117. lock_limit = rlimit(RLIMIT_MEMLOCK);
  1118. lock_limit >>= PAGE_SHIFT;
  1119. if (locked > lock_limit && !capable(CAP_IPC_LOCK))
  1120. return -EAGAIN;
  1121. }
  1122. return 0;
  1123. }
  1124. /*
  1125. * The caller must hold down_write(&current->mm->mmap_sem).
  1126. */
  1127. unsigned long do_mmap(struct file *file, unsigned long addr,
  1128. unsigned long len, unsigned long prot,
  1129. unsigned long flags, vm_flags_t vm_flags,
  1130. unsigned long pgoff, unsigned long *populate)
  1131. {
  1132. struct mm_struct *mm = current->mm;
  1133. *populate = 0;
  1134. if (!len)
  1135. return -EINVAL;
  1136. /*
  1137. * Does the application expect PROT_READ to imply PROT_EXEC?
  1138. *
  1139. * (the exception is when the underlying filesystem is noexec
  1140. * mounted, in which case we dont add PROT_EXEC.)
  1141. */
  1142. if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
  1143. if (!(file && path_noexec(&file->f_path)))
  1144. prot |= PROT_EXEC;
  1145. if (!(flags & MAP_FIXED))
  1146. addr = round_hint_to_min(addr);
  1147. /* Careful about overflows.. */
  1148. len = PAGE_ALIGN(len);
  1149. if (!len)
  1150. return -ENOMEM;
  1151. /* offset overflow? */
  1152. if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
  1153. return -EOVERFLOW;
  1154. /* Too many mappings? */
  1155. if (mm->map_count > sysctl_max_map_count)
  1156. return -ENOMEM;
  1157. /* Obtain the address to map to. we verify (or select) it and ensure
  1158. * that it represents a valid section of the address space.
  1159. */
  1160. addr = get_unmapped_area(file, addr, len, pgoff, flags);
  1161. if (offset_in_page(addr))
  1162. return addr;
  1163. /* Do simple checking here so the lower-level routines won't have
  1164. * to. we assume access permissions have been handled by the open
  1165. * of the memory object, so we don't do any here.
  1166. */
  1167. vm_flags |= calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
  1168. mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
  1169. if (flags & MAP_LOCKED)
  1170. if (!can_do_mlock())
  1171. return -EPERM;
  1172. if (mlock_future_check(mm, vm_flags, len))
  1173. return -EAGAIN;
  1174. if (file) {
  1175. struct inode *inode = file_inode(file);
  1176. switch (flags & MAP_TYPE) {
  1177. case MAP_SHARED:
  1178. if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
  1179. return -EACCES;
  1180. /*
  1181. * Make sure we don't allow writing to an append-only
  1182. * file..
  1183. */
  1184. if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
  1185. return -EACCES;
  1186. /*
  1187. * Make sure there are no mandatory locks on the file.
  1188. */
  1189. if (locks_verify_locked(file))
  1190. return -EAGAIN;
  1191. vm_flags |= VM_SHARED | VM_MAYSHARE;
  1192. if (!(file->f_mode & FMODE_WRITE))
  1193. vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
  1194. /* fall through */
  1195. case MAP_PRIVATE:
  1196. if (!(file->f_mode & FMODE_READ))
  1197. return -EACCES;
  1198. if (path_noexec(&file->f_path)) {
  1199. if (vm_flags & VM_EXEC)
  1200. return -EPERM;
  1201. vm_flags &= ~VM_MAYEXEC;
  1202. }
  1203. if (!file->f_op->mmap)
  1204. return -ENODEV;
  1205. if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
  1206. return -EINVAL;
  1207. break;
  1208. default:
  1209. return -EINVAL;
  1210. }
  1211. } else {
  1212. switch (flags & MAP_TYPE) {
  1213. case MAP_SHARED:
  1214. if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
  1215. return -EINVAL;
  1216. /*
  1217. * Ignore pgoff.
  1218. */
  1219. pgoff = 0;
  1220. vm_flags |= VM_SHARED | VM_MAYSHARE;
  1221. break;
  1222. case MAP_PRIVATE:
  1223. /*
  1224. * Set pgoff according to addr for anon_vma.
  1225. */
  1226. pgoff = addr >> PAGE_SHIFT;
  1227. break;
  1228. default:
  1229. return -EINVAL;
  1230. }
  1231. }
  1232. /*
  1233. * Set 'VM_NORESERVE' if we should not account for the
  1234. * memory use of this mapping.
  1235. */
  1236. if (flags & MAP_NORESERVE) {
  1237. /* We honor MAP_NORESERVE if allowed to overcommit */
  1238. if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
  1239. vm_flags |= VM_NORESERVE;
  1240. /* hugetlb applies strict overcommit unless MAP_NORESERVE */
  1241. if (file && is_file_hugepages(file))
  1242. vm_flags |= VM_NORESERVE;
  1243. }
  1244. addr = mmap_region(file, addr, len, vm_flags, pgoff);
  1245. if (!IS_ERR_VALUE(addr) &&
  1246. ((vm_flags & VM_LOCKED) ||
  1247. (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
  1248. *populate = len;
  1249. return addr;
  1250. }
  1251. SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
  1252. unsigned long, prot, unsigned long, flags,
  1253. unsigned long, fd, unsigned long, pgoff)
  1254. {
  1255. struct file *file = NULL;
  1256. unsigned long retval;
  1257. if (!(flags & MAP_ANONYMOUS)) {
  1258. audit_mmap_fd(fd, flags);
  1259. file = fget(fd);
  1260. if (!file)
  1261. return -EBADF;
  1262. if (is_file_hugepages(file))
  1263. len = ALIGN(len, huge_page_size(hstate_file(file)));
  1264. retval = -EINVAL;
  1265. if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
  1266. goto out_fput;
  1267. } else if (flags & MAP_HUGETLB) {
  1268. struct user_struct *user = NULL;
  1269. struct hstate *hs;
  1270. hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & SHM_HUGE_MASK);
  1271. if (!hs)
  1272. return -EINVAL;
  1273. len = ALIGN(len, huge_page_size(hs));
  1274. /*
  1275. * VM_NORESERVE is used because the reservations will be
  1276. * taken when vm_ops->mmap() is called
  1277. * A dummy user value is used because we are not locking
  1278. * memory so no accounting is necessary
  1279. */
  1280. file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
  1281. VM_NORESERVE,
  1282. &user, HUGETLB_ANONHUGE_INODE,
  1283. (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
  1284. if (IS_ERR(file))
  1285. return PTR_ERR(file);
  1286. }
  1287. flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
  1288. retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
  1289. out_fput:
  1290. if (file)
  1291. fput(file);
  1292. return retval;
  1293. }
  1294. #ifdef __ARCH_WANT_SYS_OLD_MMAP
  1295. struct mmap_arg_struct {
  1296. unsigned long addr;
  1297. unsigned long len;
  1298. unsigned long prot;
  1299. unsigned long flags;
  1300. unsigned long fd;
  1301. unsigned long offset;
  1302. };
  1303. SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
  1304. {
  1305. struct mmap_arg_struct a;
  1306. if (copy_from_user(&a, arg, sizeof(a)))
  1307. return -EFAULT;
  1308. if (offset_in_page(a.offset))
  1309. return -EINVAL;
  1310. return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
  1311. a.offset >> PAGE_SHIFT);
  1312. }
  1313. #endif /* __ARCH_WANT_SYS_OLD_MMAP */
  1314. /*
  1315. * Some shared mappigns will want the pages marked read-only
  1316. * to track write events. If so, we'll downgrade vm_page_prot
  1317. * to the private version (using protection_map[] without the
  1318. * VM_SHARED bit).
  1319. */
  1320. int vma_wants_writenotify(struct vm_area_struct *vma)
  1321. {
  1322. vm_flags_t vm_flags = vma->vm_flags;
  1323. const struct vm_operations_struct *vm_ops = vma->vm_ops;
  1324. /* If it was private or non-writable, the write bit is already clear */
  1325. if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
  1326. return 0;
  1327. /* The backer wishes to know when pages are first written to? */
  1328. if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
  1329. return 1;
  1330. /* The open routine did something to the protections that pgprot_modify
  1331. * won't preserve? */
  1332. if (pgprot_val(vma->vm_page_prot) !=
  1333. pgprot_val(vm_pgprot_modify(vma->vm_page_prot, vm_flags)))
  1334. return 0;
  1335. /* Do we need to track softdirty? */
  1336. if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
  1337. return 1;
  1338. /* Specialty mapping? */
  1339. if (vm_flags & VM_PFNMAP)
  1340. return 0;
  1341. /* Can the mapping track the dirty pages? */
  1342. return vma->vm_file && vma->vm_file->f_mapping &&
  1343. mapping_cap_account_dirty(vma->vm_file->f_mapping);
  1344. }
  1345. /*
  1346. * We account for memory if it's a private writeable mapping,
  1347. * not hugepages and VM_NORESERVE wasn't set.
  1348. */
  1349. static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
  1350. {
  1351. /*
  1352. * hugetlb has its own accounting separate from the core VM
  1353. * VM_HUGETLB may not be set yet so we cannot check for that flag.
  1354. */
  1355. if (file && is_file_hugepages(file))
  1356. return 0;
  1357. return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
  1358. }
  1359. unsigned long mmap_region(struct file *file, unsigned long addr,
  1360. unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
  1361. {
  1362. struct mm_struct *mm = current->mm;
  1363. struct vm_area_struct *vma, *prev;
  1364. int error;
  1365. struct rb_node **rb_link, *rb_parent;
  1366. unsigned long charged = 0;
  1367. /* Check against address space limit. */
  1368. if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
  1369. unsigned long nr_pages;
  1370. /*
  1371. * MAP_FIXED may remove pages of mappings that intersects with
  1372. * requested mapping. Account for the pages it would unmap.
  1373. */
  1374. nr_pages = count_vma_pages_range(mm, addr, addr + len);
  1375. if (!may_expand_vm(mm, vm_flags,
  1376. (len >> PAGE_SHIFT) - nr_pages))
  1377. return -ENOMEM;
  1378. }
  1379. /* Clear old maps */
  1380. while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
  1381. &rb_parent)) {
  1382. if (do_munmap(mm, addr, len))
  1383. return -ENOMEM;
  1384. }
  1385. /*
  1386. * Private writable mapping: check memory availability
  1387. */
  1388. if (accountable_mapping(file, vm_flags)) {
  1389. charged = len >> PAGE_SHIFT;
  1390. if (security_vm_enough_memory_mm(mm, charged))
  1391. return -ENOMEM;
  1392. vm_flags |= VM_ACCOUNT;
  1393. }
  1394. /*
  1395. * Can we just expand an old mapping?
  1396. */
  1397. vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
  1398. NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
  1399. if (vma)
  1400. goto out;
  1401. /*
  1402. * Determine the object being mapped and call the appropriate
  1403. * specific mapper. the address has already been validated, but
  1404. * not unmapped, but the maps are removed from the list.
  1405. */
  1406. vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
  1407. if (!vma) {
  1408. error = -ENOMEM;
  1409. goto unacct_error;
  1410. }
  1411. vma->vm_mm = mm;
  1412. vma->vm_start = addr;
  1413. vma->vm_end = addr + len;
  1414. vma->vm_flags = vm_flags;
  1415. vma->vm_page_prot = vm_get_page_prot(vm_flags);
  1416. vma->vm_pgoff = pgoff;
  1417. INIT_LIST_HEAD(&vma->anon_vma_chain);
  1418. if (file) {
  1419. if (vm_flags & VM_DENYWRITE) {
  1420. error = deny_write_access(file);
  1421. if (error)
  1422. goto free_vma;
  1423. }
  1424. if (vm_flags & VM_SHARED) {
  1425. error = mapping_map_writable(file->f_mapping);
  1426. if (error)
  1427. goto allow_write_and_free_vma;
  1428. }
  1429. /* ->mmap() can change vma->vm_file, but must guarantee that
  1430. * vma_link() below can deny write-access if VM_DENYWRITE is set
  1431. * and map writably if VM_SHARED is set. This usually means the
  1432. * new file must not have been exposed to user-space, yet.
  1433. */
  1434. vma->vm_file = get_file(file);
  1435. error = file->f_op->mmap(file, vma);
  1436. if (error)
  1437. goto unmap_and_free_vma;
  1438. /* Can addr have changed??
  1439. *
  1440. * Answer: Yes, several device drivers can do it in their
  1441. * f_op->mmap method. -DaveM
  1442. * Bug: If addr is changed, prev, rb_link, rb_parent should
  1443. * be updated for vma_link()
  1444. */
  1445. WARN_ON_ONCE(addr != vma->vm_start);
  1446. addr = vma->vm_start;
  1447. vm_flags = vma->vm_flags;
  1448. } else if (vm_flags & VM_SHARED) {
  1449. error = shmem_zero_setup(vma);
  1450. if (error)
  1451. goto free_vma;
  1452. }
  1453. vma_link(mm, vma, prev, rb_link, rb_parent);
  1454. /* Once vma denies write, undo our temporary denial count */
  1455. if (file) {
  1456. if (vm_flags & VM_SHARED)
  1457. mapping_unmap_writable(file->f_mapping);
  1458. if (vm_flags & VM_DENYWRITE)
  1459. allow_write_access(file);
  1460. }
  1461. file = vma->vm_file;
  1462. out:
  1463. perf_event_mmap(vma);
  1464. vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
  1465. if (vm_flags & VM_LOCKED) {
  1466. if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
  1467. vma == get_gate_vma(current->mm)))
  1468. mm->locked_vm += (len >> PAGE_SHIFT);
  1469. else
  1470. vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
  1471. }
  1472. if (file)
  1473. uprobe_mmap(vma);
  1474. /*
  1475. * New (or expanded) vma always get soft dirty status.
  1476. * Otherwise user-space soft-dirty page tracker won't
  1477. * be able to distinguish situation when vma area unmapped,
  1478. * then new mapped in-place (which must be aimed as
  1479. * a completely new data area).
  1480. */
  1481. vma->vm_flags |= VM_SOFTDIRTY;
  1482. vma_set_page_prot(vma);
  1483. return addr;
  1484. unmap_and_free_vma:
  1485. vma->vm_file = NULL;
  1486. fput(file);
  1487. /* Undo any partial mapping done by a device driver. */
  1488. unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
  1489. charged = 0;
  1490. if (vm_flags & VM_SHARED)
  1491. mapping_unmap_writable(file->f_mapping);
  1492. allow_write_and_free_vma:
  1493. if (vm_flags & VM_DENYWRITE)
  1494. allow_write_access(file);
  1495. free_vma:
  1496. kmem_cache_free(vm_area_cachep, vma);
  1497. unacct_error:
  1498. if (charged)
  1499. vm_unacct_memory(charged);
  1500. return error;
  1501. }
  1502. unsigned long unmapped_area(struct vm_unmapped_area_info *info)
  1503. {
  1504. /*
  1505. * We implement the search by looking for an rbtree node that
  1506. * immediately follows a suitable gap. That is,
  1507. * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
  1508. * - gap_end = vma->vm_start >= info->low_limit + length;
  1509. * - gap_end - gap_start >= length
  1510. */
  1511. struct mm_struct *mm = current->mm;
  1512. struct vm_area_struct *vma;
  1513. unsigned long length, low_limit, high_limit, gap_start, gap_end;
  1514. /* Adjust search length to account for worst case alignment overhead */
  1515. length = info->length + info->align_mask;
  1516. if (length < info->length)
  1517. return -ENOMEM;
  1518. /* Adjust search limits by the desired length */
  1519. if (info->high_limit < length)
  1520. return -ENOMEM;
  1521. high_limit = info->high_limit - length;
  1522. if (info->low_limit > high_limit)
  1523. return -ENOMEM;
  1524. low_limit = info->low_limit + length;
  1525. /* Check if rbtree root looks promising */
  1526. if (RB_EMPTY_ROOT(&mm->mm_rb))
  1527. goto check_highest;
  1528. vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
  1529. if (vma->rb_subtree_gap < length)
  1530. goto check_highest;
  1531. while (true) {
  1532. /* Visit left subtree if it looks promising */
  1533. gap_end = vma->vm_start;
  1534. if (gap_end >= low_limit && vma->vm_rb.rb_left) {
  1535. struct vm_area_struct *left =
  1536. rb_entry(vma->vm_rb.rb_left,
  1537. struct vm_area_struct, vm_rb);
  1538. if (left->rb_subtree_gap >= length) {
  1539. vma = left;
  1540. continue;
  1541. }
  1542. }
  1543. gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
  1544. check_current:
  1545. /* Check if current node has a suitable gap */
  1546. if (gap_start > high_limit)
  1547. return -ENOMEM;
  1548. if (gap_end >= low_limit && gap_end - gap_start >= length)
  1549. goto found;
  1550. /* Visit right subtree if it looks promising */
  1551. if (vma->vm_rb.rb_right) {
  1552. struct vm_area_struct *right =
  1553. rb_entry(vma->vm_rb.rb_right,
  1554. struct vm_area_struct, vm_rb);
  1555. if (right->rb_subtree_gap >= length) {
  1556. vma = right;
  1557. continue;
  1558. }
  1559. }
  1560. /* Go back up the rbtree to find next candidate node */
  1561. while (true) {
  1562. struct rb_node *prev = &vma->vm_rb;
  1563. if (!rb_parent(prev))
  1564. goto check_highest;
  1565. vma = rb_entry(rb_parent(prev),
  1566. struct vm_area_struct, vm_rb);
  1567. if (prev == vma->vm_rb.rb_left) {
  1568. gap_start = vma->vm_prev->vm_end;
  1569. gap_end = vma->vm_start;
  1570. goto check_current;
  1571. }
  1572. }
  1573. }
  1574. check_highest:
  1575. /* Check highest gap, which does not precede any rbtree node */
  1576. gap_start = mm->highest_vm_end;
  1577. gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
  1578. if (gap_start > high_limit)
  1579. return -ENOMEM;
  1580. found:
  1581. /* We found a suitable gap. Clip it with the original low_limit. */
  1582. if (gap_start < info->low_limit)
  1583. gap_start = info->low_limit;
  1584. /* Adjust gap address to the desired alignment */
  1585. gap_start += (info->align_offset - gap_start) & info->align_mask;
  1586. VM_BUG_ON(gap_start + info->length > info->high_limit);
  1587. VM_BUG_ON(gap_start + info->length > gap_end);
  1588. return gap_start;
  1589. }
  1590. unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
  1591. {
  1592. struct mm_struct *mm = current->mm;
  1593. struct vm_area_struct *vma;
  1594. unsigned long length, low_limit, high_limit, gap_start, gap_end;
  1595. /* Adjust search length to account for worst case alignment overhead */
  1596. length = info->length + info->align_mask;
  1597. if (length < info->length)
  1598. return -ENOMEM;
  1599. /*
  1600. * Adjust search limits by the desired length.
  1601. * See implementation comment at top of unmapped_area().
  1602. */
  1603. gap_end = info->high_limit;
  1604. if (gap_end < length)
  1605. return -ENOMEM;
  1606. high_limit = gap_end - length;
  1607. if (info->low_limit > high_limit)
  1608. return -ENOMEM;
  1609. low_limit = info->low_limit + length;
  1610. /* Check highest gap, which does not precede any rbtree node */
  1611. gap_start = mm->highest_vm_end;
  1612. if (gap_start <= high_limit)
  1613. goto found_highest;
  1614. /* Check if rbtree root looks promising */
  1615. if (RB_EMPTY_ROOT(&mm->mm_rb))
  1616. return -ENOMEM;
  1617. vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
  1618. if (vma->rb_subtree_gap < length)
  1619. return -ENOMEM;
  1620. while (true) {
  1621. /* Visit right subtree if it looks promising */
  1622. gap_start = vma->vm_prev ? vma->vm_prev->vm_end : 0;
  1623. if (gap_start <= high_limit && vma->vm_rb.rb_right) {
  1624. struct vm_area_struct *right =
  1625. rb_entry(vma->vm_rb.rb_right,
  1626. struct vm_area_struct, vm_rb);
  1627. if (right->rb_subtree_gap >= length) {
  1628. vma = right;
  1629. continue;
  1630. }
  1631. }
  1632. check_current:
  1633. /* Check if current node has a suitable gap */
  1634. gap_end = vma->vm_start;
  1635. if (gap_end < low_limit)
  1636. return -ENOMEM;
  1637. if (gap_start <= high_limit && gap_end - gap_start >= length)
  1638. goto found;
  1639. /* Visit left subtree if it looks promising */
  1640. if (vma->vm_rb.rb_left) {
  1641. struct vm_area_struct *left =
  1642. rb_entry(vma->vm_rb.rb_left,
  1643. struct vm_area_struct, vm_rb);
  1644. if (left->rb_subtree_gap >= length) {
  1645. vma = left;
  1646. continue;
  1647. }
  1648. }
  1649. /* Go back up the rbtree to find next candidate node */
  1650. while (true) {
  1651. struct rb_node *prev = &vma->vm_rb;
  1652. if (!rb_parent(prev))
  1653. return -ENOMEM;
  1654. vma = rb_entry(rb_parent(prev),
  1655. struct vm_area_struct, vm_rb);
  1656. if (prev == vma->vm_rb.rb_right) {
  1657. gap_start = vma->vm_prev ?
  1658. vma->vm_prev->vm_end : 0;
  1659. goto check_current;
  1660. }
  1661. }
  1662. }
  1663. found:
  1664. /* We found a suitable gap. Clip it with the original high_limit. */
  1665. if (gap_end > info->high_limit)
  1666. gap_end = info->high_limit;
  1667. found_highest:
  1668. /* Compute highest gap address at the desired alignment */
  1669. gap_end -= info->length;
  1670. gap_end -= (gap_end - info->align_offset) & info->align_mask;
  1671. VM_BUG_ON(gap_end < info->low_limit);
  1672. VM_BUG_ON(gap_end < gap_start);
  1673. return gap_end;
  1674. }
  1675. /* Get an address range which is currently unmapped.
  1676. * For shmat() with addr=0.
  1677. *
  1678. * Ugly calling convention alert:
  1679. * Return value with the low bits set means error value,
  1680. * ie
  1681. * if (ret & ~PAGE_MASK)
  1682. * error = ret;
  1683. *
  1684. * This function "knows" that -ENOMEM has the bits set.
  1685. */
  1686. #ifndef HAVE_ARCH_UNMAPPED_AREA
  1687. unsigned long
  1688. arch_get_unmapped_area(struct file *filp, unsigned long addr,
  1689. unsigned long len, unsigned long pgoff, unsigned long flags)
  1690. {
  1691. struct mm_struct *mm = current->mm;
  1692. struct vm_area_struct *vma;
  1693. struct vm_unmapped_area_info info;
  1694. if (len > TASK_SIZE - mmap_min_addr)
  1695. return -ENOMEM;
  1696. if (flags & MAP_FIXED)
  1697. return addr;
  1698. if (addr) {
  1699. addr = PAGE_ALIGN(addr);
  1700. vma = find_vma(mm, addr);
  1701. if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
  1702. (!vma || addr + len <= vma->vm_start))
  1703. return addr;
  1704. }
  1705. info.flags = 0;
  1706. info.length = len;
  1707. info.low_limit = mm->mmap_base;
  1708. info.high_limit = TASK_SIZE;
  1709. info.align_mask = 0;
  1710. return vm_unmapped_area(&info);
  1711. }
  1712. #endif
  1713. /*
  1714. * This mmap-allocator allocates new areas top-down from below the
  1715. * stack's low limit (the base):
  1716. */
  1717. #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
  1718. unsigned long
  1719. arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
  1720. const unsigned long len, const unsigned long pgoff,
  1721. const unsigned long flags)
  1722. {
  1723. struct vm_area_struct *vma;
  1724. struct mm_struct *mm = current->mm;
  1725. unsigned long addr = addr0;
  1726. struct vm_unmapped_area_info info;
  1727. /* requested length too big for entire address space */
  1728. if (len > TASK_SIZE - mmap_min_addr)
  1729. return -ENOMEM;
  1730. if (flags & MAP_FIXED)
  1731. return addr;
  1732. /* requesting a specific address */
  1733. if (addr) {
  1734. addr = PAGE_ALIGN(addr);
  1735. vma = find_vma(mm, addr);
  1736. if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
  1737. (!vma || addr + len <= vma->vm_start))
  1738. return addr;
  1739. }
  1740. info.flags = VM_UNMAPPED_AREA_TOPDOWN;
  1741. info.length = len;
  1742. info.low_limit = max(PAGE_SIZE, mmap_min_addr);
  1743. info.high_limit = mm->mmap_base;
  1744. info.align_mask = 0;
  1745. addr = vm_unmapped_area(&info);
  1746. /*
  1747. * A failed mmap() very likely causes application failure,
  1748. * so fall back to the bottom-up function here. This scenario
  1749. * can happen with large stack limits and large mmap()
  1750. * allocations.
  1751. */
  1752. if (offset_in_page(addr)) {
  1753. VM_BUG_ON(addr != -ENOMEM);
  1754. info.flags = 0;
  1755. info.low_limit = TASK_UNMAPPED_BASE;
  1756. info.high_limit = TASK_SIZE;
  1757. addr = vm_unmapped_area(&info);
  1758. }
  1759. return addr;
  1760. }
  1761. #endif
  1762. unsigned long
  1763. get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
  1764. unsigned long pgoff, unsigned long flags)
  1765. {
  1766. unsigned long (*get_area)(struct file *, unsigned long,
  1767. unsigned long, unsigned long, unsigned long);
  1768. unsigned long error = arch_mmap_check(addr, len, flags);
  1769. if (error)
  1770. return error;
  1771. /* Careful about overflows.. */
  1772. if (len > TASK_SIZE)
  1773. return -ENOMEM;
  1774. get_area = current->mm->get_unmapped_area;
  1775. if (file && file->f_op->get_unmapped_area)
  1776. get_area = file->f_op->get_unmapped_area;
  1777. addr = get_area(file, addr, len, pgoff, flags);
  1778. if (IS_ERR_VALUE(addr))
  1779. return addr;
  1780. if (addr > TASK_SIZE - len)
  1781. return -ENOMEM;
  1782. if (offset_in_page(addr))
  1783. return -EINVAL;
  1784. addr = arch_rebalance_pgtables(addr, len);
  1785. error = security_mmap_addr(addr);
  1786. return error ? error : addr;
  1787. }
  1788. EXPORT_SYMBOL(get_unmapped_area);
  1789. /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
  1790. struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
  1791. {
  1792. struct rb_node *rb_node;
  1793. struct vm_area_struct *vma;
  1794. /* Check the cache first. */
  1795. vma = vmacache_find(mm, addr);
  1796. if (likely(vma))
  1797. return vma;
  1798. rb_node = mm->mm_rb.rb_node;
  1799. while (rb_node) {
  1800. struct vm_area_struct *tmp;
  1801. tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
  1802. if (tmp->vm_end > addr) {
  1803. vma = tmp;
  1804. if (tmp->vm_start <= addr)
  1805. break;
  1806. rb_node = rb_node->rb_left;
  1807. } else
  1808. rb_node = rb_node->rb_right;
  1809. }
  1810. if (vma)
  1811. vmacache_update(addr, vma);
  1812. return vma;
  1813. }
  1814. EXPORT_SYMBOL(find_vma);
  1815. /*
  1816. * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
  1817. */
  1818. struct vm_area_struct *
  1819. find_vma_prev(struct mm_struct *mm, unsigned long addr,
  1820. struct vm_area_struct **pprev)
  1821. {
  1822. struct vm_area_struct *vma;
  1823. vma = find_vma(mm, addr);
  1824. if (vma) {
  1825. *pprev = vma->vm_prev;
  1826. } else {
  1827. struct rb_node *rb_node = mm->mm_rb.rb_node;
  1828. *pprev = NULL;
  1829. while (rb_node) {
  1830. *pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
  1831. rb_node = rb_node->rb_right;
  1832. }
  1833. }
  1834. return vma;
  1835. }
  1836. /*
  1837. * Verify that the stack growth is acceptable and
  1838. * update accounting. This is shared with both the
  1839. * grow-up and grow-down cases.
  1840. */
  1841. static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, unsigned long grow)
  1842. {
  1843. struct mm_struct *mm = vma->vm_mm;
  1844. struct rlimit *rlim = current->signal->rlim;
  1845. unsigned long new_start, actual_size;
  1846. /* address space limit tests */
  1847. if (!may_expand_vm(mm, vma->vm_flags, grow))
  1848. return -ENOMEM;
  1849. /* Stack limit test */
  1850. actual_size = size;
  1851. if (size && (vma->vm_flags & (VM_GROWSUP | VM_GROWSDOWN)))
  1852. actual_size -= PAGE_SIZE;
  1853. if (actual_size > READ_ONCE(rlim[RLIMIT_STACK].rlim_cur))
  1854. return -ENOMEM;
  1855. /* mlock limit tests */
  1856. if (vma->vm_flags & VM_LOCKED) {
  1857. unsigned long locked;
  1858. unsigned long limit;
  1859. locked = mm->locked_vm + grow;
  1860. limit = READ_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
  1861. limit >>= PAGE_SHIFT;
  1862. if (locked > limit && !capable(CAP_IPC_LOCK))
  1863. return -ENOMEM;
  1864. }
  1865. /* Check to ensure the stack will not grow into a hugetlb-only region */
  1866. new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
  1867. vma->vm_end - size;
  1868. if (is_hugepage_only_range(vma->vm_mm, new_start, size))
  1869. return -EFAULT;
  1870. /*
  1871. * Overcommit.. This must be the final test, as it will
  1872. * update security statistics.
  1873. */
  1874. if (security_vm_enough_memory_mm(mm, grow))
  1875. return -ENOMEM;
  1876. return 0;
  1877. }
  1878. #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
  1879. /*
  1880. * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
  1881. * vma is the last one with address > vma->vm_end. Have to extend vma.
  1882. */
  1883. int expand_upwards(struct vm_area_struct *vma, unsigned long address)
  1884. {
  1885. struct mm_struct *mm = vma->vm_mm;
  1886. int error = 0;
  1887. if (!(vma->vm_flags & VM_GROWSUP))
  1888. return -EFAULT;
  1889. /* Guard against wrapping around to address 0. */
  1890. if (address < PAGE_ALIGN(address+4))
  1891. address = PAGE_ALIGN(address+4);
  1892. else
  1893. return -ENOMEM;
  1894. /* We must make sure the anon_vma is allocated. */
  1895. if (unlikely(anon_vma_prepare(vma)))
  1896. return -ENOMEM;
  1897. /*
  1898. * vma->vm_start/vm_end cannot change under us because the caller
  1899. * is required to hold the mmap_sem in read mode. We need the
  1900. * anon_vma lock to serialize against concurrent expand_stacks.
  1901. */
  1902. anon_vma_lock_write(vma->anon_vma);
  1903. /* Somebody else might have raced and expanded it already */
  1904. if (address > vma->vm_end) {
  1905. unsigned long size, grow;
  1906. size = address - vma->vm_start;
  1907. grow = (address - vma->vm_end) >> PAGE_SHIFT;
  1908. error = -ENOMEM;
  1909. if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
  1910. error = acct_stack_growth(vma, size, grow);
  1911. if (!error) {
  1912. /*
  1913. * vma_gap_update() doesn't support concurrent
  1914. * updates, but we only hold a shared mmap_sem
  1915. * lock here, so we need to protect against
  1916. * concurrent vma expansions.
  1917. * anon_vma_lock_write() doesn't help here, as
  1918. * we don't guarantee that all growable vmas
  1919. * in a mm share the same root anon vma.
  1920. * So, we reuse mm->page_table_lock to guard
  1921. * against concurrent vma expansions.
  1922. */
  1923. spin_lock(&mm->page_table_lock);
  1924. if (vma->vm_flags & VM_LOCKED)
  1925. mm->locked_vm += grow;
  1926. vm_stat_account(mm, vma->vm_flags, grow);
  1927. anon_vma_interval_tree_pre_update_vma(vma);
  1928. vma->vm_end = address;
  1929. anon_vma_interval_tree_post_update_vma(vma);
  1930. if (vma->vm_next)
  1931. vma_gap_update(vma->vm_next);
  1932. else
  1933. mm->highest_vm_end = address;
  1934. spin_unlock(&mm->page_table_lock);
  1935. perf_event_mmap(vma);
  1936. }
  1937. }
  1938. }
  1939. anon_vma_unlock_write(vma->anon_vma);
  1940. khugepaged_enter_vma_merge(vma, vma->vm_flags);
  1941. validate_mm(mm);
  1942. return error;
  1943. }
  1944. #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
  1945. /*
  1946. * vma is the first one with address < vma->vm_start. Have to extend vma.
  1947. */
  1948. int expand_downwards(struct vm_area_struct *vma,
  1949. unsigned long address)
  1950. {
  1951. struct mm_struct *mm = vma->vm_mm;
  1952. int error;
  1953. address &= PAGE_MASK;
  1954. error = security_mmap_addr(address);
  1955. if (error)
  1956. return error;
  1957. /* We must make sure the anon_vma is allocated. */
  1958. if (unlikely(anon_vma_prepare(vma)))
  1959. return -ENOMEM;
  1960. /*
  1961. * vma->vm_start/vm_end cannot change under us because the caller
  1962. * is required to hold the mmap_sem in read mode. We need the
  1963. * anon_vma lock to serialize against concurrent expand_stacks.
  1964. */
  1965. anon_vma_lock_write(vma->anon_vma);
  1966. /* Somebody else might have raced and expanded it already */
  1967. if (address < vma->vm_start) {
  1968. unsigned long size, grow;
  1969. size = vma->vm_end - address;
  1970. grow = (vma->vm_start - address) >> PAGE_SHIFT;
  1971. error = -ENOMEM;
  1972. if (grow <= vma->vm_pgoff) {
  1973. error = acct_stack_growth(vma, size, grow);
  1974. if (!error) {
  1975. /*
  1976. * vma_gap_update() doesn't support concurrent
  1977. * updates, but we only hold a shared mmap_sem
  1978. * lock here, so we need to protect against
  1979. * concurrent vma expansions.
  1980. * anon_vma_lock_write() doesn't help here, as
  1981. * we don't guarantee that all growable vmas
  1982. * in a mm share the same root anon vma.
  1983. * So, we reuse mm->page_table_lock to guard
  1984. * against concurrent vma expansions.
  1985. */
  1986. spin_lock(&mm->page_table_lock);
  1987. if (vma->vm_flags & VM_LOCKED)
  1988. mm->locked_vm += grow;
  1989. vm_stat_account(mm, vma->vm_flags, grow);
  1990. anon_vma_interval_tree_pre_update_vma(vma);
  1991. vma->vm_start = address;
  1992. vma->vm_pgoff -= grow;
  1993. anon_vma_interval_tree_post_update_vma(vma);
  1994. vma_gap_update(vma);
  1995. spin_unlock(&mm->page_table_lock);
  1996. perf_event_mmap(vma);
  1997. }
  1998. }
  1999. }
  2000. anon_vma_unlock_write(vma->anon_vma);
  2001. khugepaged_enter_vma_merge(vma, vma->vm_flags);
  2002. validate_mm(mm);
  2003. return error;
  2004. }
  2005. /*
  2006. * Note how expand_stack() refuses to expand the stack all the way to
  2007. * abut the next virtual mapping, *unless* that mapping itself is also
  2008. * a stack mapping. We want to leave room for a guard page, after all
  2009. * (the guard page itself is not added here, that is done by the
  2010. * actual page faulting logic)
  2011. *
  2012. * This matches the behavior of the guard page logic (see mm/memory.c:
  2013. * check_stack_guard_page()), which only allows the guard page to be
  2014. * removed under these circumstances.
  2015. */
  2016. #ifdef CONFIG_STACK_GROWSUP
  2017. int expand_stack(struct vm_area_struct *vma, unsigned long address)
  2018. {
  2019. struct vm_area_struct *next;
  2020. address &= PAGE_MASK;
  2021. next = vma->vm_next;
  2022. if (next && next->vm_start == address + PAGE_SIZE) {
  2023. if (!(next->vm_flags & VM_GROWSUP))
  2024. return -ENOMEM;
  2025. }
  2026. return expand_upwards(vma, address);
  2027. }
  2028. struct vm_area_struct *
  2029. find_extend_vma(struct mm_struct *mm, unsigned long addr)
  2030. {
  2031. struct vm_area_struct *vma, *prev;
  2032. addr &= PAGE_MASK;
  2033. vma = find_vma_prev(mm, addr, &prev);
  2034. if (vma && (vma->vm_start <= addr))
  2035. return vma;
  2036. if (!prev || expand_stack(prev, addr))
  2037. return NULL;
  2038. if (prev->vm_flags & VM_LOCKED)
  2039. populate_vma_page_range(prev, addr, prev->vm_end, NULL);
  2040. return prev;
  2041. }
  2042. #else
  2043. int expand_stack(struct vm_area_struct *vma, unsigned long address)
  2044. {
  2045. struct vm_area_struct *prev;
  2046. address &= PAGE_MASK;
  2047. prev = vma->vm_prev;
  2048. if (prev && prev->vm_end == address) {
  2049. if (!(prev->vm_flags & VM_GROWSDOWN))
  2050. return -ENOMEM;
  2051. }
  2052. return expand_downwards(vma, address);
  2053. }
  2054. struct vm_area_struct *
  2055. find_extend_vma(struct mm_struct *mm, unsigned long addr)
  2056. {
  2057. struct vm_area_struct *vma;
  2058. unsigned long start;
  2059. addr &= PAGE_MASK;
  2060. vma = find_vma(mm, addr);
  2061. if (!vma)
  2062. return NULL;
  2063. if (vma->vm_start <= addr)
  2064. return vma;
  2065. if (!(vma->vm_flags & VM_GROWSDOWN))
  2066. return NULL;
  2067. start = vma->vm_start;
  2068. if (expand_stack(vma, addr))
  2069. return NULL;
  2070. if (vma->vm_flags & VM_LOCKED)
  2071. populate_vma_page_range(vma, addr, start, NULL);
  2072. return vma;
  2073. }
  2074. #endif
  2075. EXPORT_SYMBOL_GPL(find_extend_vma);
  2076. /*
  2077. * Ok - we have the memory areas we should free on the vma list,
  2078. * so release them, and do the vma updates.
  2079. *
  2080. * Called with the mm semaphore held.
  2081. */
  2082. static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
  2083. {
  2084. unsigned long nr_accounted = 0;
  2085. /* Update high watermark before we lower total_vm */
  2086. update_hiwater_vm(mm);
  2087. do {
  2088. long nrpages = vma_pages(vma);
  2089. if (vma->vm_flags & VM_ACCOUNT)
  2090. nr_accounted += nrpages;
  2091. vm_stat_account(mm, vma->vm_flags, -nrpages);
  2092. vma = remove_vma(vma);
  2093. } while (vma);
  2094. vm_unacct_memory(nr_accounted);
  2095. validate_mm(mm);
  2096. }
  2097. /*
  2098. * Get rid of page table information in the indicated region.
  2099. *
  2100. * Called with the mm semaphore held.
  2101. */
  2102. static void unmap_region(struct mm_struct *mm,
  2103. struct vm_area_struct *vma, struct vm_area_struct *prev,
  2104. unsigned long start, unsigned long end)
  2105. {
  2106. struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
  2107. struct mmu_gather tlb;
  2108. lru_add_drain();
  2109. tlb_gather_mmu(&tlb, mm, start, end);
  2110. update_hiwater_rss(mm);
  2111. unmap_vmas(&tlb, vma, start, end);
  2112. free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
  2113. next ? next->vm_start : USER_PGTABLES_CEILING);
  2114. tlb_finish_mmu(&tlb, start, end);
  2115. }
  2116. /*
  2117. * Create a list of vma's touched by the unmap, removing them from the mm's
  2118. * vma list as we go..
  2119. */
  2120. static void
  2121. detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
  2122. struct vm_area_struct *prev, unsigned long end)
  2123. {
  2124. struct vm_area_struct **insertion_point;
  2125. struct vm_area_struct *tail_vma = NULL;
  2126. insertion_point = (prev ? &prev->vm_next : &mm->mmap);
  2127. vma->vm_prev = NULL;
  2128. do {
  2129. vma_rb_erase(vma, &mm->mm_rb);
  2130. mm->map_count--;
  2131. tail_vma = vma;
  2132. vma = vma->vm_next;
  2133. } while (vma && vma->vm_start < end);
  2134. *insertion_point = vma;
  2135. if (vma) {
  2136. vma->vm_prev = prev;
  2137. vma_gap_update(vma);
  2138. } else
  2139. mm->highest_vm_end = prev ? prev->vm_end : 0;
  2140. tail_vma->vm_next = NULL;
  2141. /* Kill the cache */
  2142. vmacache_invalidate(mm);
  2143. }
  2144. /*
  2145. * __split_vma() bypasses sysctl_max_map_count checking. We use this on the
  2146. * munmap path where it doesn't make sense to fail.
  2147. */
  2148. static int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
  2149. unsigned long addr, int new_below)
  2150. {
  2151. struct vm_area_struct *new;
  2152. int err;
  2153. if (is_vm_hugetlb_page(vma) && (addr &
  2154. ~(huge_page_mask(hstate_vma(vma)))))
  2155. return -EINVAL;
  2156. new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
  2157. if (!new)
  2158. return -ENOMEM;
  2159. /* most fields are the same, copy all, and then fixup */
  2160. *new = *vma;
  2161. INIT_LIST_HEAD(&new->anon_vma_chain);
  2162. if (new_below)
  2163. new->vm_end = addr;
  2164. else {
  2165. new->vm_start = addr;
  2166. new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
  2167. }
  2168. err = vma_dup_policy(vma, new);
  2169. if (err)
  2170. goto out_free_vma;
  2171. err = anon_vma_clone(new, vma);
  2172. if (err)
  2173. goto out_free_mpol;
  2174. if (new->vm_file)
  2175. get_file(new->vm_file);
  2176. if (new->vm_ops && new->vm_ops->open)
  2177. new->vm_ops->open(new);
  2178. if (new_below)
  2179. err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
  2180. ((addr - new->vm_start) >> PAGE_SHIFT), new);
  2181. else
  2182. err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
  2183. /* Success. */
  2184. if (!err)
  2185. return 0;
  2186. /* Clean everything up if vma_adjust failed. */
  2187. if (new->vm_ops && new->vm_ops->close)
  2188. new->vm_ops->close(new);
  2189. if (new->vm_file)
  2190. fput(new->vm_file);
  2191. unlink_anon_vmas(new);
  2192. out_free_mpol:
  2193. mpol_put(vma_policy(new));
  2194. out_free_vma:
  2195. kmem_cache_free(vm_area_cachep, new);
  2196. return err;
  2197. }
  2198. /*
  2199. * Split a vma into two pieces at address 'addr', a new vma is allocated
  2200. * either for the first part or the tail.
  2201. */
  2202. int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
  2203. unsigned long addr, int new_below)
  2204. {
  2205. if (mm->map_count >= sysctl_max_map_count)
  2206. return -ENOMEM;
  2207. return __split_vma(mm, vma, addr, new_below);
  2208. }
  2209. /* Munmap is split into 2 main parts -- this part which finds
  2210. * what needs doing, and the areas themselves, which do the
  2211. * work. This now handles partial unmappings.
  2212. * Jeremy Fitzhardinge <jeremy@goop.org>
  2213. */
  2214. int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
  2215. {
  2216. unsigned long end;
  2217. struct vm_area_struct *vma, *prev, *last;
  2218. if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
  2219. return -EINVAL;
  2220. len = PAGE_ALIGN(len);
  2221. if (len == 0)
  2222. return -EINVAL;
  2223. /* Find the first overlapping VMA */
  2224. vma = find_vma(mm, start);
  2225. if (!vma)
  2226. return 0;
  2227. prev = vma->vm_prev;
  2228. /* we have start < vma->vm_end */
  2229. /* if it doesn't overlap, we have nothing.. */
  2230. end = start + len;
  2231. if (vma->vm_start >= end)
  2232. return 0;
  2233. /*
  2234. * If we need to split any vma, do it now to save pain later.
  2235. *
  2236. * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
  2237. * unmapped vm_area_struct will remain in use: so lower split_vma
  2238. * places tmp vma above, and higher split_vma places tmp vma below.
  2239. */
  2240. if (start > vma->vm_start) {
  2241. int error;
  2242. /*
  2243. * Make sure that map_count on return from munmap() will
  2244. * not exceed its limit; but let map_count go just above
  2245. * its limit temporarily, to help free resources as expected.
  2246. */
  2247. if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
  2248. return -ENOMEM;
  2249. error = __split_vma(mm, vma, start, 0);
  2250. if (error)
  2251. return error;
  2252. prev = vma;
  2253. }
  2254. /* Does it split the last one? */
  2255. last = find_vma(mm, end);
  2256. if (last && end > last->vm_start) {
  2257. int error = __split_vma(mm, last, end, 1);
  2258. if (error)
  2259. return error;
  2260. }
  2261. vma = prev ? prev->vm_next : mm->mmap;
  2262. /*
  2263. * unlock any mlock()ed ranges before detaching vmas
  2264. */
  2265. if (mm->locked_vm) {
  2266. struct vm_area_struct *tmp = vma;
  2267. while (tmp && tmp->vm_start < end) {
  2268. if (tmp->vm_flags & VM_LOCKED) {
  2269. mm->locked_vm -= vma_pages(tmp);
  2270. munlock_vma_pages_all(tmp);
  2271. }
  2272. tmp = tmp->vm_next;
  2273. }
  2274. }
  2275. /*
  2276. * Remove the vma's, and unmap the actual pages
  2277. */
  2278. detach_vmas_to_be_unmapped(mm, vma, prev, end);
  2279. unmap_region(mm, vma, prev, start, end);
  2280. arch_unmap(mm, vma, start, end);
  2281. /* Fix up all other VM information */
  2282. remove_vma_list(mm, vma);
  2283. return 0;
  2284. }
  2285. int vm_munmap(unsigned long start, size_t len)
  2286. {
  2287. int ret;
  2288. struct mm_struct *mm = current->mm;
  2289. down_write(&mm->mmap_sem);
  2290. ret = do_munmap(mm, start, len);
  2291. up_write(&mm->mmap_sem);
  2292. return ret;
  2293. }
  2294. EXPORT_SYMBOL(vm_munmap);
  2295. SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
  2296. {
  2297. profile_munmap(addr);
  2298. return vm_munmap(addr, len);
  2299. }
  2300. /*
  2301. * Emulation of deprecated remap_file_pages() syscall.
  2302. */
  2303. SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
  2304. unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
  2305. {
  2306. struct mm_struct *mm = current->mm;
  2307. struct vm_area_struct *vma;
  2308. unsigned long populate = 0;
  2309. unsigned long ret = -EINVAL;
  2310. struct file *file;
  2311. pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. "
  2312. "See Documentation/vm/remap_file_pages.txt.\n",
  2313. current->comm, current->pid);
  2314. if (prot)
  2315. return ret;
  2316. start = start & PAGE_MASK;
  2317. size = size & PAGE_MASK;
  2318. if (start + size <= start)
  2319. return ret;
  2320. /* Does pgoff wrap? */
  2321. if (pgoff + (size >> PAGE_SHIFT) < pgoff)
  2322. return ret;
  2323. down_write(&mm->mmap_sem);
  2324. vma = find_vma(mm, start);
  2325. if (!vma || !(vma->vm_flags & VM_SHARED))
  2326. goto out;
  2327. if (start < vma->vm_start)
  2328. goto out;
  2329. if (start + size > vma->vm_end) {
  2330. struct vm_area_struct *next;
  2331. for (next = vma->vm_next; next; next = next->vm_next) {
  2332. /* hole between vmas ? */
  2333. if (next->vm_start != next->vm_prev->vm_end)
  2334. goto out;
  2335. if (next->vm_file != vma->vm_file)
  2336. goto out;
  2337. if (next->vm_flags != vma->vm_flags)
  2338. goto out;
  2339. if (start + size <= next->vm_end)
  2340. break;
  2341. }
  2342. if (!next)
  2343. goto out;
  2344. }
  2345. prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
  2346. prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
  2347. prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
  2348. flags &= MAP_NONBLOCK;
  2349. flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
  2350. if (vma->vm_flags & VM_LOCKED) {
  2351. struct vm_area_struct *tmp;
  2352. flags |= MAP_LOCKED;
  2353. /* drop PG_Mlocked flag for over-mapped range */
  2354. for (tmp = vma; tmp->vm_start >= start + size;
  2355. tmp = tmp->vm_next) {
  2356. munlock_vma_pages_range(tmp,
  2357. max(tmp->vm_start, start),
  2358. min(tmp->vm_end, start + size));
  2359. }
  2360. }
  2361. file = get_file(vma->vm_file);
  2362. ret = do_mmap_pgoff(vma->vm_file, start, size,
  2363. prot, flags, pgoff, &populate);
  2364. fput(file);
  2365. out:
  2366. up_write(&mm->mmap_sem);
  2367. if (populate)
  2368. mm_populate(ret, populate);
  2369. if (!IS_ERR_VALUE(ret))
  2370. ret = 0;
  2371. return ret;
  2372. }
  2373. static inline void verify_mm_writelocked(struct mm_struct *mm)
  2374. {
  2375. #ifdef CONFIG_DEBUG_VM
  2376. if (unlikely(down_read_trylock(&mm->mmap_sem))) {
  2377. WARN_ON(1);
  2378. up_read(&mm->mmap_sem);
  2379. }
  2380. #endif
  2381. }
  2382. /*
  2383. * this is really a simplified "do_mmap". it only handles
  2384. * anonymous maps. eventually we may be able to do some
  2385. * brk-specific accounting here.
  2386. */
  2387. static unsigned long do_brk(unsigned long addr, unsigned long len)
  2388. {
  2389. struct mm_struct *mm = current->mm;
  2390. struct vm_area_struct *vma, *prev;
  2391. unsigned long flags;
  2392. struct rb_node **rb_link, *rb_parent;
  2393. pgoff_t pgoff = addr >> PAGE_SHIFT;
  2394. int error;
  2395. len = PAGE_ALIGN(len);
  2396. if (!len)
  2397. return addr;
  2398. flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
  2399. error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
  2400. if (offset_in_page(error))
  2401. return error;
  2402. error = mlock_future_check(mm, mm->def_flags, len);
  2403. if (error)
  2404. return error;
  2405. /*
  2406. * mm->mmap_sem is required to protect against another thread
  2407. * changing the mappings in case we sleep.
  2408. */
  2409. verify_mm_writelocked(mm);
  2410. /*
  2411. * Clear old maps. this also does some error checking for us
  2412. */
  2413. while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
  2414. &rb_parent)) {
  2415. if (do_munmap(mm, addr, len))
  2416. return -ENOMEM;
  2417. }
  2418. /* Check against address space limits *after* clearing old maps... */
  2419. if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
  2420. return -ENOMEM;
  2421. if (mm->map_count > sysctl_max_map_count)
  2422. return -ENOMEM;
  2423. if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
  2424. return -ENOMEM;
  2425. /* Can we just expand an old private anonymous mapping? */
  2426. vma = vma_merge(mm, prev, addr, addr + len, flags,
  2427. NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
  2428. if (vma)
  2429. goto out;
  2430. /*
  2431. * create a vma struct for an anonymous mapping
  2432. */
  2433. vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
  2434. if (!vma) {
  2435. vm_unacct_memory(len >> PAGE_SHIFT);
  2436. return -ENOMEM;
  2437. }
  2438. INIT_LIST_HEAD(&vma->anon_vma_chain);
  2439. vma->vm_mm = mm;
  2440. vma->vm_start = addr;
  2441. vma->vm_end = addr + len;
  2442. vma->vm_pgoff = pgoff;
  2443. vma->vm_flags = flags;
  2444. vma->vm_page_prot = vm_get_page_prot(flags);
  2445. vma_link(mm, vma, prev, rb_link, rb_parent);
  2446. out:
  2447. perf_event_mmap(vma);
  2448. mm->total_vm += len >> PAGE_SHIFT;
  2449. mm->data_vm += len >> PAGE_SHIFT;
  2450. if (flags & VM_LOCKED)
  2451. mm->locked_vm += (len >> PAGE_SHIFT);
  2452. vma->vm_flags |= VM_SOFTDIRTY;
  2453. return addr;
  2454. }
  2455. unsigned long vm_brk(unsigned long addr, unsigned long len)
  2456. {
  2457. struct mm_struct *mm = current->mm;
  2458. unsigned long ret;
  2459. bool populate;
  2460. down_write(&mm->mmap_sem);
  2461. ret = do_brk(addr, len);
  2462. populate = ((mm->def_flags & VM_LOCKED) != 0);
  2463. up_write(&mm->mmap_sem);
  2464. if (populate)
  2465. mm_populate(addr, len);
  2466. return ret;
  2467. }
  2468. EXPORT_SYMBOL(vm_brk);
  2469. /* Release all mmaps. */
  2470. void exit_mmap(struct mm_struct *mm)
  2471. {
  2472. struct mmu_gather tlb;
  2473. struct vm_area_struct *vma;
  2474. unsigned long nr_accounted = 0;
  2475. /* mm's last user has gone, and its about to be pulled down */
  2476. mmu_notifier_release(mm);
  2477. if (mm->locked_vm) {
  2478. vma = mm->mmap;
  2479. while (vma) {
  2480. if (vma->vm_flags & VM_LOCKED)
  2481. munlock_vma_pages_all(vma);
  2482. vma = vma->vm_next;
  2483. }
  2484. }
  2485. arch_exit_mmap(mm);
  2486. vma = mm->mmap;
  2487. if (!vma) /* Can happen if dup_mmap() received an OOM */
  2488. return;
  2489. lru_add_drain();
  2490. flush_cache_mm(mm);
  2491. tlb_gather_mmu(&tlb, mm, 0, -1);
  2492. /* update_hiwater_rss(mm) here? but nobody should be looking */
  2493. /* Use -1 here to ensure all VMAs in the mm are unmapped */
  2494. unmap_vmas(&tlb, vma, 0, -1);
  2495. free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
  2496. tlb_finish_mmu(&tlb, 0, -1);
  2497. /*
  2498. * Walk the list again, actually closing and freeing it,
  2499. * with preemption enabled, without holding any MM locks.
  2500. */
  2501. while (vma) {
  2502. if (vma->vm_flags & VM_ACCOUNT)
  2503. nr_accounted += vma_pages(vma);
  2504. vma = remove_vma(vma);
  2505. }
  2506. vm_unacct_memory(nr_accounted);
  2507. }
  2508. /* Insert vm structure into process list sorted by address
  2509. * and into the inode's i_mmap tree. If vm_file is non-NULL
  2510. * then i_mmap_rwsem is taken here.
  2511. */
  2512. int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
  2513. {
  2514. struct vm_area_struct *prev;
  2515. struct rb_node **rb_link, *rb_parent;
  2516. if (find_vma_links(mm, vma->vm_start, vma->vm_end,
  2517. &prev, &rb_link, &rb_parent))
  2518. return -ENOMEM;
  2519. if ((vma->vm_flags & VM_ACCOUNT) &&
  2520. security_vm_enough_memory_mm(mm, vma_pages(vma)))
  2521. return -ENOMEM;
  2522. /*
  2523. * The vm_pgoff of a purely anonymous vma should be irrelevant
  2524. * until its first write fault, when page's anon_vma and index
  2525. * are set. But now set the vm_pgoff it will almost certainly
  2526. * end up with (unless mremap moves it elsewhere before that
  2527. * first wfault), so /proc/pid/maps tells a consistent story.
  2528. *
  2529. * By setting it to reflect the virtual start address of the
  2530. * vma, merges and splits can happen in a seamless way, just
  2531. * using the existing file pgoff checks and manipulations.
  2532. * Similarly in do_mmap_pgoff and in do_brk.
  2533. */
  2534. if (vma_is_anonymous(vma)) {
  2535. BUG_ON(vma->anon_vma);
  2536. vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
  2537. }
  2538. vma_link(mm, vma, prev, rb_link, rb_parent);
  2539. return 0;
  2540. }
  2541. /*
  2542. * Copy the vma structure to a new location in the same mm,
  2543. * prior to moving page table entries, to effect an mremap move.
  2544. */
  2545. struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
  2546. unsigned long addr, unsigned long len, pgoff_t pgoff,
  2547. bool *need_rmap_locks)
  2548. {
  2549. struct vm_area_struct *vma = *vmap;
  2550. unsigned long vma_start = vma->vm_start;
  2551. struct mm_struct *mm = vma->vm_mm;
  2552. struct vm_area_struct *new_vma, *prev;
  2553. struct rb_node **rb_link, *rb_parent;
  2554. bool faulted_in_anon_vma = true;
  2555. /*
  2556. * If anonymous vma has not yet been faulted, update new pgoff
  2557. * to match new location, to increase its chance of merging.
  2558. */
  2559. if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
  2560. pgoff = addr >> PAGE_SHIFT;
  2561. faulted_in_anon_vma = false;
  2562. }
  2563. if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
  2564. return NULL; /* should never get here */
  2565. new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
  2566. vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
  2567. vma->vm_userfaultfd_ctx);
  2568. if (new_vma) {
  2569. /*
  2570. * Source vma may have been merged into new_vma
  2571. */
  2572. if (unlikely(vma_start >= new_vma->vm_start &&
  2573. vma_start < new_vma->vm_end)) {
  2574. /*
  2575. * The only way we can get a vma_merge with
  2576. * self during an mremap is if the vma hasn't
  2577. * been faulted in yet and we were allowed to
  2578. * reset the dst vma->vm_pgoff to the
  2579. * destination address of the mremap to allow
  2580. * the merge to happen. mremap must change the
  2581. * vm_pgoff linearity between src and dst vmas
  2582. * (in turn preventing a vma_merge) to be
  2583. * safe. It is only safe to keep the vm_pgoff
  2584. * linear if there are no pages mapped yet.
  2585. */
  2586. VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
  2587. *vmap = vma = new_vma;
  2588. }
  2589. *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
  2590. } else {
  2591. new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
  2592. if (!new_vma)
  2593. goto out;
  2594. *new_vma = *vma;
  2595. new_vma->vm_start = addr;
  2596. new_vma->vm_end = addr + len;
  2597. new_vma->vm_pgoff = pgoff;
  2598. if (vma_dup_policy(vma, new_vma))
  2599. goto out_free_vma;
  2600. INIT_LIST_HEAD(&new_vma->anon_vma_chain);
  2601. if (anon_vma_clone(new_vma, vma))
  2602. goto out_free_mempol;
  2603. if (new_vma->vm_file)
  2604. get_file(new_vma->vm_file);
  2605. if (new_vma->vm_ops && new_vma->vm_ops->open)
  2606. new_vma->vm_ops->open(new_vma);
  2607. vma_link(mm, new_vma, prev, rb_link, rb_parent);
  2608. *need_rmap_locks = false;
  2609. }
  2610. return new_vma;
  2611. out_free_mempol:
  2612. mpol_put(vma_policy(new_vma));
  2613. out_free_vma:
  2614. kmem_cache_free(vm_area_cachep, new_vma);
  2615. out:
  2616. return NULL;
  2617. }
  2618. /*
  2619. * Return true if the calling process may expand its vm space by the passed
  2620. * number of pages
  2621. */
  2622. bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
  2623. {
  2624. if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
  2625. return false;
  2626. if (is_data_mapping(flags) &&
  2627. mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
  2628. if (ignore_rlimit_data)
  2629. pr_warn_once("%s (%d): VmData %lu exceed data ulimit "
  2630. "%lu. Will be forbidden soon.\n",
  2631. current->comm, current->pid,
  2632. (mm->data_vm + npages) << PAGE_SHIFT,
  2633. rlimit(RLIMIT_DATA));
  2634. else
  2635. return false;
  2636. }
  2637. return true;
  2638. }
  2639. void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
  2640. {
  2641. mm->total_vm += npages;
  2642. if (is_exec_mapping(flags))
  2643. mm->exec_vm += npages;
  2644. else if (is_stack_mapping(flags))
  2645. mm->stack_vm += npages;
  2646. else if (is_data_mapping(flags))
  2647. mm->data_vm += npages;
  2648. }
  2649. static int special_mapping_fault(struct vm_area_struct *vma,
  2650. struct vm_fault *vmf);
  2651. /*
  2652. * Having a close hook prevents vma merging regardless of flags.
  2653. */
  2654. static void special_mapping_close(struct vm_area_struct *vma)
  2655. {
  2656. }
  2657. static const char *special_mapping_name(struct vm_area_struct *vma)
  2658. {
  2659. return ((struct vm_special_mapping *)vma->vm_private_data)->name;
  2660. }
  2661. static const struct vm_operations_struct special_mapping_vmops = {
  2662. .close = special_mapping_close,
  2663. .fault = special_mapping_fault,
  2664. .name = special_mapping_name,
  2665. };
  2666. static const struct vm_operations_struct legacy_special_mapping_vmops = {
  2667. .close = special_mapping_close,
  2668. .fault = special_mapping_fault,
  2669. };
  2670. static int special_mapping_fault(struct vm_area_struct *vma,
  2671. struct vm_fault *vmf)
  2672. {
  2673. pgoff_t pgoff;
  2674. struct page **pages;
  2675. if (vma->vm_ops == &legacy_special_mapping_vmops)
  2676. pages = vma->vm_private_data;
  2677. else
  2678. pages = ((struct vm_special_mapping *)vma->vm_private_data)->
  2679. pages;
  2680. for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
  2681. pgoff--;
  2682. if (*pages) {
  2683. struct page *page = *pages;
  2684. get_page(page);
  2685. vmf->page = page;
  2686. return 0;
  2687. }
  2688. return VM_FAULT_SIGBUS;
  2689. }
  2690. static struct vm_area_struct *__install_special_mapping(
  2691. struct mm_struct *mm,
  2692. unsigned long addr, unsigned long len,
  2693. unsigned long vm_flags, void *priv,
  2694. const struct vm_operations_struct *ops)
  2695. {
  2696. int ret;
  2697. struct vm_area_struct *vma;
  2698. vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
  2699. if (unlikely(vma == NULL))
  2700. return ERR_PTR(-ENOMEM);
  2701. INIT_LIST_HEAD(&vma->anon_vma_chain);
  2702. vma->vm_mm = mm;
  2703. vma->vm_start = addr;
  2704. vma->vm_end = addr + len;
  2705. vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
  2706. vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
  2707. vma->vm_ops = ops;
  2708. vma->vm_private_data = priv;
  2709. ret = insert_vm_struct(mm, vma);
  2710. if (ret)
  2711. goto out;
  2712. vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
  2713. perf_event_mmap(vma);
  2714. return vma;
  2715. out:
  2716. kmem_cache_free(vm_area_cachep, vma);
  2717. return ERR_PTR(ret);
  2718. }
  2719. /*
  2720. * Called with mm->mmap_sem held for writing.
  2721. * Insert a new vma covering the given region, with the given flags.
  2722. * Its pages are supplied by the given array of struct page *.
  2723. * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
  2724. * The region past the last page supplied will always produce SIGBUS.
  2725. * The array pointer and the pages it points to are assumed to stay alive
  2726. * for as long as this mapping might exist.
  2727. */
  2728. struct vm_area_struct *_install_special_mapping(
  2729. struct mm_struct *mm,
  2730. unsigned long addr, unsigned long len,
  2731. unsigned long vm_flags, const struct vm_special_mapping *spec)
  2732. {
  2733. return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
  2734. &special_mapping_vmops);
  2735. }
  2736. int install_special_mapping(struct mm_struct *mm,
  2737. unsigned long addr, unsigned long len,
  2738. unsigned long vm_flags, struct page **pages)
  2739. {
  2740. struct vm_area_struct *vma = __install_special_mapping(
  2741. mm, addr, len, vm_flags, (void *)pages,
  2742. &legacy_special_mapping_vmops);
  2743. return PTR_ERR_OR_ZERO(vma);
  2744. }
  2745. static DEFINE_MUTEX(mm_all_locks_mutex);
  2746. static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
  2747. {
  2748. if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
  2749. /*
  2750. * The LSB of head.next can't change from under us
  2751. * because we hold the mm_all_locks_mutex.
  2752. */
  2753. down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
  2754. /*
  2755. * We can safely modify head.next after taking the
  2756. * anon_vma->root->rwsem. If some other vma in this mm shares
  2757. * the same anon_vma we won't take it again.
  2758. *
  2759. * No need of atomic instructions here, head.next
  2760. * can't change from under us thanks to the
  2761. * anon_vma->root->rwsem.
  2762. */
  2763. if (__test_and_set_bit(0, (unsigned long *)
  2764. &anon_vma->root->rb_root.rb_node))
  2765. BUG();
  2766. }
  2767. }
  2768. static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
  2769. {
  2770. if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
  2771. /*
  2772. * AS_MM_ALL_LOCKS can't change from under us because
  2773. * we hold the mm_all_locks_mutex.
  2774. *
  2775. * Operations on ->flags have to be atomic because
  2776. * even if AS_MM_ALL_LOCKS is stable thanks to the
  2777. * mm_all_locks_mutex, there may be other cpus
  2778. * changing other bitflags in parallel to us.
  2779. */
  2780. if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
  2781. BUG();
  2782. down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
  2783. }
  2784. }
  2785. /*
  2786. * This operation locks against the VM for all pte/vma/mm related
  2787. * operations that could ever happen on a certain mm. This includes
  2788. * vmtruncate, try_to_unmap, and all page faults.
  2789. *
  2790. * The caller must take the mmap_sem in write mode before calling
  2791. * mm_take_all_locks(). The caller isn't allowed to release the
  2792. * mmap_sem until mm_drop_all_locks() returns.
  2793. *
  2794. * mmap_sem in write mode is required in order to block all operations
  2795. * that could modify pagetables and free pages without need of
  2796. * altering the vma layout. It's also needed in write mode to avoid new
  2797. * anon_vmas to be associated with existing vmas.
  2798. *
  2799. * A single task can't take more than one mm_take_all_locks() in a row
  2800. * or it would deadlock.
  2801. *
  2802. * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
  2803. * mapping->flags avoid to take the same lock twice, if more than one
  2804. * vma in this mm is backed by the same anon_vma or address_space.
  2805. *
  2806. * We take locks in following order, accordingly to comment at beginning
  2807. * of mm/rmap.c:
  2808. * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
  2809. * hugetlb mapping);
  2810. * - all i_mmap_rwsem locks;
  2811. * - all anon_vma->rwseml
  2812. *
  2813. * We can take all locks within these types randomly because the VM code
  2814. * doesn't nest them and we protected from parallel mm_take_all_locks() by
  2815. * mm_all_locks_mutex.
  2816. *
  2817. * mm_take_all_locks() and mm_drop_all_locks are expensive operations
  2818. * that may have to take thousand of locks.
  2819. *
  2820. * mm_take_all_locks() can fail if it's interrupted by signals.
  2821. */
  2822. int mm_take_all_locks(struct mm_struct *mm)
  2823. {
  2824. struct vm_area_struct *vma;
  2825. struct anon_vma_chain *avc;
  2826. BUG_ON(down_read_trylock(&mm->mmap_sem));
  2827. mutex_lock(&mm_all_locks_mutex);
  2828. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  2829. if (signal_pending(current))
  2830. goto out_unlock;
  2831. if (vma->vm_file && vma->vm_file->f_mapping &&
  2832. is_vm_hugetlb_page(vma))
  2833. vm_lock_mapping(mm, vma->vm_file->f_mapping);
  2834. }
  2835. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  2836. if (signal_pending(current))
  2837. goto out_unlock;
  2838. if (vma->vm_file && vma->vm_file->f_mapping &&
  2839. !is_vm_hugetlb_page(vma))
  2840. vm_lock_mapping(mm, vma->vm_file->f_mapping);
  2841. }
  2842. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  2843. if (signal_pending(current))
  2844. goto out_unlock;
  2845. if (vma->anon_vma)
  2846. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  2847. vm_lock_anon_vma(mm, avc->anon_vma);
  2848. }
  2849. return 0;
  2850. out_unlock:
  2851. mm_drop_all_locks(mm);
  2852. return -EINTR;
  2853. }
  2854. static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
  2855. {
  2856. if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
  2857. /*
  2858. * The LSB of head.next can't change to 0 from under
  2859. * us because we hold the mm_all_locks_mutex.
  2860. *
  2861. * We must however clear the bitflag before unlocking
  2862. * the vma so the users using the anon_vma->rb_root will
  2863. * never see our bitflag.
  2864. *
  2865. * No need of atomic instructions here, head.next
  2866. * can't change from under us until we release the
  2867. * anon_vma->root->rwsem.
  2868. */
  2869. if (!__test_and_clear_bit(0, (unsigned long *)
  2870. &anon_vma->root->rb_root.rb_node))
  2871. BUG();
  2872. anon_vma_unlock_write(anon_vma);
  2873. }
  2874. }
  2875. static void vm_unlock_mapping(struct address_space *mapping)
  2876. {
  2877. if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
  2878. /*
  2879. * AS_MM_ALL_LOCKS can't change to 0 from under us
  2880. * because we hold the mm_all_locks_mutex.
  2881. */
  2882. i_mmap_unlock_write(mapping);
  2883. if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
  2884. &mapping->flags))
  2885. BUG();
  2886. }
  2887. }
  2888. /*
  2889. * The mmap_sem cannot be released by the caller until
  2890. * mm_drop_all_locks() returns.
  2891. */
  2892. void mm_drop_all_locks(struct mm_struct *mm)
  2893. {
  2894. struct vm_area_struct *vma;
  2895. struct anon_vma_chain *avc;
  2896. BUG_ON(down_read_trylock(&mm->mmap_sem));
  2897. BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
  2898. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  2899. if (vma->anon_vma)
  2900. list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
  2901. vm_unlock_anon_vma(avc->anon_vma);
  2902. if (vma->vm_file && vma->vm_file->f_mapping)
  2903. vm_unlock_mapping(vma->vm_file->f_mapping);
  2904. }
  2905. mutex_unlock(&mm_all_locks_mutex);
  2906. }
  2907. /*
  2908. * initialise the VMA slab
  2909. */
  2910. void __init mmap_init(void)
  2911. {
  2912. int ret;
  2913. ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
  2914. VM_BUG_ON(ret);
  2915. }
  2916. /*
  2917. * Initialise sysctl_user_reserve_kbytes.
  2918. *
  2919. * This is intended to prevent a user from starting a single memory hogging
  2920. * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
  2921. * mode.
  2922. *
  2923. * The default value is min(3% of free memory, 128MB)
  2924. * 128MB is enough to recover with sshd/login, bash, and top/kill.
  2925. */
  2926. static int init_user_reserve(void)
  2927. {
  2928. unsigned long free_kbytes;
  2929. free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  2930. sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
  2931. return 0;
  2932. }
  2933. subsys_initcall(init_user_reserve);
  2934. /*
  2935. * Initialise sysctl_admin_reserve_kbytes.
  2936. *
  2937. * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
  2938. * to log in and kill a memory hogging process.
  2939. *
  2940. * Systems with more than 256MB will reserve 8MB, enough to recover
  2941. * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
  2942. * only reserve 3% of free pages by default.
  2943. */
  2944. static int init_admin_reserve(void)
  2945. {
  2946. unsigned long free_kbytes;
  2947. free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  2948. sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
  2949. return 0;
  2950. }
  2951. subsys_initcall(init_admin_reserve);
  2952. /*
  2953. * Reinititalise user and admin reserves if memory is added or removed.
  2954. *
  2955. * The default user reserve max is 128MB, and the default max for the
  2956. * admin reserve is 8MB. These are usually, but not always, enough to
  2957. * enable recovery from a memory hogging process using login/sshd, a shell,
  2958. * and tools like top. It may make sense to increase or even disable the
  2959. * reserve depending on the existence of swap or variations in the recovery
  2960. * tools. So, the admin may have changed them.
  2961. *
  2962. * If memory is added and the reserves have been eliminated or increased above
  2963. * the default max, then we'll trust the admin.
  2964. *
  2965. * If memory is removed and there isn't enough free memory, then we
  2966. * need to reset the reserves.
  2967. *
  2968. * Otherwise keep the reserve set by the admin.
  2969. */
  2970. static int reserve_mem_notifier(struct notifier_block *nb,
  2971. unsigned long action, void *data)
  2972. {
  2973. unsigned long tmp, free_kbytes;
  2974. switch (action) {
  2975. case MEM_ONLINE:
  2976. /* Default max is 128MB. Leave alone if modified by operator. */
  2977. tmp = sysctl_user_reserve_kbytes;
  2978. if (0 < tmp && tmp < (1UL << 17))
  2979. init_user_reserve();
  2980. /* Default max is 8MB. Leave alone if modified by operator. */
  2981. tmp = sysctl_admin_reserve_kbytes;
  2982. if (0 < tmp && tmp < (1UL << 13))
  2983. init_admin_reserve();
  2984. break;
  2985. case MEM_OFFLINE:
  2986. free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
  2987. if (sysctl_user_reserve_kbytes > free_kbytes) {
  2988. init_user_reserve();
  2989. pr_info("vm.user_reserve_kbytes reset to %lu\n",
  2990. sysctl_user_reserve_kbytes);
  2991. }
  2992. if (sysctl_admin_reserve_kbytes > free_kbytes) {
  2993. init_admin_reserve();
  2994. pr_info("vm.admin_reserve_kbytes reset to %lu\n",
  2995. sysctl_admin_reserve_kbytes);
  2996. }
  2997. break;
  2998. default:
  2999. break;
  3000. }
  3001. return NOTIFY_OK;
  3002. }
  3003. static struct notifier_block reserve_mem_nb = {
  3004. .notifier_call = reserve_mem_notifier,
  3005. };
  3006. static int __meminit init_reserve_notifier(void)
  3007. {
  3008. if (register_hotmemory_notifier(&reserve_mem_nb))
  3009. pr_err("Failed registering memory add/remove notifier for admin reserve\n");
  3010. return 0;
  3011. }
  3012. subsys_initcall(init_reserve_notifier);