mmap.c 95 KB

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