mmap.c 106 KB

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