mmap.c 91 KB

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