mmap.c 92 KB

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