mmap.c 90 KB

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