mmap.c 94 KB

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