mmap.c 90 KB

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