mmap.c 90 KB

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