vmalloc.c 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 1993 Linus Torvalds
  4. * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
  5. * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
  6. * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
  7. * Numa awareness, Christoph Lameter, SGI, June 2005
  8. * Improving global KVA allocator, Uladzislau Rezki, Sony, May 2019
  9. */
  10. #include <linux/vmalloc.h>
  11. #include <linux/mm.h>
  12. #include <linux/module.h>
  13. #include <linux/highmem.h>
  14. #include <linux/sched/signal.h>
  15. #include <linux/slab.h>
  16. #include <linux/spinlock.h>
  17. #include <linux/interrupt.h>
  18. #include <linux/proc_fs.h>
  19. #include <linux/seq_file.h>
  20. #include <linux/set_memory.h>
  21. #include <linux/debugobjects.h>
  22. #include <linux/kallsyms.h>
  23. #include <linux/list.h>
  24. #include <linux/notifier.h>
  25. #include <linux/rbtree.h>
  26. #include <linux/xarray.h>
  27. #include <linux/io.h>
  28. #include <linux/rcupdate.h>
  29. #include <linux/pfn.h>
  30. #include <linux/kmemleak.h>
  31. #include <linux/atomic.h>
  32. #include <linux/compiler.h>
  33. #include <linux/memcontrol.h>
  34. #include <linux/llist.h>
  35. #include <linux/uio.h>
  36. #include <linux/bitops.h>
  37. #include <linux/rbtree_augmented.h>
  38. #include <linux/overflow.h>
  39. #include <linux/pgtable.h>
  40. #include <linux/hugetlb.h>
  41. #include <linux/sched/mm.h>
  42. #include <asm/tlbflush.h>
  43. #include <asm/shmparam.h>
  44. #include <linux/page_owner.h>
  45. #define CREATE_TRACE_POINTS
  46. #include <trace/events/vmalloc.h>
  47. #include "internal.h"
  48. #include "pgalloc-track.h"
  49. #ifdef CONFIG_HAVE_ARCH_HUGE_VMAP
  50. static unsigned int __ro_after_init ioremap_max_page_shift = BITS_PER_LONG - 1;
  51. static int __init set_nohugeiomap(char *str)
  52. {
  53. ioremap_max_page_shift = PAGE_SHIFT;
  54. return 0;
  55. }
  56. early_param("nohugeiomap", set_nohugeiomap);
  57. #else /* CONFIG_HAVE_ARCH_HUGE_VMAP */
  58. static const unsigned int ioremap_max_page_shift = PAGE_SHIFT;
  59. #endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */
  60. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  61. static bool __ro_after_init vmap_allow_huge = true;
  62. static int __init set_nohugevmalloc(char *str)
  63. {
  64. vmap_allow_huge = false;
  65. return 0;
  66. }
  67. early_param("nohugevmalloc", set_nohugevmalloc);
  68. #else /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
  69. static const bool vmap_allow_huge = false;
  70. #endif /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
  71. bool is_vmalloc_addr(const void *x)
  72. {
  73. unsigned long addr = (unsigned long)kasan_reset_tag(x);
  74. return addr >= VMALLOC_START && addr < VMALLOC_END;
  75. }
  76. EXPORT_SYMBOL(is_vmalloc_addr);
  77. struct vfree_deferred {
  78. struct llist_head list;
  79. struct work_struct wq;
  80. };
  81. static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
  82. /*** Page table manipulation functions ***/
  83. static int vmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
  84. phys_addr_t phys_addr, pgprot_t prot,
  85. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  86. {
  87. pte_t *pte;
  88. u64 pfn;
  89. struct page *page;
  90. unsigned long size = PAGE_SIZE;
  91. pfn = phys_addr >> PAGE_SHIFT;
  92. pte = pte_alloc_kernel_track(pmd, addr, mask);
  93. if (!pte)
  94. return -ENOMEM;
  95. do {
  96. if (unlikely(!pte_none(ptep_get(pte)))) {
  97. if (pfn_valid(pfn)) {
  98. page = pfn_to_page(pfn);
  99. dump_page(page, "remapping already mapped page");
  100. }
  101. BUG();
  102. }
  103. #ifdef CONFIG_HUGETLB_PAGE
  104. size = arch_vmap_pte_range_map_size(addr, end, pfn, max_page_shift);
  105. if (size != PAGE_SIZE) {
  106. pte_t entry = pfn_pte(pfn, prot);
  107. entry = arch_make_huge_pte(entry, ilog2(size), 0);
  108. set_huge_pte_at(&init_mm, addr, pte, entry, size);
  109. pfn += PFN_DOWN(size);
  110. continue;
  111. }
  112. #endif
  113. set_pte_at(&init_mm, addr, pte, pfn_pte(pfn, prot));
  114. pfn++;
  115. } while (pte += PFN_DOWN(size), addr += size, addr != end);
  116. *mask |= PGTBL_PTE_MODIFIED;
  117. return 0;
  118. }
  119. static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end,
  120. phys_addr_t phys_addr, pgprot_t prot,
  121. unsigned int max_page_shift)
  122. {
  123. if (max_page_shift < PMD_SHIFT)
  124. return 0;
  125. if (!arch_vmap_pmd_supported(prot))
  126. return 0;
  127. if ((end - addr) != PMD_SIZE)
  128. return 0;
  129. if (!IS_ALIGNED(addr, PMD_SIZE))
  130. return 0;
  131. if (!IS_ALIGNED(phys_addr, PMD_SIZE))
  132. return 0;
  133. if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr))
  134. return 0;
  135. return pmd_set_huge(pmd, phys_addr, prot);
  136. }
  137. static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
  138. phys_addr_t phys_addr, pgprot_t prot,
  139. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  140. {
  141. pmd_t *pmd;
  142. unsigned long next;
  143. pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
  144. if (!pmd)
  145. return -ENOMEM;
  146. do {
  147. next = pmd_addr_end(addr, end);
  148. if (vmap_try_huge_pmd(pmd, addr, next, phys_addr, prot,
  149. max_page_shift)) {
  150. *mask |= PGTBL_PMD_MODIFIED;
  151. continue;
  152. }
  153. if (vmap_pte_range(pmd, addr, next, phys_addr, prot, max_page_shift, mask))
  154. return -ENOMEM;
  155. } while (pmd++, phys_addr += (next - addr), addr = next, addr != end);
  156. return 0;
  157. }
  158. static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end,
  159. phys_addr_t phys_addr, pgprot_t prot,
  160. unsigned int max_page_shift)
  161. {
  162. if (max_page_shift < PUD_SHIFT)
  163. return 0;
  164. if (!arch_vmap_pud_supported(prot))
  165. return 0;
  166. if ((end - addr) != PUD_SIZE)
  167. return 0;
  168. if (!IS_ALIGNED(addr, PUD_SIZE))
  169. return 0;
  170. if (!IS_ALIGNED(phys_addr, PUD_SIZE))
  171. return 0;
  172. if (pud_present(*pud) && !pud_free_pmd_page(pud, addr))
  173. return 0;
  174. return pud_set_huge(pud, phys_addr, prot);
  175. }
  176. static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  177. phys_addr_t phys_addr, pgprot_t prot,
  178. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  179. {
  180. pud_t *pud;
  181. unsigned long next;
  182. pud = pud_alloc_track(&init_mm, p4d, addr, mask);
  183. if (!pud)
  184. return -ENOMEM;
  185. do {
  186. next = pud_addr_end(addr, end);
  187. if (vmap_try_huge_pud(pud, addr, next, phys_addr, prot,
  188. max_page_shift)) {
  189. *mask |= PGTBL_PUD_MODIFIED;
  190. continue;
  191. }
  192. if (vmap_pmd_range(pud, addr, next, phys_addr, prot,
  193. max_page_shift, mask))
  194. return -ENOMEM;
  195. } while (pud++, phys_addr += (next - addr), addr = next, addr != end);
  196. return 0;
  197. }
  198. static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end,
  199. phys_addr_t phys_addr, pgprot_t prot,
  200. unsigned int max_page_shift)
  201. {
  202. if (max_page_shift < P4D_SHIFT)
  203. return 0;
  204. if (!arch_vmap_p4d_supported(prot))
  205. return 0;
  206. if ((end - addr) != P4D_SIZE)
  207. return 0;
  208. if (!IS_ALIGNED(addr, P4D_SIZE))
  209. return 0;
  210. if (!IS_ALIGNED(phys_addr, P4D_SIZE))
  211. return 0;
  212. if (p4d_present(*p4d) && !p4d_free_pud_page(p4d, addr))
  213. return 0;
  214. return p4d_set_huge(p4d, phys_addr, prot);
  215. }
  216. static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
  217. phys_addr_t phys_addr, pgprot_t prot,
  218. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  219. {
  220. p4d_t *p4d;
  221. unsigned long next;
  222. p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
  223. if (!p4d)
  224. return -ENOMEM;
  225. do {
  226. next = p4d_addr_end(addr, end);
  227. if (vmap_try_huge_p4d(p4d, addr, next, phys_addr, prot,
  228. max_page_shift)) {
  229. *mask |= PGTBL_P4D_MODIFIED;
  230. continue;
  231. }
  232. if (vmap_pud_range(p4d, addr, next, phys_addr, prot,
  233. max_page_shift, mask))
  234. return -ENOMEM;
  235. } while (p4d++, phys_addr += (next - addr), addr = next, addr != end);
  236. return 0;
  237. }
  238. static int vmap_range_noflush(unsigned long addr, unsigned long end,
  239. phys_addr_t phys_addr, pgprot_t prot,
  240. unsigned int max_page_shift)
  241. {
  242. pgd_t *pgd;
  243. unsigned long start;
  244. unsigned long next;
  245. int err;
  246. pgtbl_mod_mask mask = 0;
  247. might_sleep();
  248. BUG_ON(addr >= end);
  249. start = addr;
  250. pgd = pgd_offset_k(addr);
  251. do {
  252. next = pgd_addr_end(addr, end);
  253. err = vmap_p4d_range(pgd, addr, next, phys_addr, prot,
  254. max_page_shift, &mask);
  255. if (err)
  256. break;
  257. } while (pgd++, phys_addr += (next - addr), addr = next, addr != end);
  258. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  259. arch_sync_kernel_mappings(start, end);
  260. return err;
  261. }
  262. int vmap_page_range(unsigned long addr, unsigned long end,
  263. phys_addr_t phys_addr, pgprot_t prot)
  264. {
  265. int err;
  266. err = vmap_range_noflush(addr, end, phys_addr, pgprot_nx(prot),
  267. ioremap_max_page_shift);
  268. flush_cache_vmap(addr, end);
  269. if (!err)
  270. err = kmsan_ioremap_page_range(addr, end, phys_addr, prot,
  271. ioremap_max_page_shift);
  272. return err;
  273. }
  274. int ioremap_page_range(unsigned long addr, unsigned long end,
  275. phys_addr_t phys_addr, pgprot_t prot)
  276. {
  277. struct vm_struct *area;
  278. area = find_vm_area((void *)addr);
  279. if (!area || !(area->flags & VM_IOREMAP)) {
  280. WARN_ONCE(1, "vm_area at addr %lx is not marked as VM_IOREMAP\n", addr);
  281. return -EINVAL;
  282. }
  283. if (addr != (unsigned long)area->addr ||
  284. (void *)end != area->addr + get_vm_area_size(area)) {
  285. WARN_ONCE(1, "ioremap request [%lx,%lx) doesn't match vm_area [%lx, %lx)\n",
  286. addr, end, (long)area->addr,
  287. (long)area->addr + get_vm_area_size(area));
  288. return -ERANGE;
  289. }
  290. return vmap_page_range(addr, end, phys_addr, prot);
  291. }
  292. static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
  293. pgtbl_mod_mask *mask)
  294. {
  295. pte_t *pte;
  296. pte = pte_offset_kernel(pmd, addr);
  297. do {
  298. pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
  299. WARN_ON(!pte_none(ptent) && !pte_present(ptent));
  300. } while (pte++, addr += PAGE_SIZE, addr != end);
  301. *mask |= PGTBL_PTE_MODIFIED;
  302. }
  303. static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
  304. pgtbl_mod_mask *mask)
  305. {
  306. pmd_t *pmd;
  307. unsigned long next;
  308. int cleared;
  309. pmd = pmd_offset(pud, addr);
  310. do {
  311. next = pmd_addr_end(addr, end);
  312. cleared = pmd_clear_huge(pmd);
  313. if (cleared || pmd_bad(*pmd))
  314. *mask |= PGTBL_PMD_MODIFIED;
  315. if (cleared)
  316. continue;
  317. if (pmd_none_or_clear_bad(pmd))
  318. continue;
  319. vunmap_pte_range(pmd, addr, next, mask);
  320. cond_resched();
  321. } while (pmd++, addr = next, addr != end);
  322. }
  323. static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  324. pgtbl_mod_mask *mask)
  325. {
  326. pud_t *pud;
  327. unsigned long next;
  328. int cleared;
  329. pud = pud_offset(p4d, addr);
  330. do {
  331. next = pud_addr_end(addr, end);
  332. cleared = pud_clear_huge(pud);
  333. if (cleared || pud_bad(*pud))
  334. *mask |= PGTBL_PUD_MODIFIED;
  335. if (cleared)
  336. continue;
  337. if (pud_none_or_clear_bad(pud))
  338. continue;
  339. vunmap_pmd_range(pud, addr, next, mask);
  340. } while (pud++, addr = next, addr != end);
  341. }
  342. static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
  343. pgtbl_mod_mask *mask)
  344. {
  345. p4d_t *p4d;
  346. unsigned long next;
  347. p4d = p4d_offset(pgd, addr);
  348. do {
  349. next = p4d_addr_end(addr, end);
  350. p4d_clear_huge(p4d);
  351. if (p4d_bad(*p4d))
  352. *mask |= PGTBL_P4D_MODIFIED;
  353. if (p4d_none_or_clear_bad(p4d))
  354. continue;
  355. vunmap_pud_range(p4d, addr, next, mask);
  356. } while (p4d++, addr = next, addr != end);
  357. }
  358. /*
  359. * vunmap_range_noflush is similar to vunmap_range, but does not
  360. * flush caches or TLBs.
  361. *
  362. * The caller is responsible for calling flush_cache_vmap() before calling
  363. * this function, and flush_tlb_kernel_range after it has returned
  364. * successfully (and before the addresses are expected to cause a page fault
  365. * or be re-mapped for something else, if TLB flushes are being delayed or
  366. * coalesced).
  367. *
  368. * This is an internal function only. Do not use outside mm/.
  369. */
  370. void __vunmap_range_noflush(unsigned long start, unsigned long end)
  371. {
  372. unsigned long next;
  373. pgd_t *pgd;
  374. unsigned long addr = start;
  375. pgtbl_mod_mask mask = 0;
  376. BUG_ON(addr >= end);
  377. pgd = pgd_offset_k(addr);
  378. do {
  379. next = pgd_addr_end(addr, end);
  380. if (pgd_bad(*pgd))
  381. mask |= PGTBL_PGD_MODIFIED;
  382. if (pgd_none_or_clear_bad(pgd))
  383. continue;
  384. vunmap_p4d_range(pgd, addr, next, &mask);
  385. } while (pgd++, addr = next, addr != end);
  386. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  387. arch_sync_kernel_mappings(start, end);
  388. }
  389. void vunmap_range_noflush(unsigned long start, unsigned long end)
  390. {
  391. kmsan_vunmap_range_noflush(start, end);
  392. __vunmap_range_noflush(start, end);
  393. }
  394. /**
  395. * vunmap_range - unmap kernel virtual addresses
  396. * @addr: start of the VM area to unmap
  397. * @end: end of the VM area to unmap (non-inclusive)
  398. *
  399. * Clears any present PTEs in the virtual address range, flushes TLBs and
  400. * caches. Any subsequent access to the address before it has been re-mapped
  401. * is a kernel bug.
  402. */
  403. void vunmap_range(unsigned long addr, unsigned long end)
  404. {
  405. flush_cache_vunmap(addr, end);
  406. vunmap_range_noflush(addr, end);
  407. flush_tlb_kernel_range(addr, end);
  408. }
  409. static int vmap_pages_pte_range(pmd_t *pmd, unsigned long addr,
  410. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  411. pgtbl_mod_mask *mask)
  412. {
  413. int err = 0;
  414. pte_t *pte;
  415. /*
  416. * nr is a running index into the array which helps higher level
  417. * callers keep track of where we're up to.
  418. */
  419. pte = pte_alloc_kernel_track(pmd, addr, mask);
  420. if (!pte)
  421. return -ENOMEM;
  422. do {
  423. struct page *page = pages[*nr];
  424. if (WARN_ON(!pte_none(ptep_get(pte)))) {
  425. err = -EBUSY;
  426. break;
  427. }
  428. if (WARN_ON(!page)) {
  429. err = -ENOMEM;
  430. break;
  431. }
  432. if (WARN_ON(!pfn_valid(page_to_pfn(page)))) {
  433. err = -EINVAL;
  434. break;
  435. }
  436. set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
  437. (*nr)++;
  438. } while (pte++, addr += PAGE_SIZE, addr != end);
  439. *mask |= PGTBL_PTE_MODIFIED;
  440. return err;
  441. }
  442. static int vmap_pages_pmd_range(pud_t *pud, unsigned long addr,
  443. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  444. pgtbl_mod_mask *mask)
  445. {
  446. pmd_t *pmd;
  447. unsigned long next;
  448. pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
  449. if (!pmd)
  450. return -ENOMEM;
  451. do {
  452. next = pmd_addr_end(addr, end);
  453. if (vmap_pages_pte_range(pmd, addr, next, prot, pages, nr, mask))
  454. return -ENOMEM;
  455. } while (pmd++, addr = next, addr != end);
  456. return 0;
  457. }
  458. static int vmap_pages_pud_range(p4d_t *p4d, unsigned long addr,
  459. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  460. pgtbl_mod_mask *mask)
  461. {
  462. pud_t *pud;
  463. unsigned long next;
  464. pud = pud_alloc_track(&init_mm, p4d, addr, mask);
  465. if (!pud)
  466. return -ENOMEM;
  467. do {
  468. next = pud_addr_end(addr, end);
  469. if (vmap_pages_pmd_range(pud, addr, next, prot, pages, nr, mask))
  470. return -ENOMEM;
  471. } while (pud++, addr = next, addr != end);
  472. return 0;
  473. }
  474. static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr,
  475. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  476. pgtbl_mod_mask *mask)
  477. {
  478. p4d_t *p4d;
  479. unsigned long next;
  480. p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
  481. if (!p4d)
  482. return -ENOMEM;
  483. do {
  484. next = p4d_addr_end(addr, end);
  485. if (vmap_pages_pud_range(p4d, addr, next, prot, pages, nr, mask))
  486. return -ENOMEM;
  487. } while (p4d++, addr = next, addr != end);
  488. return 0;
  489. }
  490. static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end,
  491. pgprot_t prot, struct page **pages)
  492. {
  493. unsigned long start = addr;
  494. pgd_t *pgd;
  495. unsigned long next;
  496. int err = 0;
  497. int nr = 0;
  498. pgtbl_mod_mask mask = 0;
  499. BUG_ON(addr >= end);
  500. pgd = pgd_offset_k(addr);
  501. do {
  502. next = pgd_addr_end(addr, end);
  503. if (pgd_bad(*pgd))
  504. mask |= PGTBL_PGD_MODIFIED;
  505. err = vmap_pages_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
  506. if (err)
  507. break;
  508. } while (pgd++, addr = next, addr != end);
  509. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  510. arch_sync_kernel_mappings(start, end);
  511. return err;
  512. }
  513. /*
  514. * vmap_pages_range_noflush is similar to vmap_pages_range, but does not
  515. * flush caches.
  516. *
  517. * The caller is responsible for calling flush_cache_vmap() after this
  518. * function returns successfully and before the addresses are accessed.
  519. *
  520. * This is an internal function only. Do not use outside mm/.
  521. */
  522. int __vmap_pages_range_noflush(unsigned long addr, unsigned long end,
  523. pgprot_t prot, struct page **pages, unsigned int page_shift)
  524. {
  525. unsigned int i, nr = (end - addr) >> PAGE_SHIFT;
  526. WARN_ON(page_shift < PAGE_SHIFT);
  527. if (!IS_ENABLED(CONFIG_HAVE_ARCH_HUGE_VMALLOC) ||
  528. page_shift == PAGE_SHIFT)
  529. return vmap_small_pages_range_noflush(addr, end, prot, pages);
  530. for (i = 0; i < nr; i += 1U << (page_shift - PAGE_SHIFT)) {
  531. int err;
  532. err = vmap_range_noflush(addr, addr + (1UL << page_shift),
  533. page_to_phys(pages[i]), prot,
  534. page_shift);
  535. if (err)
  536. return err;
  537. addr += 1UL << page_shift;
  538. }
  539. return 0;
  540. }
  541. int vmap_pages_range_noflush(unsigned long addr, unsigned long end,
  542. pgprot_t prot, struct page **pages, unsigned int page_shift)
  543. {
  544. int ret = kmsan_vmap_pages_range_noflush(addr, end, prot, pages,
  545. page_shift);
  546. if (ret)
  547. return ret;
  548. return __vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
  549. }
  550. /**
  551. * vmap_pages_range - map pages to a kernel virtual address
  552. * @addr: start of the VM area to map
  553. * @end: end of the VM area to map (non-inclusive)
  554. * @prot: page protection flags to use
  555. * @pages: pages to map (always PAGE_SIZE pages)
  556. * @page_shift: maximum shift that the pages may be mapped with, @pages must
  557. * be aligned and contiguous up to at least this shift.
  558. *
  559. * RETURNS:
  560. * 0 on success, -errno on failure.
  561. */
  562. static int vmap_pages_range(unsigned long addr, unsigned long end,
  563. pgprot_t prot, struct page **pages, unsigned int page_shift)
  564. {
  565. int err;
  566. err = vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
  567. flush_cache_vmap(addr, end);
  568. return err;
  569. }
  570. static int check_sparse_vm_area(struct vm_struct *area, unsigned long start,
  571. unsigned long end)
  572. {
  573. might_sleep();
  574. if (WARN_ON_ONCE(area->flags & VM_FLUSH_RESET_PERMS))
  575. return -EINVAL;
  576. if (WARN_ON_ONCE(area->flags & VM_NO_GUARD))
  577. return -EINVAL;
  578. if (WARN_ON_ONCE(!(area->flags & VM_SPARSE)))
  579. return -EINVAL;
  580. if ((end - start) >> PAGE_SHIFT > totalram_pages())
  581. return -E2BIG;
  582. if (start < (unsigned long)area->addr ||
  583. (void *)end > area->addr + get_vm_area_size(area))
  584. return -ERANGE;
  585. return 0;
  586. }
  587. /**
  588. * vm_area_map_pages - map pages inside given sparse vm_area
  589. * @area: vm_area
  590. * @start: start address inside vm_area
  591. * @end: end address inside vm_area
  592. * @pages: pages to map (always PAGE_SIZE pages)
  593. */
  594. int vm_area_map_pages(struct vm_struct *area, unsigned long start,
  595. unsigned long end, struct page **pages)
  596. {
  597. int err;
  598. err = check_sparse_vm_area(area, start, end);
  599. if (err)
  600. return err;
  601. return vmap_pages_range(start, end, PAGE_KERNEL, pages, PAGE_SHIFT);
  602. }
  603. /**
  604. * vm_area_unmap_pages - unmap pages inside given sparse vm_area
  605. * @area: vm_area
  606. * @start: start address inside vm_area
  607. * @end: end address inside vm_area
  608. */
  609. void vm_area_unmap_pages(struct vm_struct *area, unsigned long start,
  610. unsigned long end)
  611. {
  612. if (check_sparse_vm_area(area, start, end))
  613. return;
  614. vunmap_range(start, end);
  615. }
  616. int is_vmalloc_or_module_addr(const void *x)
  617. {
  618. /*
  619. * ARM, x86-64 and sparc64 put modules in a special place,
  620. * and fall back on vmalloc() if that fails. Others
  621. * just put it in the vmalloc space.
  622. */
  623. #if defined(CONFIG_EXECMEM) && defined(MODULES_VADDR)
  624. unsigned long addr = (unsigned long)kasan_reset_tag(x);
  625. if (addr >= MODULES_VADDR && addr < MODULES_END)
  626. return 1;
  627. #endif
  628. return is_vmalloc_addr(x);
  629. }
  630. EXPORT_SYMBOL_GPL(is_vmalloc_or_module_addr);
  631. /*
  632. * Walk a vmap address to the struct page it maps. Huge vmap mappings will
  633. * return the tail page that corresponds to the base page address, which
  634. * matches small vmap mappings.
  635. */
  636. struct page *vmalloc_to_page(const void *vmalloc_addr)
  637. {
  638. unsigned long addr = (unsigned long) vmalloc_addr;
  639. struct page *page = NULL;
  640. pgd_t *pgd = pgd_offset_k(addr);
  641. p4d_t *p4d;
  642. pud_t *pud;
  643. pmd_t *pmd;
  644. pte_t *ptep, pte;
  645. /*
  646. * XXX we might need to change this if we add VIRTUAL_BUG_ON for
  647. * architectures that do not vmalloc module space
  648. */
  649. VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
  650. if (pgd_none(*pgd))
  651. return NULL;
  652. if (WARN_ON_ONCE(pgd_leaf(*pgd)))
  653. return NULL; /* XXX: no allowance for huge pgd */
  654. if (WARN_ON_ONCE(pgd_bad(*pgd)))
  655. return NULL;
  656. p4d = p4d_offset(pgd, addr);
  657. if (p4d_none(*p4d))
  658. return NULL;
  659. if (p4d_leaf(*p4d))
  660. return p4d_page(*p4d) + ((addr & ~P4D_MASK) >> PAGE_SHIFT);
  661. if (WARN_ON_ONCE(p4d_bad(*p4d)))
  662. return NULL;
  663. pud = pud_offset(p4d, addr);
  664. if (pud_none(*pud))
  665. return NULL;
  666. if (pud_leaf(*pud))
  667. return pud_page(*pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
  668. if (WARN_ON_ONCE(pud_bad(*pud)))
  669. return NULL;
  670. pmd = pmd_offset(pud, addr);
  671. if (pmd_none(*pmd))
  672. return NULL;
  673. if (pmd_leaf(*pmd))
  674. return pmd_page(*pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
  675. if (WARN_ON_ONCE(pmd_bad(*pmd)))
  676. return NULL;
  677. ptep = pte_offset_kernel(pmd, addr);
  678. pte = ptep_get(ptep);
  679. if (pte_present(pte))
  680. page = pte_page(pte);
  681. return page;
  682. }
  683. EXPORT_SYMBOL(vmalloc_to_page);
  684. /*
  685. * Map a vmalloc()-space virtual address to the physical page frame number.
  686. */
  687. unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
  688. {
  689. return page_to_pfn(vmalloc_to_page(vmalloc_addr));
  690. }
  691. EXPORT_SYMBOL(vmalloc_to_pfn);
  692. /*** Global kva allocator ***/
  693. #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
  694. #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
  695. static DEFINE_SPINLOCK(free_vmap_area_lock);
  696. static bool vmap_initialized __read_mostly;
  697. /*
  698. * This kmem_cache is used for vmap_area objects. Instead of
  699. * allocating from slab we reuse an object from this cache to
  700. * make things faster. Especially in "no edge" splitting of
  701. * free block.
  702. */
  703. static struct kmem_cache *vmap_area_cachep;
  704. /*
  705. * This linked list is used in pair with free_vmap_area_root.
  706. * It gives O(1) access to prev/next to perform fast coalescing.
  707. */
  708. static LIST_HEAD(free_vmap_area_list);
  709. /*
  710. * This augment red-black tree represents the free vmap space.
  711. * All vmap_area objects in this tree are sorted by va->va_start
  712. * address. It is used for allocation and merging when a vmap
  713. * object is released.
  714. *
  715. * Each vmap_area node contains a maximum available free block
  716. * of its sub-tree, right or left. Therefore it is possible to
  717. * find a lowest match of free area.
  718. */
  719. static struct rb_root free_vmap_area_root = RB_ROOT;
  720. /*
  721. * Preload a CPU with one object for "no edge" split case. The
  722. * aim is to get rid of allocations from the atomic context, thus
  723. * to use more permissive allocation masks.
  724. */
  725. static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
  726. /*
  727. * This structure defines a single, solid model where a list and
  728. * rb-tree are part of one entity protected by the lock. Nodes are
  729. * sorted in ascending order, thus for O(1) access to left/right
  730. * neighbors a list is used as well as for sequential traversal.
  731. */
  732. struct rb_list {
  733. struct rb_root root;
  734. struct list_head head;
  735. spinlock_t lock;
  736. };
  737. /*
  738. * A fast size storage contains VAs up to 1M size. A pool consists
  739. * of linked between each other ready to go VAs of certain sizes.
  740. * An index in the pool-array corresponds to number of pages + 1.
  741. */
  742. #define MAX_VA_SIZE_PAGES 256
  743. struct vmap_pool {
  744. struct list_head head;
  745. unsigned long len;
  746. };
  747. /*
  748. * An effective vmap-node logic. Users make use of nodes instead
  749. * of a global heap. It allows to balance an access and mitigate
  750. * contention.
  751. */
  752. static struct vmap_node {
  753. /* Simple size segregated storage. */
  754. struct vmap_pool pool[MAX_VA_SIZE_PAGES];
  755. spinlock_t pool_lock;
  756. bool skip_populate;
  757. /* Bookkeeping data of this node. */
  758. struct rb_list busy;
  759. struct rb_list lazy;
  760. /*
  761. * Ready-to-free areas.
  762. */
  763. struct list_head purge_list;
  764. struct work_struct purge_work;
  765. unsigned long nr_purged;
  766. } single;
  767. /*
  768. * Initial setup consists of one single node, i.e. a balancing
  769. * is fully disabled. Later on, after vmap is initialized these
  770. * parameters are updated based on a system capacity.
  771. */
  772. static struct vmap_node *vmap_nodes = &single;
  773. static __read_mostly unsigned int nr_vmap_nodes = 1;
  774. static __read_mostly unsigned int vmap_zone_size = 1;
  775. static inline unsigned int
  776. addr_to_node_id(unsigned long addr)
  777. {
  778. return (addr / vmap_zone_size) % nr_vmap_nodes;
  779. }
  780. static inline struct vmap_node *
  781. addr_to_node(unsigned long addr)
  782. {
  783. return &vmap_nodes[addr_to_node_id(addr)];
  784. }
  785. static inline struct vmap_node *
  786. id_to_node(unsigned int id)
  787. {
  788. return &vmap_nodes[id % nr_vmap_nodes];
  789. }
  790. /*
  791. * We use the value 0 to represent "no node", that is why
  792. * an encoded value will be the node-id incremented by 1.
  793. * It is always greater then 0. A valid node_id which can
  794. * be encoded is [0:nr_vmap_nodes - 1]. If a passed node_id
  795. * is not valid 0 is returned.
  796. */
  797. static unsigned int
  798. encode_vn_id(unsigned int node_id)
  799. {
  800. /* Can store U8_MAX [0:254] nodes. */
  801. if (node_id < nr_vmap_nodes)
  802. return (node_id + 1) << BITS_PER_BYTE;
  803. /* Warn and no node encoded. */
  804. WARN_ONCE(1, "Encode wrong node id (%u)\n", node_id);
  805. return 0;
  806. }
  807. /*
  808. * Returns an encoded node-id, the valid range is within
  809. * [0:nr_vmap_nodes-1] values. Otherwise nr_vmap_nodes is
  810. * returned if extracted data is wrong.
  811. */
  812. static unsigned int
  813. decode_vn_id(unsigned int val)
  814. {
  815. unsigned int node_id = (val >> BITS_PER_BYTE) - 1;
  816. /* Can store U8_MAX [0:254] nodes. */
  817. if (node_id < nr_vmap_nodes)
  818. return node_id;
  819. /* If it was _not_ zero, warn. */
  820. WARN_ONCE(node_id != UINT_MAX,
  821. "Decode wrong node id (%d)\n", node_id);
  822. return nr_vmap_nodes;
  823. }
  824. static bool
  825. is_vn_id_valid(unsigned int node_id)
  826. {
  827. if (node_id < nr_vmap_nodes)
  828. return true;
  829. return false;
  830. }
  831. static __always_inline unsigned long
  832. va_size(struct vmap_area *va)
  833. {
  834. return (va->va_end - va->va_start);
  835. }
  836. static __always_inline unsigned long
  837. get_subtree_max_size(struct rb_node *node)
  838. {
  839. struct vmap_area *va;
  840. va = rb_entry_safe(node, struct vmap_area, rb_node);
  841. return va ? va->subtree_max_size : 0;
  842. }
  843. RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
  844. struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
  845. static void reclaim_and_purge_vmap_areas(void);
  846. static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
  847. static void drain_vmap_area_work(struct work_struct *work);
  848. static DECLARE_WORK(drain_vmap_work, drain_vmap_area_work);
  849. static atomic_long_t nr_vmalloc_pages;
  850. unsigned long vmalloc_nr_pages(void)
  851. {
  852. return atomic_long_read(&nr_vmalloc_pages);
  853. }
  854. static struct vmap_area *__find_vmap_area(unsigned long addr, struct rb_root *root)
  855. {
  856. struct rb_node *n = root->rb_node;
  857. addr = (unsigned long)kasan_reset_tag((void *)addr);
  858. while (n) {
  859. struct vmap_area *va;
  860. va = rb_entry(n, struct vmap_area, rb_node);
  861. if (addr < va->va_start)
  862. n = n->rb_left;
  863. else if (addr >= va->va_end)
  864. n = n->rb_right;
  865. else
  866. return va;
  867. }
  868. return NULL;
  869. }
  870. /* Look up the first VA which satisfies addr < va_end, NULL if none. */
  871. static struct vmap_area *
  872. __find_vmap_area_exceed_addr(unsigned long addr, struct rb_root *root)
  873. {
  874. struct vmap_area *va = NULL;
  875. struct rb_node *n = root->rb_node;
  876. addr = (unsigned long)kasan_reset_tag((void *)addr);
  877. while (n) {
  878. struct vmap_area *tmp;
  879. tmp = rb_entry(n, struct vmap_area, rb_node);
  880. if (tmp->va_end > addr) {
  881. va = tmp;
  882. if (tmp->va_start <= addr)
  883. break;
  884. n = n->rb_left;
  885. } else
  886. n = n->rb_right;
  887. }
  888. return va;
  889. }
  890. /*
  891. * Returns a node where a first VA, that satisfies addr < va_end, resides.
  892. * If success, a node is locked. A user is responsible to unlock it when a
  893. * VA is no longer needed to be accessed.
  894. *
  895. * Returns NULL if nothing found.
  896. */
  897. static struct vmap_node *
  898. find_vmap_area_exceed_addr_lock(unsigned long addr, struct vmap_area **va)
  899. {
  900. unsigned long va_start_lowest;
  901. struct vmap_node *vn;
  902. int i;
  903. repeat:
  904. for (i = 0, va_start_lowest = 0; i < nr_vmap_nodes; i++) {
  905. vn = &vmap_nodes[i];
  906. spin_lock(&vn->busy.lock);
  907. *va = __find_vmap_area_exceed_addr(addr, &vn->busy.root);
  908. if (*va)
  909. if (!va_start_lowest || (*va)->va_start < va_start_lowest)
  910. va_start_lowest = (*va)->va_start;
  911. spin_unlock(&vn->busy.lock);
  912. }
  913. /*
  914. * Check if found VA exists, it might have gone away. In this case we
  915. * repeat the search because a VA has been removed concurrently and we
  916. * need to proceed to the next one, which is a rare case.
  917. */
  918. if (va_start_lowest) {
  919. vn = addr_to_node(va_start_lowest);
  920. spin_lock(&vn->busy.lock);
  921. *va = __find_vmap_area(va_start_lowest, &vn->busy.root);
  922. if (*va)
  923. return vn;
  924. spin_unlock(&vn->busy.lock);
  925. goto repeat;
  926. }
  927. return NULL;
  928. }
  929. /*
  930. * This function returns back addresses of parent node
  931. * and its left or right link for further processing.
  932. *
  933. * Otherwise NULL is returned. In that case all further
  934. * steps regarding inserting of conflicting overlap range
  935. * have to be declined and actually considered as a bug.
  936. */
  937. static __always_inline struct rb_node **
  938. find_va_links(struct vmap_area *va,
  939. struct rb_root *root, struct rb_node *from,
  940. struct rb_node **parent)
  941. {
  942. struct vmap_area *tmp_va;
  943. struct rb_node **link;
  944. if (root) {
  945. link = &root->rb_node;
  946. if (unlikely(!*link)) {
  947. *parent = NULL;
  948. return link;
  949. }
  950. } else {
  951. link = &from;
  952. }
  953. /*
  954. * Go to the bottom of the tree. When we hit the last point
  955. * we end up with parent rb_node and correct direction, i name
  956. * it link, where the new va->rb_node will be attached to.
  957. */
  958. do {
  959. tmp_va = rb_entry(*link, struct vmap_area, rb_node);
  960. /*
  961. * During the traversal we also do some sanity check.
  962. * Trigger the BUG() if there are sides(left/right)
  963. * or full overlaps.
  964. */
  965. if (va->va_end <= tmp_va->va_start)
  966. link = &(*link)->rb_left;
  967. else if (va->va_start >= tmp_va->va_end)
  968. link = &(*link)->rb_right;
  969. else {
  970. WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n",
  971. va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end);
  972. return NULL;
  973. }
  974. } while (*link);
  975. *parent = &tmp_va->rb_node;
  976. return link;
  977. }
  978. static __always_inline struct list_head *
  979. get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
  980. {
  981. struct list_head *list;
  982. if (unlikely(!parent))
  983. /*
  984. * The red-black tree where we try to find VA neighbors
  985. * before merging or inserting is empty, i.e. it means
  986. * there is no free vmap space. Normally it does not
  987. * happen but we handle this case anyway.
  988. */
  989. return NULL;
  990. list = &rb_entry(parent, struct vmap_area, rb_node)->list;
  991. return (&parent->rb_right == link ? list->next : list);
  992. }
  993. static __always_inline void
  994. __link_va(struct vmap_area *va, struct rb_root *root,
  995. struct rb_node *parent, struct rb_node **link,
  996. struct list_head *head, bool augment)
  997. {
  998. /*
  999. * VA is still not in the list, but we can
  1000. * identify its future previous list_head node.
  1001. */
  1002. if (likely(parent)) {
  1003. head = &rb_entry(parent, struct vmap_area, rb_node)->list;
  1004. if (&parent->rb_right != link)
  1005. head = head->prev;
  1006. }
  1007. /* Insert to the rb-tree */
  1008. rb_link_node(&va->rb_node, parent, link);
  1009. if (augment) {
  1010. /*
  1011. * Some explanation here. Just perform simple insertion
  1012. * to the tree. We do not set va->subtree_max_size to
  1013. * its current size before calling rb_insert_augmented().
  1014. * It is because we populate the tree from the bottom
  1015. * to parent levels when the node _is_ in the tree.
  1016. *
  1017. * Therefore we set subtree_max_size to zero after insertion,
  1018. * to let __augment_tree_propagate_from() puts everything to
  1019. * the correct order later on.
  1020. */
  1021. rb_insert_augmented(&va->rb_node,
  1022. root, &free_vmap_area_rb_augment_cb);
  1023. va->subtree_max_size = 0;
  1024. } else {
  1025. rb_insert_color(&va->rb_node, root);
  1026. }
  1027. /* Address-sort this list */
  1028. list_add(&va->list, head);
  1029. }
  1030. static __always_inline void
  1031. link_va(struct vmap_area *va, struct rb_root *root,
  1032. struct rb_node *parent, struct rb_node **link,
  1033. struct list_head *head)
  1034. {
  1035. __link_va(va, root, parent, link, head, false);
  1036. }
  1037. static __always_inline void
  1038. link_va_augment(struct vmap_area *va, struct rb_root *root,
  1039. struct rb_node *parent, struct rb_node **link,
  1040. struct list_head *head)
  1041. {
  1042. __link_va(va, root, parent, link, head, true);
  1043. }
  1044. static __always_inline void
  1045. __unlink_va(struct vmap_area *va, struct rb_root *root, bool augment)
  1046. {
  1047. if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
  1048. return;
  1049. if (augment)
  1050. rb_erase_augmented(&va->rb_node,
  1051. root, &free_vmap_area_rb_augment_cb);
  1052. else
  1053. rb_erase(&va->rb_node, root);
  1054. list_del_init(&va->list);
  1055. RB_CLEAR_NODE(&va->rb_node);
  1056. }
  1057. static __always_inline void
  1058. unlink_va(struct vmap_area *va, struct rb_root *root)
  1059. {
  1060. __unlink_va(va, root, false);
  1061. }
  1062. static __always_inline void
  1063. unlink_va_augment(struct vmap_area *va, struct rb_root *root)
  1064. {
  1065. __unlink_va(va, root, true);
  1066. }
  1067. #if DEBUG_AUGMENT_PROPAGATE_CHECK
  1068. /*
  1069. * Gets called when remove the node and rotate.
  1070. */
  1071. static __always_inline unsigned long
  1072. compute_subtree_max_size(struct vmap_area *va)
  1073. {
  1074. return max3(va_size(va),
  1075. get_subtree_max_size(va->rb_node.rb_left),
  1076. get_subtree_max_size(va->rb_node.rb_right));
  1077. }
  1078. static void
  1079. augment_tree_propagate_check(void)
  1080. {
  1081. struct vmap_area *va;
  1082. unsigned long computed_size;
  1083. list_for_each_entry(va, &free_vmap_area_list, list) {
  1084. computed_size = compute_subtree_max_size(va);
  1085. if (computed_size != va->subtree_max_size)
  1086. pr_emerg("tree is corrupted: %lu, %lu\n",
  1087. va_size(va), va->subtree_max_size);
  1088. }
  1089. }
  1090. #endif
  1091. /*
  1092. * This function populates subtree_max_size from bottom to upper
  1093. * levels starting from VA point. The propagation must be done
  1094. * when VA size is modified by changing its va_start/va_end. Or
  1095. * in case of newly inserting of VA to the tree.
  1096. *
  1097. * It means that __augment_tree_propagate_from() must be called:
  1098. * - After VA has been inserted to the tree(free path);
  1099. * - After VA has been shrunk(allocation path);
  1100. * - After VA has been increased(merging path).
  1101. *
  1102. * Please note that, it does not mean that upper parent nodes
  1103. * and their subtree_max_size are recalculated all the time up
  1104. * to the root node.
  1105. *
  1106. * 4--8
  1107. * /\
  1108. * / \
  1109. * / \
  1110. * 2--2 8--8
  1111. *
  1112. * For example if we modify the node 4, shrinking it to 2, then
  1113. * no any modification is required. If we shrink the node 2 to 1
  1114. * its subtree_max_size is updated only, and set to 1. If we shrink
  1115. * the node 8 to 6, then its subtree_max_size is set to 6 and parent
  1116. * node becomes 4--6.
  1117. */
  1118. static __always_inline void
  1119. augment_tree_propagate_from(struct vmap_area *va)
  1120. {
  1121. /*
  1122. * Populate the tree from bottom towards the root until
  1123. * the calculated maximum available size of checked node
  1124. * is equal to its current one.
  1125. */
  1126. free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL);
  1127. #if DEBUG_AUGMENT_PROPAGATE_CHECK
  1128. augment_tree_propagate_check();
  1129. #endif
  1130. }
  1131. static void
  1132. insert_vmap_area(struct vmap_area *va,
  1133. struct rb_root *root, struct list_head *head)
  1134. {
  1135. struct rb_node **link;
  1136. struct rb_node *parent;
  1137. link = find_va_links(va, root, NULL, &parent);
  1138. if (link)
  1139. link_va(va, root, parent, link, head);
  1140. }
  1141. static void
  1142. insert_vmap_area_augment(struct vmap_area *va,
  1143. struct rb_node *from, struct rb_root *root,
  1144. struct list_head *head)
  1145. {
  1146. struct rb_node **link;
  1147. struct rb_node *parent;
  1148. if (from)
  1149. link = find_va_links(va, NULL, from, &parent);
  1150. else
  1151. link = find_va_links(va, root, NULL, &parent);
  1152. if (link) {
  1153. link_va_augment(va, root, parent, link, head);
  1154. augment_tree_propagate_from(va);
  1155. }
  1156. }
  1157. /*
  1158. * Merge de-allocated chunk of VA memory with previous
  1159. * and next free blocks. If coalesce is not done a new
  1160. * free area is inserted. If VA has been merged, it is
  1161. * freed.
  1162. *
  1163. * Please note, it can return NULL in case of overlap
  1164. * ranges, followed by WARN() report. Despite it is a
  1165. * buggy behaviour, a system can be alive and keep
  1166. * ongoing.
  1167. */
  1168. static __always_inline struct vmap_area *
  1169. __merge_or_add_vmap_area(struct vmap_area *va,
  1170. struct rb_root *root, struct list_head *head, bool augment)
  1171. {
  1172. struct vmap_area *sibling;
  1173. struct list_head *next;
  1174. struct rb_node **link;
  1175. struct rb_node *parent;
  1176. bool merged = false;
  1177. /*
  1178. * Find a place in the tree where VA potentially will be
  1179. * inserted, unless it is merged with its sibling/siblings.
  1180. */
  1181. link = find_va_links(va, root, NULL, &parent);
  1182. if (!link)
  1183. return NULL;
  1184. /*
  1185. * Get next node of VA to check if merging can be done.
  1186. */
  1187. next = get_va_next_sibling(parent, link);
  1188. if (unlikely(next == NULL))
  1189. goto insert;
  1190. /*
  1191. * start end
  1192. * | |
  1193. * |<------VA------>|<-----Next----->|
  1194. * | |
  1195. * start end
  1196. */
  1197. if (next != head) {
  1198. sibling = list_entry(next, struct vmap_area, list);
  1199. if (sibling->va_start == va->va_end) {
  1200. sibling->va_start = va->va_start;
  1201. /* Free vmap_area object. */
  1202. kmem_cache_free(vmap_area_cachep, va);
  1203. /* Point to the new merged area. */
  1204. va = sibling;
  1205. merged = true;
  1206. }
  1207. }
  1208. /*
  1209. * start end
  1210. * | |
  1211. * |<-----Prev----->|<------VA------>|
  1212. * | |
  1213. * start end
  1214. */
  1215. if (next->prev != head) {
  1216. sibling = list_entry(next->prev, struct vmap_area, list);
  1217. if (sibling->va_end == va->va_start) {
  1218. /*
  1219. * If both neighbors are coalesced, it is important
  1220. * to unlink the "next" node first, followed by merging
  1221. * with "previous" one. Otherwise the tree might not be
  1222. * fully populated if a sibling's augmented value is
  1223. * "normalized" because of rotation operations.
  1224. */
  1225. if (merged)
  1226. __unlink_va(va, root, augment);
  1227. sibling->va_end = va->va_end;
  1228. /* Free vmap_area object. */
  1229. kmem_cache_free(vmap_area_cachep, va);
  1230. /* Point to the new merged area. */
  1231. va = sibling;
  1232. merged = true;
  1233. }
  1234. }
  1235. insert:
  1236. if (!merged)
  1237. __link_va(va, root, parent, link, head, augment);
  1238. return va;
  1239. }
  1240. static __always_inline struct vmap_area *
  1241. merge_or_add_vmap_area(struct vmap_area *va,
  1242. struct rb_root *root, struct list_head *head)
  1243. {
  1244. return __merge_or_add_vmap_area(va, root, head, false);
  1245. }
  1246. static __always_inline struct vmap_area *
  1247. merge_or_add_vmap_area_augment(struct vmap_area *va,
  1248. struct rb_root *root, struct list_head *head)
  1249. {
  1250. va = __merge_or_add_vmap_area(va, root, head, true);
  1251. if (va)
  1252. augment_tree_propagate_from(va);
  1253. return va;
  1254. }
  1255. static __always_inline bool
  1256. is_within_this_va(struct vmap_area *va, unsigned long size,
  1257. unsigned long align, unsigned long vstart)
  1258. {
  1259. unsigned long nva_start_addr;
  1260. if (va->va_start > vstart)
  1261. nva_start_addr = ALIGN(va->va_start, align);
  1262. else
  1263. nva_start_addr = ALIGN(vstart, align);
  1264. /* Can be overflowed due to big size or alignment. */
  1265. if (nva_start_addr + size < nva_start_addr ||
  1266. nva_start_addr < vstart)
  1267. return false;
  1268. return (nva_start_addr + size <= va->va_end);
  1269. }
  1270. /*
  1271. * Find the first free block(lowest start address) in the tree,
  1272. * that will accomplish the request corresponding to passing
  1273. * parameters. Please note, with an alignment bigger than PAGE_SIZE,
  1274. * a search length is adjusted to account for worst case alignment
  1275. * overhead.
  1276. */
  1277. static __always_inline struct vmap_area *
  1278. find_vmap_lowest_match(struct rb_root *root, unsigned long size,
  1279. unsigned long align, unsigned long vstart, bool adjust_search_size)
  1280. {
  1281. struct vmap_area *va;
  1282. struct rb_node *node;
  1283. unsigned long length;
  1284. /* Start from the root. */
  1285. node = root->rb_node;
  1286. /* Adjust the search size for alignment overhead. */
  1287. length = adjust_search_size ? size + align - 1 : size;
  1288. while (node) {
  1289. va = rb_entry(node, struct vmap_area, rb_node);
  1290. if (get_subtree_max_size(node->rb_left) >= length &&
  1291. vstart < va->va_start) {
  1292. node = node->rb_left;
  1293. } else {
  1294. if (is_within_this_va(va, size, align, vstart))
  1295. return va;
  1296. /*
  1297. * Does not make sense to go deeper towards the right
  1298. * sub-tree if it does not have a free block that is
  1299. * equal or bigger to the requested search length.
  1300. */
  1301. if (get_subtree_max_size(node->rb_right) >= length) {
  1302. node = node->rb_right;
  1303. continue;
  1304. }
  1305. /*
  1306. * OK. We roll back and find the first right sub-tree,
  1307. * that will satisfy the search criteria. It can happen
  1308. * due to "vstart" restriction or an alignment overhead
  1309. * that is bigger then PAGE_SIZE.
  1310. */
  1311. while ((node = rb_parent(node))) {
  1312. va = rb_entry(node, struct vmap_area, rb_node);
  1313. if (is_within_this_va(va, size, align, vstart))
  1314. return va;
  1315. if (get_subtree_max_size(node->rb_right) >= length &&
  1316. vstart <= va->va_start) {
  1317. /*
  1318. * Shift the vstart forward. Please note, we update it with
  1319. * parent's start address adding "1" because we do not want
  1320. * to enter same sub-tree after it has already been checked
  1321. * and no suitable free block found there.
  1322. */
  1323. vstart = va->va_start + 1;
  1324. node = node->rb_right;
  1325. break;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. return NULL;
  1331. }
  1332. #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
  1333. #include <linux/random.h>
  1334. static struct vmap_area *
  1335. find_vmap_lowest_linear_match(struct list_head *head, unsigned long size,
  1336. unsigned long align, unsigned long vstart)
  1337. {
  1338. struct vmap_area *va;
  1339. list_for_each_entry(va, head, list) {
  1340. if (!is_within_this_va(va, size, align, vstart))
  1341. continue;
  1342. return va;
  1343. }
  1344. return NULL;
  1345. }
  1346. static void
  1347. find_vmap_lowest_match_check(struct rb_root *root, struct list_head *head,
  1348. unsigned long size, unsigned long align)
  1349. {
  1350. struct vmap_area *va_1, *va_2;
  1351. unsigned long vstart;
  1352. unsigned int rnd;
  1353. get_random_bytes(&rnd, sizeof(rnd));
  1354. vstart = VMALLOC_START + rnd;
  1355. va_1 = find_vmap_lowest_match(root, size, align, vstart, false);
  1356. va_2 = find_vmap_lowest_linear_match(head, size, align, vstart);
  1357. if (va_1 != va_2)
  1358. pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
  1359. va_1, va_2, vstart);
  1360. }
  1361. #endif
  1362. enum fit_type {
  1363. NOTHING_FIT = 0,
  1364. FL_FIT_TYPE = 1, /* full fit */
  1365. LE_FIT_TYPE = 2, /* left edge fit */
  1366. RE_FIT_TYPE = 3, /* right edge fit */
  1367. NE_FIT_TYPE = 4 /* no edge fit */
  1368. };
  1369. static __always_inline enum fit_type
  1370. classify_va_fit_type(struct vmap_area *va,
  1371. unsigned long nva_start_addr, unsigned long size)
  1372. {
  1373. enum fit_type type;
  1374. /* Check if it is within VA. */
  1375. if (nva_start_addr < va->va_start ||
  1376. nva_start_addr + size > va->va_end)
  1377. return NOTHING_FIT;
  1378. /* Now classify. */
  1379. if (va->va_start == nva_start_addr) {
  1380. if (va->va_end == nva_start_addr + size)
  1381. type = FL_FIT_TYPE;
  1382. else
  1383. type = LE_FIT_TYPE;
  1384. } else if (va->va_end == nva_start_addr + size) {
  1385. type = RE_FIT_TYPE;
  1386. } else {
  1387. type = NE_FIT_TYPE;
  1388. }
  1389. return type;
  1390. }
  1391. static __always_inline int
  1392. va_clip(struct rb_root *root, struct list_head *head,
  1393. struct vmap_area *va, unsigned long nva_start_addr,
  1394. unsigned long size)
  1395. {
  1396. struct vmap_area *lva = NULL;
  1397. enum fit_type type = classify_va_fit_type(va, nva_start_addr, size);
  1398. if (type == FL_FIT_TYPE) {
  1399. /*
  1400. * No need to split VA, it fully fits.
  1401. *
  1402. * | |
  1403. * V NVA V
  1404. * |---------------|
  1405. */
  1406. unlink_va_augment(va, root);
  1407. kmem_cache_free(vmap_area_cachep, va);
  1408. } else if (type == LE_FIT_TYPE) {
  1409. /*
  1410. * Split left edge of fit VA.
  1411. *
  1412. * | |
  1413. * V NVA V R
  1414. * |-------|-------|
  1415. */
  1416. va->va_start += size;
  1417. } else if (type == RE_FIT_TYPE) {
  1418. /*
  1419. * Split right edge of fit VA.
  1420. *
  1421. * | |
  1422. * L V NVA V
  1423. * |-------|-------|
  1424. */
  1425. va->va_end = nva_start_addr;
  1426. } else if (type == NE_FIT_TYPE) {
  1427. /*
  1428. * Split no edge of fit VA.
  1429. *
  1430. * | |
  1431. * L V NVA V R
  1432. * |---|-------|---|
  1433. */
  1434. lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
  1435. if (unlikely(!lva)) {
  1436. /*
  1437. * For percpu allocator we do not do any pre-allocation
  1438. * and leave it as it is. The reason is it most likely
  1439. * never ends up with NE_FIT_TYPE splitting. In case of
  1440. * percpu allocations offsets and sizes are aligned to
  1441. * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
  1442. * are its main fitting cases.
  1443. *
  1444. * There are a few exceptions though, as an example it is
  1445. * a first allocation (early boot up) when we have "one"
  1446. * big free space that has to be split.
  1447. *
  1448. * Also we can hit this path in case of regular "vmap"
  1449. * allocations, if "this" current CPU was not preloaded.
  1450. * See the comment in alloc_vmap_area() why. If so, then
  1451. * GFP_NOWAIT is used instead to get an extra object for
  1452. * split purpose. That is rare and most time does not
  1453. * occur.
  1454. *
  1455. * What happens if an allocation gets failed. Basically,
  1456. * an "overflow" path is triggered to purge lazily freed
  1457. * areas to free some memory, then, the "retry" path is
  1458. * triggered to repeat one more time. See more details
  1459. * in alloc_vmap_area() function.
  1460. */
  1461. lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
  1462. if (!lva)
  1463. return -1;
  1464. }
  1465. /*
  1466. * Build the remainder.
  1467. */
  1468. lva->va_start = va->va_start;
  1469. lva->va_end = nva_start_addr;
  1470. /*
  1471. * Shrink this VA to remaining size.
  1472. */
  1473. va->va_start = nva_start_addr + size;
  1474. } else {
  1475. return -1;
  1476. }
  1477. if (type != FL_FIT_TYPE) {
  1478. augment_tree_propagate_from(va);
  1479. if (lva) /* type == NE_FIT_TYPE */
  1480. insert_vmap_area_augment(lva, &va->rb_node, root, head);
  1481. }
  1482. return 0;
  1483. }
  1484. static unsigned long
  1485. va_alloc(struct vmap_area *va,
  1486. struct rb_root *root, struct list_head *head,
  1487. unsigned long size, unsigned long align,
  1488. unsigned long vstart, unsigned long vend)
  1489. {
  1490. unsigned long nva_start_addr;
  1491. int ret;
  1492. if (va->va_start > vstart)
  1493. nva_start_addr = ALIGN(va->va_start, align);
  1494. else
  1495. nva_start_addr = ALIGN(vstart, align);
  1496. /* Check the "vend" restriction. */
  1497. if (nva_start_addr + size > vend)
  1498. return vend;
  1499. /* Update the free vmap_area. */
  1500. ret = va_clip(root, head, va, nva_start_addr, size);
  1501. if (WARN_ON_ONCE(ret))
  1502. return vend;
  1503. return nva_start_addr;
  1504. }
  1505. /*
  1506. * Returns a start address of the newly allocated area, if success.
  1507. * Otherwise a vend is returned that indicates failure.
  1508. */
  1509. static __always_inline unsigned long
  1510. __alloc_vmap_area(struct rb_root *root, struct list_head *head,
  1511. unsigned long size, unsigned long align,
  1512. unsigned long vstart, unsigned long vend)
  1513. {
  1514. bool adjust_search_size = true;
  1515. unsigned long nva_start_addr;
  1516. struct vmap_area *va;
  1517. /*
  1518. * Do not adjust when:
  1519. * a) align <= PAGE_SIZE, because it does not make any sense.
  1520. * All blocks(their start addresses) are at least PAGE_SIZE
  1521. * aligned anyway;
  1522. * b) a short range where a requested size corresponds to exactly
  1523. * specified [vstart:vend] interval and an alignment > PAGE_SIZE.
  1524. * With adjusted search length an allocation would not succeed.
  1525. */
  1526. if (align <= PAGE_SIZE || (align > PAGE_SIZE && (vend - vstart) == size))
  1527. adjust_search_size = false;
  1528. va = find_vmap_lowest_match(root, size, align, vstart, adjust_search_size);
  1529. if (unlikely(!va))
  1530. return vend;
  1531. nva_start_addr = va_alloc(va, root, head, size, align, vstart, vend);
  1532. if (nva_start_addr == vend)
  1533. return vend;
  1534. #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
  1535. find_vmap_lowest_match_check(root, head, size, align);
  1536. #endif
  1537. return nva_start_addr;
  1538. }
  1539. /*
  1540. * Free a region of KVA allocated by alloc_vmap_area
  1541. */
  1542. static void free_vmap_area(struct vmap_area *va)
  1543. {
  1544. struct vmap_node *vn = addr_to_node(va->va_start);
  1545. /*
  1546. * Remove from the busy tree/list.
  1547. */
  1548. spin_lock(&vn->busy.lock);
  1549. unlink_va(va, &vn->busy.root);
  1550. spin_unlock(&vn->busy.lock);
  1551. /*
  1552. * Insert/Merge it back to the free tree/list.
  1553. */
  1554. spin_lock(&free_vmap_area_lock);
  1555. merge_or_add_vmap_area_augment(va, &free_vmap_area_root, &free_vmap_area_list);
  1556. spin_unlock(&free_vmap_area_lock);
  1557. }
  1558. static inline void
  1559. preload_this_cpu_lock(spinlock_t *lock, gfp_t gfp_mask, int node)
  1560. {
  1561. struct vmap_area *va = NULL, *tmp;
  1562. /*
  1563. * Preload this CPU with one extra vmap_area object. It is used
  1564. * when fit type of free area is NE_FIT_TYPE. It guarantees that
  1565. * a CPU that does an allocation is preloaded.
  1566. *
  1567. * We do it in non-atomic context, thus it allows us to use more
  1568. * permissive allocation masks to be more stable under low memory
  1569. * condition and high memory pressure.
  1570. */
  1571. if (!this_cpu_read(ne_fit_preload_node))
  1572. va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
  1573. spin_lock(lock);
  1574. tmp = NULL;
  1575. if (va && !__this_cpu_try_cmpxchg(ne_fit_preload_node, &tmp, va))
  1576. kmem_cache_free(vmap_area_cachep, va);
  1577. }
  1578. static struct vmap_pool *
  1579. size_to_va_pool(struct vmap_node *vn, unsigned long size)
  1580. {
  1581. unsigned int idx = (size - 1) / PAGE_SIZE;
  1582. if (idx < MAX_VA_SIZE_PAGES)
  1583. return &vn->pool[idx];
  1584. return NULL;
  1585. }
  1586. static bool
  1587. node_pool_add_va(struct vmap_node *n, struct vmap_area *va)
  1588. {
  1589. struct vmap_pool *vp;
  1590. vp = size_to_va_pool(n, va_size(va));
  1591. if (!vp)
  1592. return false;
  1593. spin_lock(&n->pool_lock);
  1594. list_add(&va->list, &vp->head);
  1595. WRITE_ONCE(vp->len, vp->len + 1);
  1596. spin_unlock(&n->pool_lock);
  1597. return true;
  1598. }
  1599. static struct vmap_area *
  1600. node_pool_del_va(struct vmap_node *vn, unsigned long size,
  1601. unsigned long align, unsigned long vstart,
  1602. unsigned long vend)
  1603. {
  1604. struct vmap_area *va = NULL;
  1605. struct vmap_pool *vp;
  1606. int err = 0;
  1607. vp = size_to_va_pool(vn, size);
  1608. if (!vp || list_empty(&vp->head))
  1609. return NULL;
  1610. spin_lock(&vn->pool_lock);
  1611. if (!list_empty(&vp->head)) {
  1612. va = list_first_entry(&vp->head, struct vmap_area, list);
  1613. if (IS_ALIGNED(va->va_start, align)) {
  1614. /*
  1615. * Do some sanity check and emit a warning
  1616. * if one of below checks detects an error.
  1617. */
  1618. err |= (va_size(va) != size);
  1619. err |= (va->va_start < vstart);
  1620. err |= (va->va_end > vend);
  1621. if (!WARN_ON_ONCE(err)) {
  1622. list_del_init(&va->list);
  1623. WRITE_ONCE(vp->len, vp->len - 1);
  1624. } else {
  1625. va = NULL;
  1626. }
  1627. } else {
  1628. list_move_tail(&va->list, &vp->head);
  1629. va = NULL;
  1630. }
  1631. }
  1632. spin_unlock(&vn->pool_lock);
  1633. return va;
  1634. }
  1635. static struct vmap_area *
  1636. node_alloc(unsigned long size, unsigned long align,
  1637. unsigned long vstart, unsigned long vend,
  1638. unsigned long *addr, unsigned int *vn_id)
  1639. {
  1640. struct vmap_area *va;
  1641. *vn_id = 0;
  1642. *addr = vend;
  1643. /*
  1644. * Fallback to a global heap if not vmalloc or there
  1645. * is only one node.
  1646. */
  1647. if (vstart != VMALLOC_START || vend != VMALLOC_END ||
  1648. nr_vmap_nodes == 1)
  1649. return NULL;
  1650. *vn_id = raw_smp_processor_id() % nr_vmap_nodes;
  1651. va = node_pool_del_va(id_to_node(*vn_id), size, align, vstart, vend);
  1652. *vn_id = encode_vn_id(*vn_id);
  1653. if (va)
  1654. *addr = va->va_start;
  1655. return va;
  1656. }
  1657. static inline void setup_vmalloc_vm(struct vm_struct *vm,
  1658. struct vmap_area *va, unsigned long flags, const void *caller)
  1659. {
  1660. vm->flags = flags;
  1661. vm->addr = (void *)va->va_start;
  1662. vm->size = vm->requested_size = va_size(va);
  1663. vm->caller = caller;
  1664. va->vm = vm;
  1665. }
  1666. /*
  1667. * Allocate a region of KVA of the specified size and alignment, within the
  1668. * vstart and vend. If vm is passed in, the two will also be bound.
  1669. */
  1670. static struct vmap_area *alloc_vmap_area(unsigned long size,
  1671. unsigned long align,
  1672. unsigned long vstart, unsigned long vend,
  1673. int node, gfp_t gfp_mask,
  1674. unsigned long va_flags, struct vm_struct *vm)
  1675. {
  1676. struct vmap_node *vn;
  1677. struct vmap_area *va;
  1678. unsigned long freed;
  1679. unsigned long addr;
  1680. unsigned int vn_id;
  1681. int purged = 0;
  1682. int ret;
  1683. if (unlikely(!size || offset_in_page(size) || !is_power_of_2(align)))
  1684. return ERR_PTR(-EINVAL);
  1685. if (unlikely(!vmap_initialized))
  1686. return ERR_PTR(-EBUSY);
  1687. might_sleep();
  1688. /*
  1689. * If a VA is obtained from a global heap(if it fails here)
  1690. * it is anyway marked with this "vn_id" so it is returned
  1691. * to this pool's node later. Such way gives a possibility
  1692. * to populate pools based on users demand.
  1693. *
  1694. * On success a ready to go VA is returned.
  1695. */
  1696. va = node_alloc(size, align, vstart, vend, &addr, &vn_id);
  1697. if (!va) {
  1698. gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
  1699. va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
  1700. if (unlikely(!va))
  1701. return ERR_PTR(-ENOMEM);
  1702. /*
  1703. * Only scan the relevant parts containing pointers to other objects
  1704. * to avoid false negatives.
  1705. */
  1706. kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
  1707. }
  1708. retry:
  1709. if (addr == vend) {
  1710. preload_this_cpu_lock(&free_vmap_area_lock, gfp_mask, node);
  1711. addr = __alloc_vmap_area(&free_vmap_area_root, &free_vmap_area_list,
  1712. size, align, vstart, vend);
  1713. spin_unlock(&free_vmap_area_lock);
  1714. }
  1715. trace_alloc_vmap_area(addr, size, align, vstart, vend, addr == vend);
  1716. /*
  1717. * If an allocation fails, the "vend" address is
  1718. * returned. Therefore trigger the overflow path.
  1719. */
  1720. if (unlikely(addr == vend))
  1721. goto overflow;
  1722. va->va_start = addr;
  1723. va->va_end = addr + size;
  1724. va->vm = NULL;
  1725. va->flags = (va_flags | vn_id);
  1726. if (vm) {
  1727. vm->addr = (void *)va->va_start;
  1728. vm->size = va_size(va);
  1729. va->vm = vm;
  1730. }
  1731. vn = addr_to_node(va->va_start);
  1732. spin_lock(&vn->busy.lock);
  1733. insert_vmap_area(va, &vn->busy.root, &vn->busy.head);
  1734. spin_unlock(&vn->busy.lock);
  1735. BUG_ON(!IS_ALIGNED(va->va_start, align));
  1736. BUG_ON(va->va_start < vstart);
  1737. BUG_ON(va->va_end > vend);
  1738. ret = kasan_populate_vmalloc(addr, size);
  1739. if (ret) {
  1740. free_vmap_area(va);
  1741. return ERR_PTR(ret);
  1742. }
  1743. return va;
  1744. overflow:
  1745. if (!purged) {
  1746. reclaim_and_purge_vmap_areas();
  1747. purged = 1;
  1748. goto retry;
  1749. }
  1750. freed = 0;
  1751. blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
  1752. if (freed > 0) {
  1753. purged = 0;
  1754. goto retry;
  1755. }
  1756. if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
  1757. pr_warn("vmalloc_node_range for size %lu failed: Address range restricted to %#lx - %#lx\n",
  1758. size, vstart, vend);
  1759. kmem_cache_free(vmap_area_cachep, va);
  1760. return ERR_PTR(-EBUSY);
  1761. }
  1762. int register_vmap_purge_notifier(struct notifier_block *nb)
  1763. {
  1764. return blocking_notifier_chain_register(&vmap_notify_list, nb);
  1765. }
  1766. EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
  1767. int unregister_vmap_purge_notifier(struct notifier_block *nb)
  1768. {
  1769. return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
  1770. }
  1771. EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
  1772. /*
  1773. * lazy_max_pages is the maximum amount of virtual address space we gather up
  1774. * before attempting to purge with a TLB flush.
  1775. *
  1776. * There is a tradeoff here: a larger number will cover more kernel page tables
  1777. * and take slightly longer to purge, but it will linearly reduce the number of
  1778. * global TLB flushes that must be performed. It would seem natural to scale
  1779. * this number up linearly with the number of CPUs (because vmapping activity
  1780. * could also scale linearly with the number of CPUs), however it is likely
  1781. * that in practice, workloads might be constrained in other ways that mean
  1782. * vmap activity will not scale linearly with CPUs. Also, I want to be
  1783. * conservative and not introduce a big latency on huge systems, so go with
  1784. * a less aggressive log scale. It will still be an improvement over the old
  1785. * code, and it will be simple to change the scale factor if we find that it
  1786. * becomes a problem on bigger systems.
  1787. */
  1788. static unsigned long lazy_max_pages(void)
  1789. {
  1790. unsigned int log;
  1791. log = fls(num_online_cpus());
  1792. return log * (32UL * 1024 * 1024 / PAGE_SIZE);
  1793. }
  1794. static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
  1795. /*
  1796. * Serialize vmap purging. There is no actual critical section protected
  1797. * by this lock, but we want to avoid concurrent calls for performance
  1798. * reasons and to make the pcpu_get_vm_areas more deterministic.
  1799. */
  1800. static DEFINE_MUTEX(vmap_purge_lock);
  1801. /* for per-CPU blocks */
  1802. static void purge_fragmented_blocks_allcpus(void);
  1803. static cpumask_t purge_nodes;
  1804. static void
  1805. reclaim_list_global(struct list_head *head)
  1806. {
  1807. struct vmap_area *va, *n;
  1808. if (list_empty(head))
  1809. return;
  1810. spin_lock(&free_vmap_area_lock);
  1811. list_for_each_entry_safe(va, n, head, list)
  1812. merge_or_add_vmap_area_augment(va,
  1813. &free_vmap_area_root, &free_vmap_area_list);
  1814. spin_unlock(&free_vmap_area_lock);
  1815. }
  1816. static void
  1817. decay_va_pool_node(struct vmap_node *vn, bool full_decay)
  1818. {
  1819. LIST_HEAD(decay_list);
  1820. struct rb_root decay_root = RB_ROOT;
  1821. struct vmap_area *va, *nva;
  1822. unsigned long n_decay;
  1823. int i;
  1824. for (i = 0; i < MAX_VA_SIZE_PAGES; i++) {
  1825. LIST_HEAD(tmp_list);
  1826. if (list_empty(&vn->pool[i].head))
  1827. continue;
  1828. /* Detach the pool, so no-one can access it. */
  1829. spin_lock(&vn->pool_lock);
  1830. list_replace_init(&vn->pool[i].head, &tmp_list);
  1831. spin_unlock(&vn->pool_lock);
  1832. if (full_decay)
  1833. WRITE_ONCE(vn->pool[i].len, 0);
  1834. /* Decay a pool by ~25% out of left objects. */
  1835. n_decay = vn->pool[i].len >> 2;
  1836. list_for_each_entry_safe(va, nva, &tmp_list, list) {
  1837. list_del_init(&va->list);
  1838. merge_or_add_vmap_area(va, &decay_root, &decay_list);
  1839. if (!full_decay) {
  1840. WRITE_ONCE(vn->pool[i].len, vn->pool[i].len - 1);
  1841. if (!--n_decay)
  1842. break;
  1843. }
  1844. }
  1845. /*
  1846. * Attach the pool back if it has been partly decayed.
  1847. * Please note, it is supposed that nobody(other contexts)
  1848. * can populate the pool therefore a simple list replace
  1849. * operation takes place here.
  1850. */
  1851. if (!full_decay && !list_empty(&tmp_list)) {
  1852. spin_lock(&vn->pool_lock);
  1853. list_replace_init(&tmp_list, &vn->pool[i].head);
  1854. spin_unlock(&vn->pool_lock);
  1855. }
  1856. }
  1857. reclaim_list_global(&decay_list);
  1858. }
  1859. static void
  1860. kasan_release_vmalloc_node(struct vmap_node *vn)
  1861. {
  1862. struct vmap_area *va;
  1863. unsigned long start, end;
  1864. start = list_first_entry(&vn->purge_list, struct vmap_area, list)->va_start;
  1865. end = list_last_entry(&vn->purge_list, struct vmap_area, list)->va_end;
  1866. list_for_each_entry(va, &vn->purge_list, list) {
  1867. if (is_vmalloc_or_module_addr((void *) va->va_start))
  1868. kasan_release_vmalloc(va->va_start, va->va_end,
  1869. va->va_start, va->va_end,
  1870. KASAN_VMALLOC_PAGE_RANGE);
  1871. }
  1872. kasan_release_vmalloc(start, end, start, end, KASAN_VMALLOC_TLB_FLUSH);
  1873. }
  1874. static void purge_vmap_node(struct work_struct *work)
  1875. {
  1876. struct vmap_node *vn = container_of(work,
  1877. struct vmap_node, purge_work);
  1878. unsigned long nr_purged_pages = 0;
  1879. struct vmap_area *va, *n_va;
  1880. LIST_HEAD(local_list);
  1881. if (IS_ENABLED(CONFIG_KASAN_VMALLOC))
  1882. kasan_release_vmalloc_node(vn);
  1883. vn->nr_purged = 0;
  1884. list_for_each_entry_safe(va, n_va, &vn->purge_list, list) {
  1885. unsigned long nr = va_size(va) >> PAGE_SHIFT;
  1886. unsigned int vn_id = decode_vn_id(va->flags);
  1887. list_del_init(&va->list);
  1888. nr_purged_pages += nr;
  1889. vn->nr_purged++;
  1890. if (is_vn_id_valid(vn_id) && !vn->skip_populate)
  1891. if (node_pool_add_va(vn, va))
  1892. continue;
  1893. /* Go back to global. */
  1894. list_add(&va->list, &local_list);
  1895. }
  1896. atomic_long_sub(nr_purged_pages, &vmap_lazy_nr);
  1897. reclaim_list_global(&local_list);
  1898. }
  1899. /*
  1900. * Purges all lazily-freed vmap areas.
  1901. */
  1902. static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end,
  1903. bool full_pool_decay)
  1904. {
  1905. unsigned long nr_purged_areas = 0;
  1906. unsigned int nr_purge_helpers;
  1907. unsigned int nr_purge_nodes;
  1908. struct vmap_node *vn;
  1909. int i;
  1910. lockdep_assert_held(&vmap_purge_lock);
  1911. /*
  1912. * Use cpumask to mark which node has to be processed.
  1913. */
  1914. purge_nodes = CPU_MASK_NONE;
  1915. for (i = 0; i < nr_vmap_nodes; i++) {
  1916. vn = &vmap_nodes[i];
  1917. INIT_LIST_HEAD(&vn->purge_list);
  1918. vn->skip_populate = full_pool_decay;
  1919. decay_va_pool_node(vn, full_pool_decay);
  1920. if (RB_EMPTY_ROOT(&vn->lazy.root))
  1921. continue;
  1922. spin_lock(&vn->lazy.lock);
  1923. WRITE_ONCE(vn->lazy.root.rb_node, NULL);
  1924. list_replace_init(&vn->lazy.head, &vn->purge_list);
  1925. spin_unlock(&vn->lazy.lock);
  1926. start = min(start, list_first_entry(&vn->purge_list,
  1927. struct vmap_area, list)->va_start);
  1928. end = max(end, list_last_entry(&vn->purge_list,
  1929. struct vmap_area, list)->va_end);
  1930. cpumask_set_cpu(i, &purge_nodes);
  1931. }
  1932. nr_purge_nodes = cpumask_weight(&purge_nodes);
  1933. if (nr_purge_nodes > 0) {
  1934. flush_tlb_kernel_range(start, end);
  1935. /* One extra worker is per a lazy_max_pages() full set minus one. */
  1936. nr_purge_helpers = atomic_long_read(&vmap_lazy_nr) / lazy_max_pages();
  1937. nr_purge_helpers = clamp(nr_purge_helpers, 1U, nr_purge_nodes) - 1;
  1938. for_each_cpu(i, &purge_nodes) {
  1939. vn = &vmap_nodes[i];
  1940. if (nr_purge_helpers > 0) {
  1941. INIT_WORK(&vn->purge_work, purge_vmap_node);
  1942. if (cpumask_test_cpu(i, cpu_online_mask))
  1943. schedule_work_on(i, &vn->purge_work);
  1944. else
  1945. schedule_work(&vn->purge_work);
  1946. nr_purge_helpers--;
  1947. } else {
  1948. vn->purge_work.func = NULL;
  1949. purge_vmap_node(&vn->purge_work);
  1950. nr_purged_areas += vn->nr_purged;
  1951. }
  1952. }
  1953. for_each_cpu(i, &purge_nodes) {
  1954. vn = &vmap_nodes[i];
  1955. if (vn->purge_work.func) {
  1956. flush_work(&vn->purge_work);
  1957. nr_purged_areas += vn->nr_purged;
  1958. }
  1959. }
  1960. }
  1961. trace_purge_vmap_area_lazy(start, end, nr_purged_areas);
  1962. return nr_purged_areas > 0;
  1963. }
  1964. /*
  1965. * Reclaim vmap areas by purging fragmented blocks and purge_vmap_area_list.
  1966. */
  1967. static void reclaim_and_purge_vmap_areas(void)
  1968. {
  1969. mutex_lock(&vmap_purge_lock);
  1970. purge_fragmented_blocks_allcpus();
  1971. __purge_vmap_area_lazy(ULONG_MAX, 0, true);
  1972. mutex_unlock(&vmap_purge_lock);
  1973. }
  1974. static void drain_vmap_area_work(struct work_struct *work)
  1975. {
  1976. mutex_lock(&vmap_purge_lock);
  1977. __purge_vmap_area_lazy(ULONG_MAX, 0, false);
  1978. mutex_unlock(&vmap_purge_lock);
  1979. }
  1980. /*
  1981. * Free a vmap area, caller ensuring that the area has been unmapped,
  1982. * unlinked and flush_cache_vunmap had been called for the correct
  1983. * range previously.
  1984. */
  1985. static void free_vmap_area_noflush(struct vmap_area *va)
  1986. {
  1987. unsigned long nr_lazy_max = lazy_max_pages();
  1988. unsigned long va_start = va->va_start;
  1989. unsigned int vn_id = decode_vn_id(va->flags);
  1990. struct vmap_node *vn;
  1991. unsigned long nr_lazy;
  1992. if (WARN_ON_ONCE(!list_empty(&va->list)))
  1993. return;
  1994. nr_lazy = atomic_long_add_return(va_size(va) >> PAGE_SHIFT,
  1995. &vmap_lazy_nr);
  1996. /*
  1997. * If it was request by a certain node we would like to
  1998. * return it to that node, i.e. its pool for later reuse.
  1999. */
  2000. vn = is_vn_id_valid(vn_id) ?
  2001. id_to_node(vn_id):addr_to_node(va->va_start);
  2002. spin_lock(&vn->lazy.lock);
  2003. insert_vmap_area(va, &vn->lazy.root, &vn->lazy.head);
  2004. spin_unlock(&vn->lazy.lock);
  2005. trace_free_vmap_area_noflush(va_start, nr_lazy, nr_lazy_max);
  2006. /* After this point, we may free va at any time */
  2007. if (unlikely(nr_lazy > nr_lazy_max))
  2008. schedule_work(&drain_vmap_work);
  2009. }
  2010. /*
  2011. * Free and unmap a vmap area
  2012. */
  2013. static void free_unmap_vmap_area(struct vmap_area *va)
  2014. {
  2015. flush_cache_vunmap(va->va_start, va->va_end);
  2016. vunmap_range_noflush(va->va_start, va->va_end);
  2017. if (debug_pagealloc_enabled_static())
  2018. flush_tlb_kernel_range(va->va_start, va->va_end);
  2019. free_vmap_area_noflush(va);
  2020. }
  2021. struct vmap_area *find_vmap_area(unsigned long addr)
  2022. {
  2023. struct vmap_node *vn;
  2024. struct vmap_area *va;
  2025. int i, j;
  2026. if (unlikely(!vmap_initialized))
  2027. return NULL;
  2028. /*
  2029. * An addr_to_node_id(addr) converts an address to a node index
  2030. * where a VA is located. If VA spans several zones and passed
  2031. * addr is not the same as va->va_start, what is not common, we
  2032. * may need to scan extra nodes. See an example:
  2033. *
  2034. * <----va---->
  2035. * -|-----|-----|-----|-----|-
  2036. * 1 2 0 1
  2037. *
  2038. * VA resides in node 1 whereas it spans 1, 2 an 0. If passed
  2039. * addr is within 2 or 0 nodes we should do extra work.
  2040. */
  2041. i = j = addr_to_node_id(addr);
  2042. do {
  2043. vn = &vmap_nodes[i];
  2044. spin_lock(&vn->busy.lock);
  2045. va = __find_vmap_area(addr, &vn->busy.root);
  2046. spin_unlock(&vn->busy.lock);
  2047. if (va)
  2048. return va;
  2049. } while ((i = (i + 1) % nr_vmap_nodes) != j);
  2050. return NULL;
  2051. }
  2052. static struct vmap_area *find_unlink_vmap_area(unsigned long addr)
  2053. {
  2054. struct vmap_node *vn;
  2055. struct vmap_area *va;
  2056. int i, j;
  2057. /*
  2058. * Check the comment in the find_vmap_area() about the loop.
  2059. */
  2060. i = j = addr_to_node_id(addr);
  2061. do {
  2062. vn = &vmap_nodes[i];
  2063. spin_lock(&vn->busy.lock);
  2064. va = __find_vmap_area(addr, &vn->busy.root);
  2065. if (va)
  2066. unlink_va(va, &vn->busy.root);
  2067. spin_unlock(&vn->busy.lock);
  2068. if (va)
  2069. return va;
  2070. } while ((i = (i + 1) % nr_vmap_nodes) != j);
  2071. return NULL;
  2072. }
  2073. /*** Per cpu kva allocator ***/
  2074. /*
  2075. * vmap space is limited especially on 32 bit architectures. Ensure there is
  2076. * room for at least 16 percpu vmap blocks per CPU.
  2077. */
  2078. /*
  2079. * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
  2080. * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
  2081. * instead (we just need a rough idea)
  2082. */
  2083. #if BITS_PER_LONG == 32
  2084. #define VMALLOC_SPACE (128UL*1024*1024)
  2085. #else
  2086. #define VMALLOC_SPACE (128UL*1024*1024*1024)
  2087. #endif
  2088. #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
  2089. #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
  2090. #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
  2091. #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
  2092. #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
  2093. #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
  2094. #define VMAP_BBMAP_BITS \
  2095. VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
  2096. VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
  2097. VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
  2098. #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
  2099. /*
  2100. * Purge threshold to prevent overeager purging of fragmented blocks for
  2101. * regular operations: Purge if vb->free is less than 1/4 of the capacity.
  2102. */
  2103. #define VMAP_PURGE_THRESHOLD (VMAP_BBMAP_BITS / 4)
  2104. #define VMAP_RAM 0x1 /* indicates vm_map_ram area*/
  2105. #define VMAP_BLOCK 0x2 /* mark out the vmap_block sub-type*/
  2106. #define VMAP_FLAGS_MASK 0x3
  2107. struct vmap_block_queue {
  2108. spinlock_t lock;
  2109. struct list_head free;
  2110. /*
  2111. * An xarray requires an extra memory dynamically to
  2112. * be allocated. If it is an issue, we can use rb-tree
  2113. * instead.
  2114. */
  2115. struct xarray vmap_blocks;
  2116. };
  2117. struct vmap_block {
  2118. spinlock_t lock;
  2119. struct vmap_area *va;
  2120. unsigned long free, dirty;
  2121. DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS);
  2122. unsigned long dirty_min, dirty_max; /*< dirty range */
  2123. struct list_head free_list;
  2124. struct rcu_head rcu_head;
  2125. struct list_head purge;
  2126. unsigned int cpu;
  2127. };
  2128. /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
  2129. static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
  2130. /*
  2131. * In order to fast access to any "vmap_block" associated with a
  2132. * specific address, we use a hash.
  2133. *
  2134. * A per-cpu vmap_block_queue is used in both ways, to serialize
  2135. * an access to free block chains among CPUs(alloc path) and it
  2136. * also acts as a vmap_block hash(alloc/free paths). It means we
  2137. * overload it, since we already have the per-cpu array which is
  2138. * used as a hash table. When used as a hash a 'cpu' passed to
  2139. * per_cpu() is not actually a CPU but rather a hash index.
  2140. *
  2141. * A hash function is addr_to_vb_xa() which hashes any address
  2142. * to a specific index(in a hash) it belongs to. This then uses a
  2143. * per_cpu() macro to access an array with generated index.
  2144. *
  2145. * An example:
  2146. *
  2147. * CPU_1 CPU_2 CPU_0
  2148. * | | |
  2149. * V V V
  2150. * 0 10 20 30 40 50 60
  2151. * |------|------|------|------|------|------|...<vmap address space>
  2152. * CPU0 CPU1 CPU2 CPU0 CPU1 CPU2
  2153. *
  2154. * - CPU_1 invokes vm_unmap_ram(6), 6 belongs to CPU0 zone, thus
  2155. * it access: CPU0/INDEX0 -> vmap_blocks -> xa_lock;
  2156. *
  2157. * - CPU_2 invokes vm_unmap_ram(11), 11 belongs to CPU1 zone, thus
  2158. * it access: CPU1/INDEX1 -> vmap_blocks -> xa_lock;
  2159. *
  2160. * - CPU_0 invokes vm_unmap_ram(20), 20 belongs to CPU2 zone, thus
  2161. * it access: CPU2/INDEX2 -> vmap_blocks -> xa_lock.
  2162. *
  2163. * This technique almost always avoids lock contention on insert/remove,
  2164. * however xarray spinlocks protect against any contention that remains.
  2165. */
  2166. static struct xarray *
  2167. addr_to_vb_xa(unsigned long addr)
  2168. {
  2169. int index = (addr / VMAP_BLOCK_SIZE) % nr_cpu_ids;
  2170. /*
  2171. * Please note, nr_cpu_ids points on a highest set
  2172. * possible bit, i.e. we never invoke cpumask_next()
  2173. * if an index points on it which is nr_cpu_ids - 1.
  2174. */
  2175. if (!cpu_possible(index))
  2176. index = cpumask_next(index, cpu_possible_mask);
  2177. return &per_cpu(vmap_block_queue, index).vmap_blocks;
  2178. }
  2179. /*
  2180. * We should probably have a fallback mechanism to allocate virtual memory
  2181. * out of partially filled vmap blocks. However vmap block sizing should be
  2182. * fairly reasonable according to the vmalloc size, so it shouldn't be a
  2183. * big problem.
  2184. */
  2185. static unsigned long addr_to_vb_idx(unsigned long addr)
  2186. {
  2187. addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
  2188. addr /= VMAP_BLOCK_SIZE;
  2189. return addr;
  2190. }
  2191. static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
  2192. {
  2193. unsigned long addr;
  2194. addr = va_start + (pages_off << PAGE_SHIFT);
  2195. BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
  2196. return (void *)addr;
  2197. }
  2198. /**
  2199. * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
  2200. * block. Of course pages number can't exceed VMAP_BBMAP_BITS
  2201. * @order: how many 2^order pages should be occupied in newly allocated block
  2202. * @gfp_mask: flags for the page level allocator
  2203. *
  2204. * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
  2205. */
  2206. static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
  2207. {
  2208. struct vmap_block_queue *vbq;
  2209. struct vmap_block *vb;
  2210. struct vmap_area *va;
  2211. struct xarray *xa;
  2212. unsigned long vb_idx;
  2213. int node, err;
  2214. void *vaddr;
  2215. node = numa_node_id();
  2216. vb = kmalloc_node(sizeof(struct vmap_block),
  2217. gfp_mask & GFP_RECLAIM_MASK, node);
  2218. if (unlikely(!vb))
  2219. return ERR_PTR(-ENOMEM);
  2220. va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
  2221. VMALLOC_START, VMALLOC_END,
  2222. node, gfp_mask,
  2223. VMAP_RAM|VMAP_BLOCK, NULL);
  2224. if (IS_ERR(va)) {
  2225. kfree(vb);
  2226. return ERR_CAST(va);
  2227. }
  2228. vaddr = vmap_block_vaddr(va->va_start, 0);
  2229. spin_lock_init(&vb->lock);
  2230. vb->va = va;
  2231. /* At least something should be left free */
  2232. BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
  2233. bitmap_zero(vb->used_map, VMAP_BBMAP_BITS);
  2234. vb->free = VMAP_BBMAP_BITS - (1UL << order);
  2235. vb->dirty = 0;
  2236. vb->dirty_min = VMAP_BBMAP_BITS;
  2237. vb->dirty_max = 0;
  2238. bitmap_set(vb->used_map, 0, (1UL << order));
  2239. INIT_LIST_HEAD(&vb->free_list);
  2240. vb->cpu = raw_smp_processor_id();
  2241. xa = addr_to_vb_xa(va->va_start);
  2242. vb_idx = addr_to_vb_idx(va->va_start);
  2243. err = xa_insert(xa, vb_idx, vb, gfp_mask);
  2244. if (err) {
  2245. kfree(vb);
  2246. free_vmap_area(va);
  2247. return ERR_PTR(err);
  2248. }
  2249. /*
  2250. * list_add_tail_rcu could happened in another core
  2251. * rather than vb->cpu due to task migration, which
  2252. * is safe as list_add_tail_rcu will ensure the list's
  2253. * integrity together with list_for_each_rcu from read
  2254. * side.
  2255. */
  2256. vbq = per_cpu_ptr(&vmap_block_queue, vb->cpu);
  2257. spin_lock(&vbq->lock);
  2258. list_add_tail_rcu(&vb->free_list, &vbq->free);
  2259. spin_unlock(&vbq->lock);
  2260. return vaddr;
  2261. }
  2262. static void free_vmap_block(struct vmap_block *vb)
  2263. {
  2264. struct vmap_node *vn;
  2265. struct vmap_block *tmp;
  2266. struct xarray *xa;
  2267. xa = addr_to_vb_xa(vb->va->va_start);
  2268. tmp = xa_erase(xa, addr_to_vb_idx(vb->va->va_start));
  2269. BUG_ON(tmp != vb);
  2270. vn = addr_to_node(vb->va->va_start);
  2271. spin_lock(&vn->busy.lock);
  2272. unlink_va(vb->va, &vn->busy.root);
  2273. spin_unlock(&vn->busy.lock);
  2274. free_vmap_area_noflush(vb->va);
  2275. kfree_rcu(vb, rcu_head);
  2276. }
  2277. static bool purge_fragmented_block(struct vmap_block *vb,
  2278. struct list_head *purge_list, bool force_purge)
  2279. {
  2280. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, vb->cpu);
  2281. if (vb->free + vb->dirty != VMAP_BBMAP_BITS ||
  2282. vb->dirty == VMAP_BBMAP_BITS)
  2283. return false;
  2284. /* Don't overeagerly purge usable blocks unless requested */
  2285. if (!(force_purge || vb->free < VMAP_PURGE_THRESHOLD))
  2286. return false;
  2287. /* prevent further allocs after releasing lock */
  2288. WRITE_ONCE(vb->free, 0);
  2289. /* prevent purging it again */
  2290. WRITE_ONCE(vb->dirty, VMAP_BBMAP_BITS);
  2291. vb->dirty_min = 0;
  2292. vb->dirty_max = VMAP_BBMAP_BITS;
  2293. spin_lock(&vbq->lock);
  2294. list_del_rcu(&vb->free_list);
  2295. spin_unlock(&vbq->lock);
  2296. list_add_tail(&vb->purge, purge_list);
  2297. return true;
  2298. }
  2299. static void free_purged_blocks(struct list_head *purge_list)
  2300. {
  2301. struct vmap_block *vb, *n_vb;
  2302. list_for_each_entry_safe(vb, n_vb, purge_list, purge) {
  2303. list_del(&vb->purge);
  2304. free_vmap_block(vb);
  2305. }
  2306. }
  2307. static void purge_fragmented_blocks(int cpu)
  2308. {
  2309. LIST_HEAD(purge);
  2310. struct vmap_block *vb;
  2311. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
  2312. rcu_read_lock();
  2313. list_for_each_entry_rcu(vb, &vbq->free, free_list) {
  2314. unsigned long free = READ_ONCE(vb->free);
  2315. unsigned long dirty = READ_ONCE(vb->dirty);
  2316. if (free + dirty != VMAP_BBMAP_BITS ||
  2317. dirty == VMAP_BBMAP_BITS)
  2318. continue;
  2319. spin_lock(&vb->lock);
  2320. purge_fragmented_block(vb, &purge, true);
  2321. spin_unlock(&vb->lock);
  2322. }
  2323. rcu_read_unlock();
  2324. free_purged_blocks(&purge);
  2325. }
  2326. static void purge_fragmented_blocks_allcpus(void)
  2327. {
  2328. int cpu;
  2329. for_each_possible_cpu(cpu)
  2330. purge_fragmented_blocks(cpu);
  2331. }
  2332. static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
  2333. {
  2334. struct vmap_block_queue *vbq;
  2335. struct vmap_block *vb;
  2336. void *vaddr = NULL;
  2337. unsigned int order;
  2338. BUG_ON(offset_in_page(size));
  2339. BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
  2340. if (WARN_ON(size == 0)) {
  2341. /*
  2342. * Allocating 0 bytes isn't what caller wants since
  2343. * get_order(0) returns funny result. Just warn and terminate
  2344. * early.
  2345. */
  2346. return ERR_PTR(-EINVAL);
  2347. }
  2348. order = get_order(size);
  2349. rcu_read_lock();
  2350. vbq = raw_cpu_ptr(&vmap_block_queue);
  2351. list_for_each_entry_rcu(vb, &vbq->free, free_list) {
  2352. unsigned long pages_off;
  2353. if (READ_ONCE(vb->free) < (1UL << order))
  2354. continue;
  2355. spin_lock(&vb->lock);
  2356. if (vb->free < (1UL << order)) {
  2357. spin_unlock(&vb->lock);
  2358. continue;
  2359. }
  2360. pages_off = VMAP_BBMAP_BITS - vb->free;
  2361. vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
  2362. WRITE_ONCE(vb->free, vb->free - (1UL << order));
  2363. bitmap_set(vb->used_map, pages_off, (1UL << order));
  2364. if (vb->free == 0) {
  2365. spin_lock(&vbq->lock);
  2366. list_del_rcu(&vb->free_list);
  2367. spin_unlock(&vbq->lock);
  2368. }
  2369. spin_unlock(&vb->lock);
  2370. break;
  2371. }
  2372. rcu_read_unlock();
  2373. /* Allocate new block if nothing was found */
  2374. if (!vaddr)
  2375. vaddr = new_vmap_block(order, gfp_mask);
  2376. return vaddr;
  2377. }
  2378. static void vb_free(unsigned long addr, unsigned long size)
  2379. {
  2380. unsigned long offset;
  2381. unsigned int order;
  2382. struct vmap_block *vb;
  2383. struct xarray *xa;
  2384. BUG_ON(offset_in_page(size));
  2385. BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
  2386. flush_cache_vunmap(addr, addr + size);
  2387. order = get_order(size);
  2388. offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
  2389. xa = addr_to_vb_xa(addr);
  2390. vb = xa_load(xa, addr_to_vb_idx(addr));
  2391. spin_lock(&vb->lock);
  2392. bitmap_clear(vb->used_map, offset, (1UL << order));
  2393. spin_unlock(&vb->lock);
  2394. vunmap_range_noflush(addr, addr + size);
  2395. if (debug_pagealloc_enabled_static())
  2396. flush_tlb_kernel_range(addr, addr + size);
  2397. spin_lock(&vb->lock);
  2398. /* Expand the not yet TLB flushed dirty range */
  2399. vb->dirty_min = min(vb->dirty_min, offset);
  2400. vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
  2401. WRITE_ONCE(vb->dirty, vb->dirty + (1UL << order));
  2402. if (vb->dirty == VMAP_BBMAP_BITS) {
  2403. BUG_ON(vb->free);
  2404. spin_unlock(&vb->lock);
  2405. free_vmap_block(vb);
  2406. } else
  2407. spin_unlock(&vb->lock);
  2408. }
  2409. static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
  2410. {
  2411. LIST_HEAD(purge_list);
  2412. int cpu;
  2413. if (unlikely(!vmap_initialized))
  2414. return;
  2415. mutex_lock(&vmap_purge_lock);
  2416. for_each_possible_cpu(cpu) {
  2417. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
  2418. struct vmap_block *vb;
  2419. unsigned long idx;
  2420. rcu_read_lock();
  2421. xa_for_each(&vbq->vmap_blocks, idx, vb) {
  2422. spin_lock(&vb->lock);
  2423. /*
  2424. * Try to purge a fragmented block first. If it's
  2425. * not purgeable, check whether there is dirty
  2426. * space to be flushed.
  2427. */
  2428. if (!purge_fragmented_block(vb, &purge_list, false) &&
  2429. vb->dirty_max && vb->dirty != VMAP_BBMAP_BITS) {
  2430. unsigned long va_start = vb->va->va_start;
  2431. unsigned long s, e;
  2432. s = va_start + (vb->dirty_min << PAGE_SHIFT);
  2433. e = va_start + (vb->dirty_max << PAGE_SHIFT);
  2434. start = min(s, start);
  2435. end = max(e, end);
  2436. /* Prevent that this is flushed again */
  2437. vb->dirty_min = VMAP_BBMAP_BITS;
  2438. vb->dirty_max = 0;
  2439. flush = 1;
  2440. }
  2441. spin_unlock(&vb->lock);
  2442. }
  2443. rcu_read_unlock();
  2444. }
  2445. free_purged_blocks(&purge_list);
  2446. if (!__purge_vmap_area_lazy(start, end, false) && flush)
  2447. flush_tlb_kernel_range(start, end);
  2448. mutex_unlock(&vmap_purge_lock);
  2449. }
  2450. /**
  2451. * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
  2452. *
  2453. * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
  2454. * to amortize TLB flushing overheads. What this means is that any page you
  2455. * have now, may, in a former life, have been mapped into kernel virtual
  2456. * address by the vmap layer and so there might be some CPUs with TLB entries
  2457. * still referencing that page (additional to the regular 1:1 kernel mapping).
  2458. *
  2459. * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
  2460. * be sure that none of the pages we have control over will have any aliases
  2461. * from the vmap layer.
  2462. */
  2463. void vm_unmap_aliases(void)
  2464. {
  2465. unsigned long start = ULONG_MAX, end = 0;
  2466. int flush = 0;
  2467. _vm_unmap_aliases(start, end, flush);
  2468. }
  2469. EXPORT_SYMBOL_GPL(vm_unmap_aliases);
  2470. /**
  2471. * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
  2472. * @mem: the pointer returned by vm_map_ram
  2473. * @count: the count passed to that vm_map_ram call (cannot unmap partial)
  2474. */
  2475. void vm_unmap_ram(const void *mem, unsigned int count)
  2476. {
  2477. unsigned long size = (unsigned long)count << PAGE_SHIFT;
  2478. unsigned long addr = (unsigned long)kasan_reset_tag(mem);
  2479. struct vmap_area *va;
  2480. might_sleep();
  2481. BUG_ON(!addr);
  2482. BUG_ON(addr < VMALLOC_START);
  2483. BUG_ON(addr > VMALLOC_END);
  2484. BUG_ON(!PAGE_ALIGNED(addr));
  2485. kasan_poison_vmalloc(mem, size);
  2486. if (likely(count <= VMAP_MAX_ALLOC)) {
  2487. debug_check_no_locks_freed(mem, size);
  2488. vb_free(addr, size);
  2489. return;
  2490. }
  2491. va = find_unlink_vmap_area(addr);
  2492. if (WARN_ON_ONCE(!va))
  2493. return;
  2494. debug_check_no_locks_freed((void *)va->va_start, va_size(va));
  2495. free_unmap_vmap_area(va);
  2496. }
  2497. EXPORT_SYMBOL(vm_unmap_ram);
  2498. /**
  2499. * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
  2500. * @pages: an array of pointers to the pages to be mapped
  2501. * @count: number of pages
  2502. * @node: prefer to allocate data structures on this node
  2503. *
  2504. * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
  2505. * faster than vmap so it's good. But if you mix long-life and short-life
  2506. * objects with vm_map_ram(), it could consume lots of address space through
  2507. * fragmentation (especially on a 32bit machine). You could see failures in
  2508. * the end. Please use this function for short-lived objects.
  2509. *
  2510. * Returns: a pointer to the address that has been mapped, or %NULL on failure
  2511. */
  2512. void *vm_map_ram(struct page **pages, unsigned int count, int node)
  2513. {
  2514. unsigned long size = (unsigned long)count << PAGE_SHIFT;
  2515. unsigned long addr;
  2516. void *mem;
  2517. if (likely(count <= VMAP_MAX_ALLOC)) {
  2518. mem = vb_alloc(size, GFP_KERNEL);
  2519. if (IS_ERR(mem))
  2520. return NULL;
  2521. addr = (unsigned long)mem;
  2522. } else {
  2523. struct vmap_area *va;
  2524. va = alloc_vmap_area(size, PAGE_SIZE,
  2525. VMALLOC_START, VMALLOC_END,
  2526. node, GFP_KERNEL, VMAP_RAM,
  2527. NULL);
  2528. if (IS_ERR(va))
  2529. return NULL;
  2530. addr = va->va_start;
  2531. mem = (void *)addr;
  2532. }
  2533. if (vmap_pages_range(addr, addr + size, PAGE_KERNEL,
  2534. pages, PAGE_SHIFT) < 0) {
  2535. vm_unmap_ram(mem, count);
  2536. return NULL;
  2537. }
  2538. /*
  2539. * Mark the pages as accessible, now that they are mapped.
  2540. * With hardware tag-based KASAN, marking is skipped for
  2541. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  2542. */
  2543. mem = kasan_unpoison_vmalloc(mem, size, KASAN_VMALLOC_PROT_NORMAL);
  2544. return mem;
  2545. }
  2546. EXPORT_SYMBOL(vm_map_ram);
  2547. static struct vm_struct *vmlist __initdata;
  2548. static inline unsigned int vm_area_page_order(struct vm_struct *vm)
  2549. {
  2550. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  2551. return vm->page_order;
  2552. #else
  2553. return 0;
  2554. #endif
  2555. }
  2556. static inline void set_vm_area_page_order(struct vm_struct *vm, unsigned int order)
  2557. {
  2558. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  2559. vm->page_order = order;
  2560. #else
  2561. BUG_ON(order != 0);
  2562. #endif
  2563. }
  2564. /**
  2565. * vm_area_add_early - add vmap area early during boot
  2566. * @vm: vm_struct to add
  2567. *
  2568. * This function is used to add fixed kernel vm area to vmlist before
  2569. * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
  2570. * should contain proper values and the other fields should be zero.
  2571. *
  2572. * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
  2573. */
  2574. void __init vm_area_add_early(struct vm_struct *vm)
  2575. {
  2576. struct vm_struct *tmp, **p;
  2577. BUG_ON(vmap_initialized);
  2578. for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
  2579. if (tmp->addr >= vm->addr) {
  2580. BUG_ON(tmp->addr < vm->addr + vm->size);
  2581. break;
  2582. } else
  2583. BUG_ON(tmp->addr + tmp->size > vm->addr);
  2584. }
  2585. vm->next = *p;
  2586. *p = vm;
  2587. }
  2588. /**
  2589. * vm_area_register_early - register vmap area early during boot
  2590. * @vm: vm_struct to register
  2591. * @align: requested alignment
  2592. *
  2593. * This function is used to register kernel vm area before
  2594. * vmalloc_init() is called. @vm->size and @vm->flags should contain
  2595. * proper values on entry and other fields should be zero. On return,
  2596. * vm->addr contains the allocated address.
  2597. *
  2598. * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
  2599. */
  2600. void __init vm_area_register_early(struct vm_struct *vm, size_t align)
  2601. {
  2602. unsigned long addr = ALIGN(VMALLOC_START, align);
  2603. struct vm_struct *cur, **p;
  2604. BUG_ON(vmap_initialized);
  2605. for (p = &vmlist; (cur = *p) != NULL; p = &cur->next) {
  2606. if ((unsigned long)cur->addr - addr >= vm->size)
  2607. break;
  2608. addr = ALIGN((unsigned long)cur->addr + cur->size, align);
  2609. }
  2610. BUG_ON(addr > VMALLOC_END - vm->size);
  2611. vm->addr = (void *)addr;
  2612. vm->next = *p;
  2613. *p = vm;
  2614. kasan_populate_early_vm_area_shadow(vm->addr, vm->size);
  2615. }
  2616. static void clear_vm_uninitialized_flag(struct vm_struct *vm)
  2617. {
  2618. /*
  2619. * Before removing VM_UNINITIALIZED,
  2620. * we should make sure that vm has proper values.
  2621. * Pair with smp_rmb() in vread_iter() and vmalloc_info_show().
  2622. */
  2623. smp_wmb();
  2624. vm->flags &= ~VM_UNINITIALIZED;
  2625. }
  2626. static struct vm_struct *__get_vm_area_node(unsigned long size,
  2627. unsigned long align, unsigned long shift, unsigned long flags,
  2628. unsigned long start, unsigned long end, int node,
  2629. gfp_t gfp_mask, const void *caller)
  2630. {
  2631. struct vmap_area *va;
  2632. struct vm_struct *area;
  2633. unsigned long requested_size = size;
  2634. BUG_ON(in_interrupt());
  2635. size = ALIGN(size, 1ul << shift);
  2636. if (unlikely(!size))
  2637. return NULL;
  2638. if (flags & VM_IOREMAP)
  2639. align = 1ul << clamp_t(int, get_count_order_long(size),
  2640. PAGE_SHIFT, IOREMAP_MAX_ORDER);
  2641. area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
  2642. if (unlikely(!area))
  2643. return NULL;
  2644. if (!(flags & VM_NO_GUARD))
  2645. size += PAGE_SIZE;
  2646. area->flags = flags;
  2647. area->caller = caller;
  2648. area->requested_size = requested_size;
  2649. va = alloc_vmap_area(size, align, start, end, node, gfp_mask, 0, area);
  2650. if (IS_ERR(va)) {
  2651. kfree(area);
  2652. return NULL;
  2653. }
  2654. /*
  2655. * Mark pages for non-VM_ALLOC mappings as accessible. Do it now as a
  2656. * best-effort approach, as they can be mapped outside of vmalloc code.
  2657. * For VM_ALLOC mappings, the pages are marked as accessible after
  2658. * getting mapped in __vmalloc_node_range().
  2659. * With hardware tag-based KASAN, marking is skipped for
  2660. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  2661. */
  2662. if (!(flags & VM_ALLOC))
  2663. area->addr = kasan_unpoison_vmalloc(area->addr, requested_size,
  2664. KASAN_VMALLOC_PROT_NORMAL);
  2665. return area;
  2666. }
  2667. struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
  2668. unsigned long start, unsigned long end,
  2669. const void *caller)
  2670. {
  2671. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, start, end,
  2672. NUMA_NO_NODE, GFP_KERNEL, caller);
  2673. }
  2674. /**
  2675. * get_vm_area - reserve a contiguous kernel virtual area
  2676. * @size: size of the area
  2677. * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
  2678. *
  2679. * Search an area of @size in the kernel virtual mapping area,
  2680. * and reserved it for out purposes. Returns the area descriptor
  2681. * on success or %NULL on failure.
  2682. *
  2683. * Return: the area descriptor on success or %NULL on failure.
  2684. */
  2685. struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
  2686. {
  2687. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
  2688. VMALLOC_START, VMALLOC_END,
  2689. NUMA_NO_NODE, GFP_KERNEL,
  2690. __builtin_return_address(0));
  2691. }
  2692. struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
  2693. const void *caller)
  2694. {
  2695. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
  2696. VMALLOC_START, VMALLOC_END,
  2697. NUMA_NO_NODE, GFP_KERNEL, caller);
  2698. }
  2699. /**
  2700. * find_vm_area - find a continuous kernel virtual area
  2701. * @addr: base address
  2702. *
  2703. * Search for the kernel VM area starting at @addr, and return it.
  2704. * It is up to the caller to do all required locking to keep the returned
  2705. * pointer valid.
  2706. *
  2707. * Return: the area descriptor on success or %NULL on failure.
  2708. */
  2709. struct vm_struct *find_vm_area(const void *addr)
  2710. {
  2711. struct vmap_area *va;
  2712. va = find_vmap_area((unsigned long)addr);
  2713. if (!va)
  2714. return NULL;
  2715. return va->vm;
  2716. }
  2717. /**
  2718. * remove_vm_area - find and remove a continuous kernel virtual area
  2719. * @addr: base address
  2720. *
  2721. * Search for the kernel VM area starting at @addr, and remove it.
  2722. * This function returns the found VM area, but using it is NOT safe
  2723. * on SMP machines, except for its size or flags.
  2724. *
  2725. * Return: the area descriptor on success or %NULL on failure.
  2726. */
  2727. struct vm_struct *remove_vm_area(const void *addr)
  2728. {
  2729. struct vmap_area *va;
  2730. struct vm_struct *vm;
  2731. might_sleep();
  2732. if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
  2733. addr))
  2734. return NULL;
  2735. va = find_unlink_vmap_area((unsigned long)addr);
  2736. if (!va || !va->vm)
  2737. return NULL;
  2738. vm = va->vm;
  2739. debug_check_no_locks_freed(vm->addr, get_vm_area_size(vm));
  2740. debug_check_no_obj_freed(vm->addr, get_vm_area_size(vm));
  2741. kasan_free_module_shadow(vm);
  2742. kasan_poison_vmalloc(vm->addr, get_vm_area_size(vm));
  2743. free_unmap_vmap_area(va);
  2744. return vm;
  2745. }
  2746. static inline void set_area_direct_map(const struct vm_struct *area,
  2747. int (*set_direct_map)(struct page *page))
  2748. {
  2749. int i;
  2750. /* HUGE_VMALLOC passes small pages to set_direct_map */
  2751. for (i = 0; i < area->nr_pages; i++)
  2752. if (page_address(area->pages[i]))
  2753. set_direct_map(area->pages[i]);
  2754. }
  2755. /*
  2756. * Flush the vm mapping and reset the direct map.
  2757. */
  2758. static void vm_reset_perms(struct vm_struct *area)
  2759. {
  2760. unsigned long start = ULONG_MAX, end = 0;
  2761. unsigned int page_order = vm_area_page_order(area);
  2762. int flush_dmap = 0;
  2763. int i;
  2764. /*
  2765. * Find the start and end range of the direct mappings to make sure that
  2766. * the vm_unmap_aliases() flush includes the direct map.
  2767. */
  2768. for (i = 0; i < area->nr_pages; i += 1U << page_order) {
  2769. unsigned long addr = (unsigned long)page_address(area->pages[i]);
  2770. if (addr) {
  2771. unsigned long page_size;
  2772. page_size = PAGE_SIZE << page_order;
  2773. start = min(addr, start);
  2774. end = max(addr + page_size, end);
  2775. flush_dmap = 1;
  2776. }
  2777. }
  2778. /*
  2779. * Set direct map to something invalid so that it won't be cached if
  2780. * there are any accesses after the TLB flush, then flush the TLB and
  2781. * reset the direct map permissions to the default.
  2782. */
  2783. set_area_direct_map(area, set_direct_map_invalid_noflush);
  2784. _vm_unmap_aliases(start, end, flush_dmap);
  2785. set_area_direct_map(area, set_direct_map_default_noflush);
  2786. }
  2787. static void delayed_vfree_work(struct work_struct *w)
  2788. {
  2789. struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
  2790. struct llist_node *t, *llnode;
  2791. llist_for_each_safe(llnode, t, llist_del_all(&p->list))
  2792. vfree(llnode);
  2793. }
  2794. /**
  2795. * vfree_atomic - release memory allocated by vmalloc()
  2796. * @addr: memory base address
  2797. *
  2798. * This one is just like vfree() but can be called in any atomic context
  2799. * except NMIs.
  2800. */
  2801. void vfree_atomic(const void *addr)
  2802. {
  2803. struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
  2804. BUG_ON(in_nmi());
  2805. kmemleak_free(addr);
  2806. /*
  2807. * Use raw_cpu_ptr() because this can be called from preemptible
  2808. * context. Preemption is absolutely fine here, because the llist_add()
  2809. * implementation is lockless, so it works even if we are adding to
  2810. * another cpu's list. schedule_work() should be fine with this too.
  2811. */
  2812. if (addr && llist_add((struct llist_node *)addr, &p->list))
  2813. schedule_work(&p->wq);
  2814. }
  2815. /**
  2816. * vfree - Release memory allocated by vmalloc()
  2817. * @addr: Memory base address
  2818. *
  2819. * Free the virtually continuous memory area starting at @addr, as obtained
  2820. * from one of the vmalloc() family of APIs. This will usually also free the
  2821. * physical memory underlying the virtual allocation, but that memory is
  2822. * reference counted, so it will not be freed until the last user goes away.
  2823. *
  2824. * If @addr is NULL, no operation is performed.
  2825. *
  2826. * Context:
  2827. * May sleep if called *not* from interrupt context.
  2828. * Must not be called in NMI context (strictly speaking, it could be
  2829. * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
  2830. * conventions for vfree() arch-dependent would be a really bad idea).
  2831. */
  2832. void vfree(const void *addr)
  2833. {
  2834. struct vm_struct *vm;
  2835. int i;
  2836. if (unlikely(in_interrupt())) {
  2837. vfree_atomic(addr);
  2838. return;
  2839. }
  2840. BUG_ON(in_nmi());
  2841. kmemleak_free(addr);
  2842. might_sleep();
  2843. if (!addr)
  2844. return;
  2845. vm = remove_vm_area(addr);
  2846. if (unlikely(!vm)) {
  2847. WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
  2848. addr);
  2849. return;
  2850. }
  2851. if (unlikely(vm->flags & VM_FLUSH_RESET_PERMS))
  2852. vm_reset_perms(vm);
  2853. for (i = 0; i < vm->nr_pages; i++) {
  2854. struct page *page = vm->pages[i];
  2855. BUG_ON(!page);
  2856. if (!(vm->flags & VM_MAP_PUT_PAGES))
  2857. mod_memcg_page_state(page, MEMCG_VMALLOC, -1);
  2858. /*
  2859. * High-order allocs for huge vmallocs are split, so
  2860. * can be freed as an array of order-0 allocations
  2861. */
  2862. __free_page(page);
  2863. cond_resched();
  2864. }
  2865. if (!(vm->flags & VM_MAP_PUT_PAGES))
  2866. atomic_long_sub(vm->nr_pages, &nr_vmalloc_pages);
  2867. kvfree(vm->pages);
  2868. kfree(vm);
  2869. }
  2870. EXPORT_SYMBOL(vfree);
  2871. /**
  2872. * vunmap - release virtual mapping obtained by vmap()
  2873. * @addr: memory base address
  2874. *
  2875. * Free the virtually contiguous memory area starting at @addr,
  2876. * which was created from the page array passed to vmap().
  2877. *
  2878. * Must not be called in interrupt context.
  2879. */
  2880. void vunmap(const void *addr)
  2881. {
  2882. struct vm_struct *vm;
  2883. BUG_ON(in_interrupt());
  2884. might_sleep();
  2885. if (!addr)
  2886. return;
  2887. vm = remove_vm_area(addr);
  2888. if (unlikely(!vm)) {
  2889. WARN(1, KERN_ERR "Trying to vunmap() nonexistent vm area (%p)\n",
  2890. addr);
  2891. return;
  2892. }
  2893. kfree(vm);
  2894. }
  2895. EXPORT_SYMBOL(vunmap);
  2896. /**
  2897. * vmap - map an array of pages into virtually contiguous space
  2898. * @pages: array of page pointers
  2899. * @count: number of pages to map
  2900. * @flags: vm_area->flags
  2901. * @prot: page protection for the mapping
  2902. *
  2903. * Maps @count pages from @pages into contiguous kernel virtual space.
  2904. * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself
  2905. * (which must be kmalloc or vmalloc memory) and one reference per pages in it
  2906. * are transferred from the caller to vmap(), and will be freed / dropped when
  2907. * vfree() is called on the return value.
  2908. *
  2909. * Return: the address of the area or %NULL on failure
  2910. */
  2911. void *vmap(struct page **pages, unsigned int count,
  2912. unsigned long flags, pgprot_t prot)
  2913. {
  2914. struct vm_struct *area;
  2915. unsigned long addr;
  2916. unsigned long size; /* In bytes */
  2917. might_sleep();
  2918. if (WARN_ON_ONCE(flags & VM_FLUSH_RESET_PERMS))
  2919. return NULL;
  2920. /*
  2921. * Your top guard is someone else's bottom guard. Not having a top
  2922. * guard compromises someone else's mappings too.
  2923. */
  2924. if (WARN_ON_ONCE(flags & VM_NO_GUARD))
  2925. flags &= ~VM_NO_GUARD;
  2926. if (count > totalram_pages())
  2927. return NULL;
  2928. size = (unsigned long)count << PAGE_SHIFT;
  2929. area = get_vm_area_caller(size, flags, __builtin_return_address(0));
  2930. if (!area)
  2931. return NULL;
  2932. addr = (unsigned long)area->addr;
  2933. if (vmap_pages_range(addr, addr + size, pgprot_nx(prot),
  2934. pages, PAGE_SHIFT) < 0) {
  2935. vunmap(area->addr);
  2936. return NULL;
  2937. }
  2938. if (flags & VM_MAP_PUT_PAGES) {
  2939. area->pages = pages;
  2940. area->nr_pages = count;
  2941. }
  2942. return area->addr;
  2943. }
  2944. EXPORT_SYMBOL(vmap);
  2945. #ifdef CONFIG_VMAP_PFN
  2946. struct vmap_pfn_data {
  2947. unsigned long *pfns;
  2948. pgprot_t prot;
  2949. unsigned int idx;
  2950. };
  2951. static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private)
  2952. {
  2953. struct vmap_pfn_data *data = private;
  2954. unsigned long pfn = data->pfns[data->idx];
  2955. pte_t ptent;
  2956. if (WARN_ON_ONCE(pfn_valid(pfn)))
  2957. return -EINVAL;
  2958. ptent = pte_mkspecial(pfn_pte(pfn, data->prot));
  2959. set_pte_at(&init_mm, addr, pte, ptent);
  2960. data->idx++;
  2961. return 0;
  2962. }
  2963. /**
  2964. * vmap_pfn - map an array of PFNs into virtually contiguous space
  2965. * @pfns: array of PFNs
  2966. * @count: number of pages to map
  2967. * @prot: page protection for the mapping
  2968. *
  2969. * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns
  2970. * the start address of the mapping.
  2971. */
  2972. void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
  2973. {
  2974. struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) };
  2975. struct vm_struct *area;
  2976. area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP,
  2977. __builtin_return_address(0));
  2978. if (!area)
  2979. return NULL;
  2980. if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
  2981. count * PAGE_SIZE, vmap_pfn_apply, &data)) {
  2982. free_vm_area(area);
  2983. return NULL;
  2984. }
  2985. flush_cache_vmap((unsigned long)area->addr,
  2986. (unsigned long)area->addr + count * PAGE_SIZE);
  2987. return area->addr;
  2988. }
  2989. EXPORT_SYMBOL_GPL(vmap_pfn);
  2990. #endif /* CONFIG_VMAP_PFN */
  2991. static inline unsigned int
  2992. vm_area_alloc_pages(gfp_t gfp, int nid,
  2993. unsigned int order, unsigned int nr_pages, struct page **pages)
  2994. {
  2995. unsigned int nr_allocated = 0;
  2996. struct page *page;
  2997. int i;
  2998. /*
  2999. * For order-0 pages we make use of bulk allocator, if
  3000. * the page array is partly or not at all populated due
  3001. * to fails, fallback to a single page allocator that is
  3002. * more permissive.
  3003. */
  3004. if (!order) {
  3005. while (nr_allocated < nr_pages) {
  3006. unsigned int nr, nr_pages_request;
  3007. /*
  3008. * A maximum allowed request is hard-coded and is 100
  3009. * pages per call. That is done in order to prevent a
  3010. * long preemption off scenario in the bulk-allocator
  3011. * so the range is [1:100].
  3012. */
  3013. nr_pages_request = min(100U, nr_pages - nr_allocated);
  3014. /* memory allocation should consider mempolicy, we can't
  3015. * wrongly use nearest node when nid == NUMA_NO_NODE,
  3016. * otherwise memory may be allocated in only one node,
  3017. * but mempolicy wants to alloc memory by interleaving.
  3018. */
  3019. if (IS_ENABLED(CONFIG_NUMA) && nid == NUMA_NO_NODE)
  3020. nr = alloc_pages_bulk_array_mempolicy_noprof(gfp,
  3021. nr_pages_request,
  3022. pages + nr_allocated);
  3023. else
  3024. nr = alloc_pages_bulk_array_node_noprof(gfp, nid,
  3025. nr_pages_request,
  3026. pages + nr_allocated);
  3027. nr_allocated += nr;
  3028. cond_resched();
  3029. /*
  3030. * If zero or pages were obtained partly,
  3031. * fallback to a single page allocator.
  3032. */
  3033. if (nr != nr_pages_request)
  3034. break;
  3035. }
  3036. }
  3037. /* High-order pages or fallback path if "bulk" fails. */
  3038. while (nr_allocated < nr_pages) {
  3039. if (!(gfp & __GFP_NOFAIL) && fatal_signal_pending(current))
  3040. break;
  3041. if (nid == NUMA_NO_NODE)
  3042. page = alloc_pages_noprof(gfp, order);
  3043. else
  3044. page = alloc_pages_node_noprof(nid, gfp, order);
  3045. if (unlikely(!page))
  3046. break;
  3047. /*
  3048. * High-order allocations must be able to be treated as
  3049. * independent small pages by callers (as they can with
  3050. * small-page vmallocs). Some drivers do their own refcounting
  3051. * on vmalloc_to_page() pages, some use page->mapping,
  3052. * page->lru, etc.
  3053. */
  3054. if (order)
  3055. split_page(page, order);
  3056. /*
  3057. * Careful, we allocate and map page-order pages, but
  3058. * tracking is done per PAGE_SIZE page so as to keep the
  3059. * vm_struct APIs independent of the physical/mapped size.
  3060. */
  3061. for (i = 0; i < (1U << order); i++)
  3062. pages[nr_allocated + i] = page + i;
  3063. cond_resched();
  3064. nr_allocated += 1U << order;
  3065. }
  3066. return nr_allocated;
  3067. }
  3068. static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
  3069. pgprot_t prot, unsigned int page_shift,
  3070. int node)
  3071. {
  3072. const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
  3073. bool nofail = gfp_mask & __GFP_NOFAIL;
  3074. unsigned long addr = (unsigned long)area->addr;
  3075. unsigned long size = get_vm_area_size(area);
  3076. unsigned long array_size;
  3077. unsigned int nr_small_pages = size >> PAGE_SHIFT;
  3078. unsigned int page_order;
  3079. unsigned int flags;
  3080. int ret;
  3081. array_size = (unsigned long)nr_small_pages * sizeof(struct page *);
  3082. if (!(gfp_mask & (GFP_DMA | GFP_DMA32)))
  3083. gfp_mask |= __GFP_HIGHMEM;
  3084. /* Please note that the recursion is strictly bounded. */
  3085. if (array_size > PAGE_SIZE) {
  3086. area->pages = __vmalloc_node_noprof(array_size, 1, nested_gfp, node,
  3087. area->caller);
  3088. } else {
  3089. area->pages = kmalloc_node_noprof(array_size, nested_gfp, node);
  3090. }
  3091. if (!area->pages) {
  3092. warn_alloc(gfp_mask, NULL,
  3093. "vmalloc error: size %lu, failed to allocated page array size %lu",
  3094. nr_small_pages * PAGE_SIZE, array_size);
  3095. free_vm_area(area);
  3096. return NULL;
  3097. }
  3098. set_vm_area_page_order(area, page_shift - PAGE_SHIFT);
  3099. page_order = vm_area_page_order(area);
  3100. /*
  3101. * High-order nofail allocations are really expensive and
  3102. * potentially dangerous (pre-mature OOM, disruptive reclaim
  3103. * and compaction etc.
  3104. *
  3105. * Please note, the __vmalloc_node_range_noprof() falls-back
  3106. * to order-0 pages if high-order attempt is unsuccessful.
  3107. */
  3108. area->nr_pages = vm_area_alloc_pages((page_order ?
  3109. gfp_mask & ~__GFP_NOFAIL : gfp_mask) | __GFP_NOWARN,
  3110. node, page_order, nr_small_pages, area->pages);
  3111. atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
  3112. if (gfp_mask & __GFP_ACCOUNT) {
  3113. int i;
  3114. for (i = 0; i < area->nr_pages; i++)
  3115. mod_memcg_page_state(area->pages[i], MEMCG_VMALLOC, 1);
  3116. }
  3117. /*
  3118. * If not enough pages were obtained to accomplish an
  3119. * allocation request, free them via vfree() if any.
  3120. */
  3121. if (area->nr_pages != nr_small_pages) {
  3122. /*
  3123. * vm_area_alloc_pages() can fail due to insufficient memory but
  3124. * also:-
  3125. *
  3126. * - a pending fatal signal
  3127. * - insufficient huge page-order pages
  3128. *
  3129. * Since we always retry allocations at order-0 in the huge page
  3130. * case a warning for either is spurious.
  3131. */
  3132. if (!fatal_signal_pending(current) && page_order == 0)
  3133. warn_alloc(gfp_mask, NULL,
  3134. "vmalloc error: size %lu, failed to allocate pages",
  3135. area->nr_pages * PAGE_SIZE);
  3136. goto fail;
  3137. }
  3138. /*
  3139. * page tables allocations ignore external gfp mask, enforce it
  3140. * by the scope API
  3141. */
  3142. if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO)
  3143. flags = memalloc_nofs_save();
  3144. else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0)
  3145. flags = memalloc_noio_save();
  3146. do {
  3147. ret = vmap_pages_range(addr, addr + size, prot, area->pages,
  3148. page_shift);
  3149. if (nofail && (ret < 0))
  3150. schedule_timeout_uninterruptible(1);
  3151. } while (nofail && (ret < 0));
  3152. if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO)
  3153. memalloc_nofs_restore(flags);
  3154. else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0)
  3155. memalloc_noio_restore(flags);
  3156. if (ret < 0) {
  3157. warn_alloc(gfp_mask, NULL,
  3158. "vmalloc error: size %lu, failed to map pages",
  3159. area->nr_pages * PAGE_SIZE);
  3160. goto fail;
  3161. }
  3162. return area->addr;
  3163. fail:
  3164. vfree(area->addr);
  3165. return NULL;
  3166. }
  3167. /**
  3168. * __vmalloc_node_range - allocate virtually contiguous memory
  3169. * @size: allocation size
  3170. * @align: desired alignment
  3171. * @start: vm area range start
  3172. * @end: vm area range end
  3173. * @gfp_mask: flags for the page level allocator
  3174. * @prot: protection mask for the allocated pages
  3175. * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
  3176. * @node: node to use for allocation or NUMA_NO_NODE
  3177. * @caller: caller's return address
  3178. *
  3179. * Allocate enough pages to cover @size from the page level
  3180. * allocator with @gfp_mask flags. Please note that the full set of gfp
  3181. * flags are not supported. GFP_KERNEL, GFP_NOFS and GFP_NOIO are all
  3182. * supported.
  3183. * Zone modifiers are not supported. From the reclaim modifiers
  3184. * __GFP_DIRECT_RECLAIM is required (aka GFP_NOWAIT is not supported)
  3185. * and only __GFP_NOFAIL is supported (i.e. __GFP_NORETRY and
  3186. * __GFP_RETRY_MAYFAIL are not supported).
  3187. *
  3188. * __GFP_NOWARN can be used to suppress failures messages.
  3189. *
  3190. * Map them into contiguous kernel virtual space, using a pagetable
  3191. * protection of @prot.
  3192. *
  3193. * Return: the address of the area or %NULL on failure
  3194. */
  3195. void *__vmalloc_node_range_noprof(unsigned long size, unsigned long align,
  3196. unsigned long start, unsigned long end, gfp_t gfp_mask,
  3197. pgprot_t prot, unsigned long vm_flags, int node,
  3198. const void *caller)
  3199. {
  3200. struct vm_struct *area;
  3201. void *ret;
  3202. kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_NONE;
  3203. unsigned long real_size = size;
  3204. unsigned long real_align = align;
  3205. unsigned int shift = PAGE_SHIFT;
  3206. if (WARN_ON_ONCE(!size))
  3207. return NULL;
  3208. if ((size >> PAGE_SHIFT) > totalram_pages()) {
  3209. warn_alloc(gfp_mask, NULL,
  3210. "vmalloc error: size %lu, exceeds total pages",
  3211. real_size);
  3212. return NULL;
  3213. }
  3214. if (vmap_allow_huge && (vm_flags & VM_ALLOW_HUGE_VMAP)) {
  3215. unsigned long size_per_node;
  3216. /*
  3217. * Try huge pages. Only try for PAGE_KERNEL allocations,
  3218. * others like modules don't yet expect huge pages in
  3219. * their allocations due to apply_to_page_range not
  3220. * supporting them.
  3221. */
  3222. size_per_node = size;
  3223. if (node == NUMA_NO_NODE)
  3224. size_per_node /= num_online_nodes();
  3225. if (arch_vmap_pmd_supported(prot) && size_per_node >= PMD_SIZE)
  3226. shift = PMD_SHIFT;
  3227. else
  3228. shift = arch_vmap_pte_supported_shift(size_per_node);
  3229. align = max(real_align, 1UL << shift);
  3230. size = ALIGN(real_size, 1UL << shift);
  3231. }
  3232. again:
  3233. area = __get_vm_area_node(real_size, align, shift, VM_ALLOC |
  3234. VM_UNINITIALIZED | vm_flags, start, end, node,
  3235. gfp_mask, caller);
  3236. if (!area) {
  3237. bool nofail = gfp_mask & __GFP_NOFAIL;
  3238. warn_alloc(gfp_mask, NULL,
  3239. "vmalloc error: size %lu, vm_struct allocation failed%s",
  3240. real_size, (nofail) ? ". Retrying." : "");
  3241. if (nofail) {
  3242. schedule_timeout_uninterruptible(1);
  3243. goto again;
  3244. }
  3245. goto fail;
  3246. }
  3247. /*
  3248. * Prepare arguments for __vmalloc_area_node() and
  3249. * kasan_unpoison_vmalloc().
  3250. */
  3251. if (pgprot_val(prot) == pgprot_val(PAGE_KERNEL)) {
  3252. if (kasan_hw_tags_enabled()) {
  3253. /*
  3254. * Modify protection bits to allow tagging.
  3255. * This must be done before mapping.
  3256. */
  3257. prot = arch_vmap_pgprot_tagged(prot);
  3258. /*
  3259. * Skip page_alloc poisoning and zeroing for physical
  3260. * pages backing VM_ALLOC mapping. Memory is instead
  3261. * poisoned and zeroed by kasan_unpoison_vmalloc().
  3262. */
  3263. gfp_mask |= __GFP_SKIP_KASAN | __GFP_SKIP_ZERO;
  3264. }
  3265. /* Take note that the mapping is PAGE_KERNEL. */
  3266. kasan_flags |= KASAN_VMALLOC_PROT_NORMAL;
  3267. }
  3268. /* Allocate physical pages and map them into vmalloc space. */
  3269. ret = __vmalloc_area_node(area, gfp_mask, prot, shift, node);
  3270. if (!ret)
  3271. goto fail;
  3272. /*
  3273. * Mark the pages as accessible, now that they are mapped.
  3274. * The condition for setting KASAN_VMALLOC_INIT should complement the
  3275. * one in post_alloc_hook() with regards to the __GFP_SKIP_ZERO check
  3276. * to make sure that memory is initialized under the same conditions.
  3277. * Tag-based KASAN modes only assign tags to normal non-executable
  3278. * allocations, see __kasan_unpoison_vmalloc().
  3279. */
  3280. kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
  3281. if (!want_init_on_free() && want_init_on_alloc(gfp_mask) &&
  3282. (gfp_mask & __GFP_SKIP_ZERO))
  3283. kasan_flags |= KASAN_VMALLOC_INIT;
  3284. /* KASAN_VMALLOC_PROT_NORMAL already set if required. */
  3285. area->addr = kasan_unpoison_vmalloc(area->addr, real_size, kasan_flags);
  3286. /*
  3287. * In this function, newly allocated vm_struct has VM_UNINITIALIZED
  3288. * flag. It means that vm_struct is not fully initialized.
  3289. * Now, it is fully initialized, so remove this flag here.
  3290. */
  3291. clear_vm_uninitialized_flag(area);
  3292. size = PAGE_ALIGN(size);
  3293. if (!(vm_flags & VM_DEFER_KMEMLEAK))
  3294. kmemleak_vmalloc(area, size, gfp_mask);
  3295. return area->addr;
  3296. fail:
  3297. if (shift > PAGE_SHIFT) {
  3298. shift = PAGE_SHIFT;
  3299. align = real_align;
  3300. size = real_size;
  3301. goto again;
  3302. }
  3303. return NULL;
  3304. }
  3305. /**
  3306. * __vmalloc_node - allocate virtually contiguous memory
  3307. * @size: allocation size
  3308. * @align: desired alignment
  3309. * @gfp_mask: flags for the page level allocator
  3310. * @node: node to use for allocation or NUMA_NO_NODE
  3311. * @caller: caller's return address
  3312. *
  3313. * Allocate enough pages to cover @size from the page level allocator with
  3314. * @gfp_mask flags. Map them into contiguous kernel virtual space.
  3315. *
  3316. * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
  3317. * and __GFP_NOFAIL are not supported
  3318. *
  3319. * Any use of gfp flags outside of GFP_KERNEL should be consulted
  3320. * with mm people.
  3321. *
  3322. * Return: pointer to the allocated memory or %NULL on error
  3323. */
  3324. void *__vmalloc_node_noprof(unsigned long size, unsigned long align,
  3325. gfp_t gfp_mask, int node, const void *caller)
  3326. {
  3327. return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END,
  3328. gfp_mask, PAGE_KERNEL, 0, node, caller);
  3329. }
  3330. /*
  3331. * This is only for performance analysis of vmalloc and stress purpose.
  3332. * It is required by vmalloc test module, therefore do not use it other
  3333. * than that.
  3334. */
  3335. #ifdef CONFIG_TEST_VMALLOC_MODULE
  3336. EXPORT_SYMBOL_GPL(__vmalloc_node_noprof);
  3337. #endif
  3338. void *__vmalloc_noprof(unsigned long size, gfp_t gfp_mask)
  3339. {
  3340. return __vmalloc_node_noprof(size, 1, gfp_mask, NUMA_NO_NODE,
  3341. __builtin_return_address(0));
  3342. }
  3343. EXPORT_SYMBOL(__vmalloc_noprof);
  3344. /**
  3345. * vmalloc - allocate virtually contiguous memory
  3346. * @size: allocation size
  3347. *
  3348. * Allocate enough pages to cover @size from the page level
  3349. * allocator and map them into contiguous kernel virtual space.
  3350. *
  3351. * For tight control over page level allocator and protection flags
  3352. * use __vmalloc() instead.
  3353. *
  3354. * Return: pointer to the allocated memory or %NULL on error
  3355. */
  3356. void *vmalloc_noprof(unsigned long size)
  3357. {
  3358. return __vmalloc_node_noprof(size, 1, GFP_KERNEL, NUMA_NO_NODE,
  3359. __builtin_return_address(0));
  3360. }
  3361. EXPORT_SYMBOL(vmalloc_noprof);
  3362. /**
  3363. * vmalloc_huge - allocate virtually contiguous memory, allow huge pages
  3364. * @size: allocation size
  3365. * @gfp_mask: flags for the page level allocator
  3366. *
  3367. * Allocate enough pages to cover @size from the page level
  3368. * allocator and map them into contiguous kernel virtual space.
  3369. * If @size is greater than or equal to PMD_SIZE, allow using
  3370. * huge pages for the memory
  3371. *
  3372. * Return: pointer to the allocated memory or %NULL on error
  3373. */
  3374. void *vmalloc_huge_noprof(unsigned long size, gfp_t gfp_mask)
  3375. {
  3376. return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END,
  3377. gfp_mask, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
  3378. NUMA_NO_NODE, __builtin_return_address(0));
  3379. }
  3380. EXPORT_SYMBOL_GPL(vmalloc_huge_noprof);
  3381. /**
  3382. * vzalloc - allocate virtually contiguous memory with zero fill
  3383. * @size: allocation size
  3384. *
  3385. * Allocate enough pages to cover @size from the page level
  3386. * allocator and map them into contiguous kernel virtual space.
  3387. * The memory allocated is set to zero.
  3388. *
  3389. * For tight control over page level allocator and protection flags
  3390. * use __vmalloc() instead.
  3391. *
  3392. * Return: pointer to the allocated memory or %NULL on error
  3393. */
  3394. void *vzalloc_noprof(unsigned long size)
  3395. {
  3396. return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
  3397. __builtin_return_address(0));
  3398. }
  3399. EXPORT_SYMBOL(vzalloc_noprof);
  3400. /**
  3401. * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
  3402. * @size: allocation size
  3403. *
  3404. * The resulting memory area is zeroed so it can be mapped to userspace
  3405. * without leaking data.
  3406. *
  3407. * Return: pointer to the allocated memory or %NULL on error
  3408. */
  3409. void *vmalloc_user_noprof(unsigned long size)
  3410. {
  3411. return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END,
  3412. GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
  3413. VM_USERMAP, NUMA_NO_NODE,
  3414. __builtin_return_address(0));
  3415. }
  3416. EXPORT_SYMBOL(vmalloc_user_noprof);
  3417. /**
  3418. * vmalloc_node - allocate memory on a specific node
  3419. * @size: allocation size
  3420. * @node: numa node
  3421. *
  3422. * Allocate enough pages to cover @size from the page level
  3423. * allocator and map them into contiguous kernel virtual space.
  3424. *
  3425. * For tight control over page level allocator and protection flags
  3426. * use __vmalloc() instead.
  3427. *
  3428. * Return: pointer to the allocated memory or %NULL on error
  3429. */
  3430. void *vmalloc_node_noprof(unsigned long size, int node)
  3431. {
  3432. return __vmalloc_node_noprof(size, 1, GFP_KERNEL, node,
  3433. __builtin_return_address(0));
  3434. }
  3435. EXPORT_SYMBOL(vmalloc_node_noprof);
  3436. /**
  3437. * vzalloc_node - allocate memory on a specific node with zero fill
  3438. * @size: allocation size
  3439. * @node: numa node
  3440. *
  3441. * Allocate enough pages to cover @size from the page level
  3442. * allocator and map them into contiguous kernel virtual space.
  3443. * The memory allocated is set to zero.
  3444. *
  3445. * Return: pointer to the allocated memory or %NULL on error
  3446. */
  3447. void *vzalloc_node_noprof(unsigned long size, int node)
  3448. {
  3449. return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, node,
  3450. __builtin_return_address(0));
  3451. }
  3452. EXPORT_SYMBOL(vzalloc_node_noprof);
  3453. /**
  3454. * vrealloc - reallocate virtually contiguous memory; contents remain unchanged
  3455. * @p: object to reallocate memory for
  3456. * @size: the size to reallocate
  3457. * @flags: the flags for the page level allocator
  3458. *
  3459. * If @p is %NULL, vrealloc() behaves exactly like vmalloc(). If @size is 0 and
  3460. * @p is not a %NULL pointer, the object pointed to is freed.
  3461. *
  3462. * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
  3463. * initial memory allocation, every subsequent call to this API for the same
  3464. * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
  3465. * __GFP_ZERO is not fully honored by this API.
  3466. *
  3467. * In any case, the contents of the object pointed to are preserved up to the
  3468. * lesser of the new and old sizes.
  3469. *
  3470. * This function must not be called concurrently with itself or vfree() for the
  3471. * same memory allocation.
  3472. *
  3473. * Return: pointer to the allocated memory; %NULL if @size is zero or in case of
  3474. * failure
  3475. */
  3476. void *vrealloc_noprof(const void *p, size_t size, gfp_t flags)
  3477. {
  3478. struct vm_struct *vm = NULL;
  3479. size_t alloced_size = 0;
  3480. size_t old_size = 0;
  3481. void *n;
  3482. if (!size) {
  3483. vfree(p);
  3484. return NULL;
  3485. }
  3486. if (p) {
  3487. vm = find_vm_area(p);
  3488. if (unlikely(!vm)) {
  3489. WARN(1, "Trying to vrealloc() nonexistent vm area (%p)\n", p);
  3490. return NULL;
  3491. }
  3492. alloced_size = get_vm_area_size(vm);
  3493. old_size = vm->requested_size;
  3494. if (WARN(alloced_size < old_size,
  3495. "vrealloc() has mismatched area vs requested sizes (%p)\n", p))
  3496. return NULL;
  3497. }
  3498. /*
  3499. * TODO: Shrink the vm_area, i.e. unmap and free unused pages. What
  3500. * would be a good heuristic for when to shrink the vm_area?
  3501. */
  3502. if (size <= old_size) {
  3503. /* Zero out "freed" memory, potentially for future realloc. */
  3504. if (want_init_on_free() || want_init_on_alloc(flags))
  3505. memset((void *)p + size, 0, old_size - size);
  3506. vm->requested_size = size;
  3507. kasan_poison_vmalloc(p + size, old_size - size);
  3508. return (void *)p;
  3509. }
  3510. /*
  3511. * We already have the bytes available in the allocation; use them.
  3512. */
  3513. if (size <= alloced_size) {
  3514. kasan_unpoison_vmalloc(p + old_size, size - old_size,
  3515. KASAN_VMALLOC_PROT_NORMAL);
  3516. /*
  3517. * No need to zero memory here, as unused memory will have
  3518. * already been zeroed at initial allocation time or during
  3519. * realloc shrink time.
  3520. */
  3521. vm->requested_size = size;
  3522. return (void *)p;
  3523. }
  3524. /* TODO: Grow the vm_area, i.e. allocate and map additional pages. */
  3525. n = __vmalloc_noprof(size, flags);
  3526. if (!n)
  3527. return NULL;
  3528. if (p) {
  3529. memcpy(n, p, old_size);
  3530. vfree(p);
  3531. }
  3532. return n;
  3533. }
  3534. #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
  3535. #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
  3536. #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
  3537. #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
  3538. #else
  3539. /*
  3540. * 64b systems should always have either DMA or DMA32 zones. For others
  3541. * GFP_DMA32 should do the right thing and use the normal zone.
  3542. */
  3543. #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
  3544. #endif
  3545. /**
  3546. * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
  3547. * @size: allocation size
  3548. *
  3549. * Allocate enough 32bit PA addressable pages to cover @size from the
  3550. * page level allocator and map them into contiguous kernel virtual space.
  3551. *
  3552. * Return: pointer to the allocated memory or %NULL on error
  3553. */
  3554. void *vmalloc_32_noprof(unsigned long size)
  3555. {
  3556. return __vmalloc_node_noprof(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
  3557. __builtin_return_address(0));
  3558. }
  3559. EXPORT_SYMBOL(vmalloc_32_noprof);
  3560. /**
  3561. * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
  3562. * @size: allocation size
  3563. *
  3564. * The resulting memory area is 32bit addressable and zeroed so it can be
  3565. * mapped to userspace without leaking data.
  3566. *
  3567. * Return: pointer to the allocated memory or %NULL on error
  3568. */
  3569. void *vmalloc_32_user_noprof(unsigned long size)
  3570. {
  3571. return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END,
  3572. GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
  3573. VM_USERMAP, NUMA_NO_NODE,
  3574. __builtin_return_address(0));
  3575. }
  3576. EXPORT_SYMBOL(vmalloc_32_user_noprof);
  3577. /*
  3578. * Atomically zero bytes in the iterator.
  3579. *
  3580. * Returns the number of zeroed bytes.
  3581. */
  3582. static size_t zero_iter(struct iov_iter *iter, size_t count)
  3583. {
  3584. size_t remains = count;
  3585. while (remains > 0) {
  3586. size_t num, copied;
  3587. num = min_t(size_t, remains, PAGE_SIZE);
  3588. copied = copy_page_to_iter_nofault(ZERO_PAGE(0), 0, num, iter);
  3589. remains -= copied;
  3590. if (copied < num)
  3591. break;
  3592. }
  3593. return count - remains;
  3594. }
  3595. /*
  3596. * small helper routine, copy contents to iter from addr.
  3597. * If the page is not present, fill zero.
  3598. *
  3599. * Returns the number of copied bytes.
  3600. */
  3601. static size_t aligned_vread_iter(struct iov_iter *iter,
  3602. const char *addr, size_t count)
  3603. {
  3604. size_t remains = count;
  3605. struct page *page;
  3606. while (remains > 0) {
  3607. unsigned long offset, length;
  3608. size_t copied = 0;
  3609. offset = offset_in_page(addr);
  3610. length = PAGE_SIZE - offset;
  3611. if (length > remains)
  3612. length = remains;
  3613. page = vmalloc_to_page(addr);
  3614. /*
  3615. * To do safe access to this _mapped_ area, we need lock. But
  3616. * adding lock here means that we need to add overhead of
  3617. * vmalloc()/vfree() calls for this _debug_ interface, rarely
  3618. * used. Instead of that, we'll use an local mapping via
  3619. * copy_page_to_iter_nofault() and accept a small overhead in
  3620. * this access function.
  3621. */
  3622. if (page)
  3623. copied = copy_page_to_iter_nofault(page, offset,
  3624. length, iter);
  3625. else
  3626. copied = zero_iter(iter, length);
  3627. addr += copied;
  3628. remains -= copied;
  3629. if (copied != length)
  3630. break;
  3631. }
  3632. return count - remains;
  3633. }
  3634. /*
  3635. * Read from a vm_map_ram region of memory.
  3636. *
  3637. * Returns the number of copied bytes.
  3638. */
  3639. static size_t vmap_ram_vread_iter(struct iov_iter *iter, const char *addr,
  3640. size_t count, unsigned long flags)
  3641. {
  3642. char *start;
  3643. struct vmap_block *vb;
  3644. struct xarray *xa;
  3645. unsigned long offset;
  3646. unsigned int rs, re;
  3647. size_t remains, n;
  3648. /*
  3649. * If it's area created by vm_map_ram() interface directly, but
  3650. * not further subdividing and delegating management to vmap_block,
  3651. * handle it here.
  3652. */
  3653. if (!(flags & VMAP_BLOCK))
  3654. return aligned_vread_iter(iter, addr, count);
  3655. remains = count;
  3656. /*
  3657. * Area is split into regions and tracked with vmap_block, read out
  3658. * each region and zero fill the hole between regions.
  3659. */
  3660. xa = addr_to_vb_xa((unsigned long) addr);
  3661. vb = xa_load(xa, addr_to_vb_idx((unsigned long)addr));
  3662. if (!vb)
  3663. goto finished_zero;
  3664. spin_lock(&vb->lock);
  3665. if (bitmap_empty(vb->used_map, VMAP_BBMAP_BITS)) {
  3666. spin_unlock(&vb->lock);
  3667. goto finished_zero;
  3668. }
  3669. for_each_set_bitrange(rs, re, vb->used_map, VMAP_BBMAP_BITS) {
  3670. size_t copied;
  3671. if (remains == 0)
  3672. goto finished;
  3673. start = vmap_block_vaddr(vb->va->va_start, rs);
  3674. if (addr < start) {
  3675. size_t to_zero = min_t(size_t, start - addr, remains);
  3676. size_t zeroed = zero_iter(iter, to_zero);
  3677. addr += zeroed;
  3678. remains -= zeroed;
  3679. if (remains == 0 || zeroed != to_zero)
  3680. goto finished;
  3681. }
  3682. /*it could start reading from the middle of used region*/
  3683. offset = offset_in_page(addr);
  3684. n = ((re - rs + 1) << PAGE_SHIFT) - offset;
  3685. if (n > remains)
  3686. n = remains;
  3687. copied = aligned_vread_iter(iter, start + offset, n);
  3688. addr += copied;
  3689. remains -= copied;
  3690. if (copied != n)
  3691. goto finished;
  3692. }
  3693. spin_unlock(&vb->lock);
  3694. finished_zero:
  3695. /* zero-fill the left dirty or free regions */
  3696. return count - remains + zero_iter(iter, remains);
  3697. finished:
  3698. /* We couldn't copy/zero everything */
  3699. spin_unlock(&vb->lock);
  3700. return count - remains;
  3701. }
  3702. /**
  3703. * vread_iter() - read vmalloc area in a safe way to an iterator.
  3704. * @iter: the iterator to which data should be written.
  3705. * @addr: vm address.
  3706. * @count: number of bytes to be read.
  3707. *
  3708. * This function checks that addr is a valid vmalloc'ed area, and
  3709. * copy data from that area to a given buffer. If the given memory range
  3710. * of [addr...addr+count) includes some valid address, data is copied to
  3711. * proper area of @buf. If there are memory holes, they'll be zero-filled.
  3712. * IOREMAP area is treated as memory hole and no copy is done.
  3713. *
  3714. * If [addr...addr+count) doesn't includes any intersects with alive
  3715. * vm_struct area, returns 0. @buf should be kernel's buffer.
  3716. *
  3717. * Note: In usual ops, vread() is never necessary because the caller
  3718. * should know vmalloc() area is valid and can use memcpy().
  3719. * This is for routines which have to access vmalloc area without
  3720. * any information, as /proc/kcore.
  3721. *
  3722. * Return: number of bytes for which addr and buf should be increased
  3723. * (same number as @count) or %0 if [addr...addr+count) doesn't
  3724. * include any intersection with valid vmalloc area
  3725. */
  3726. long vread_iter(struct iov_iter *iter, const char *addr, size_t count)
  3727. {
  3728. struct vmap_node *vn;
  3729. struct vmap_area *va;
  3730. struct vm_struct *vm;
  3731. char *vaddr;
  3732. size_t n, size, flags, remains;
  3733. unsigned long next;
  3734. addr = kasan_reset_tag(addr);
  3735. /* Don't allow overflow */
  3736. if ((unsigned long) addr + count < count)
  3737. count = -(unsigned long) addr;
  3738. remains = count;
  3739. vn = find_vmap_area_exceed_addr_lock((unsigned long) addr, &va);
  3740. if (!vn)
  3741. goto finished_zero;
  3742. /* no intersects with alive vmap_area */
  3743. if ((unsigned long)addr + remains <= va->va_start)
  3744. goto finished_zero;
  3745. do {
  3746. size_t copied;
  3747. if (remains == 0)
  3748. goto finished;
  3749. vm = va->vm;
  3750. flags = va->flags & VMAP_FLAGS_MASK;
  3751. /*
  3752. * VMAP_BLOCK indicates a sub-type of vm_map_ram area, need
  3753. * be set together with VMAP_RAM.
  3754. */
  3755. WARN_ON(flags == VMAP_BLOCK);
  3756. if (!vm && !flags)
  3757. goto next_va;
  3758. if (vm && (vm->flags & VM_UNINITIALIZED))
  3759. goto next_va;
  3760. /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
  3761. smp_rmb();
  3762. vaddr = (char *) va->va_start;
  3763. size = vm ? get_vm_area_size(vm) : va_size(va);
  3764. if (addr >= vaddr + size)
  3765. goto next_va;
  3766. if (addr < vaddr) {
  3767. size_t to_zero = min_t(size_t, vaddr - addr, remains);
  3768. size_t zeroed = zero_iter(iter, to_zero);
  3769. addr += zeroed;
  3770. remains -= zeroed;
  3771. if (remains == 0 || zeroed != to_zero)
  3772. goto finished;
  3773. }
  3774. n = vaddr + size - addr;
  3775. if (n > remains)
  3776. n = remains;
  3777. if (flags & VMAP_RAM)
  3778. copied = vmap_ram_vread_iter(iter, addr, n, flags);
  3779. else if (!(vm && (vm->flags & (VM_IOREMAP | VM_SPARSE))))
  3780. copied = aligned_vread_iter(iter, addr, n);
  3781. else /* IOREMAP | SPARSE area is treated as memory hole */
  3782. copied = zero_iter(iter, n);
  3783. addr += copied;
  3784. remains -= copied;
  3785. if (copied != n)
  3786. goto finished;
  3787. next_va:
  3788. next = va->va_end;
  3789. spin_unlock(&vn->busy.lock);
  3790. } while ((vn = find_vmap_area_exceed_addr_lock(next, &va)));
  3791. finished_zero:
  3792. if (vn)
  3793. spin_unlock(&vn->busy.lock);
  3794. /* zero-fill memory holes */
  3795. return count - remains + zero_iter(iter, remains);
  3796. finished:
  3797. /* Nothing remains, or We couldn't copy/zero everything. */
  3798. if (vn)
  3799. spin_unlock(&vn->busy.lock);
  3800. return count - remains;
  3801. }
  3802. /**
  3803. * remap_vmalloc_range_partial - map vmalloc pages to userspace
  3804. * @vma: vma to cover
  3805. * @uaddr: target user address to start at
  3806. * @kaddr: virtual address of vmalloc kernel memory
  3807. * @pgoff: offset from @kaddr to start at
  3808. * @size: size of map area
  3809. *
  3810. * Returns: 0 for success, -Exxx on failure
  3811. *
  3812. * This function checks that @kaddr is a valid vmalloc'ed area,
  3813. * and that it is big enough to cover the range starting at
  3814. * @uaddr in @vma. Will return failure if that criteria isn't
  3815. * met.
  3816. *
  3817. * Similar to remap_pfn_range() (see mm/memory.c)
  3818. */
  3819. int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
  3820. void *kaddr, unsigned long pgoff,
  3821. unsigned long size)
  3822. {
  3823. struct vm_struct *area;
  3824. unsigned long off;
  3825. unsigned long end_index;
  3826. if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
  3827. return -EINVAL;
  3828. size = PAGE_ALIGN(size);
  3829. if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
  3830. return -EINVAL;
  3831. area = find_vm_area(kaddr);
  3832. if (!area)
  3833. return -EINVAL;
  3834. if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
  3835. return -EINVAL;
  3836. if (check_add_overflow(size, off, &end_index) ||
  3837. end_index > get_vm_area_size(area))
  3838. return -EINVAL;
  3839. kaddr += off;
  3840. do {
  3841. struct page *page = vmalloc_to_page(kaddr);
  3842. int ret;
  3843. ret = vm_insert_page(vma, uaddr, page);
  3844. if (ret)
  3845. return ret;
  3846. uaddr += PAGE_SIZE;
  3847. kaddr += PAGE_SIZE;
  3848. size -= PAGE_SIZE;
  3849. } while (size > 0);
  3850. vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
  3851. return 0;
  3852. }
  3853. /**
  3854. * remap_vmalloc_range - map vmalloc pages to userspace
  3855. * @vma: vma to cover (map full range of vma)
  3856. * @addr: vmalloc memory
  3857. * @pgoff: number of pages into addr before first page to map
  3858. *
  3859. * Returns: 0 for success, -Exxx on failure
  3860. *
  3861. * This function checks that addr is a valid vmalloc'ed area, and
  3862. * that it is big enough to cover the vma. Will return failure if
  3863. * that criteria isn't met.
  3864. *
  3865. * Similar to remap_pfn_range() (see mm/memory.c)
  3866. */
  3867. int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
  3868. unsigned long pgoff)
  3869. {
  3870. return remap_vmalloc_range_partial(vma, vma->vm_start,
  3871. addr, pgoff,
  3872. vma->vm_end - vma->vm_start);
  3873. }
  3874. EXPORT_SYMBOL(remap_vmalloc_range);
  3875. void free_vm_area(struct vm_struct *area)
  3876. {
  3877. struct vm_struct *ret;
  3878. ret = remove_vm_area(area->addr);
  3879. BUG_ON(ret != area);
  3880. kfree(area);
  3881. }
  3882. EXPORT_SYMBOL_GPL(free_vm_area);
  3883. #ifdef CONFIG_SMP
  3884. static struct vmap_area *node_to_va(struct rb_node *n)
  3885. {
  3886. return rb_entry_safe(n, struct vmap_area, rb_node);
  3887. }
  3888. /**
  3889. * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
  3890. * @addr: target address
  3891. *
  3892. * Returns: vmap_area if it is found. If there is no such area
  3893. * the first highest(reverse order) vmap_area is returned
  3894. * i.e. va->va_start < addr && va->va_end < addr or NULL
  3895. * if there are no any areas before @addr.
  3896. */
  3897. static struct vmap_area *
  3898. pvm_find_va_enclose_addr(unsigned long addr)
  3899. {
  3900. struct vmap_area *va, *tmp;
  3901. struct rb_node *n;
  3902. n = free_vmap_area_root.rb_node;
  3903. va = NULL;
  3904. while (n) {
  3905. tmp = rb_entry(n, struct vmap_area, rb_node);
  3906. if (tmp->va_start <= addr) {
  3907. va = tmp;
  3908. if (tmp->va_end >= addr)
  3909. break;
  3910. n = n->rb_right;
  3911. } else {
  3912. n = n->rb_left;
  3913. }
  3914. }
  3915. return va;
  3916. }
  3917. /**
  3918. * pvm_determine_end_from_reverse - find the highest aligned address
  3919. * of free block below VMALLOC_END
  3920. * @va:
  3921. * in - the VA we start the search(reverse order);
  3922. * out - the VA with the highest aligned end address.
  3923. * @align: alignment for required highest address
  3924. *
  3925. * Returns: determined end address within vmap_area
  3926. */
  3927. static unsigned long
  3928. pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
  3929. {
  3930. unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
  3931. unsigned long addr;
  3932. if (likely(*va)) {
  3933. list_for_each_entry_from_reverse((*va),
  3934. &free_vmap_area_list, list) {
  3935. addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
  3936. if ((*va)->va_start < addr)
  3937. return addr;
  3938. }
  3939. }
  3940. return 0;
  3941. }
  3942. /**
  3943. * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
  3944. * @offsets: array containing offset of each area
  3945. * @sizes: array containing size of each area
  3946. * @nr_vms: the number of areas to allocate
  3947. * @align: alignment, all entries in @offsets and @sizes must be aligned to this
  3948. *
  3949. * Returns: kmalloc'd vm_struct pointer array pointing to allocated
  3950. * vm_structs on success, %NULL on failure
  3951. *
  3952. * Percpu allocator wants to use congruent vm areas so that it can
  3953. * maintain the offsets among percpu areas. This function allocates
  3954. * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
  3955. * be scattered pretty far, distance between two areas easily going up
  3956. * to gigabytes. To avoid interacting with regular vmallocs, these
  3957. * areas are allocated from top.
  3958. *
  3959. * Despite its complicated look, this allocator is rather simple. It
  3960. * does everything top-down and scans free blocks from the end looking
  3961. * for matching base. While scanning, if any of the areas do not fit the
  3962. * base address is pulled down to fit the area. Scanning is repeated till
  3963. * all the areas fit and then all necessary data structures are inserted
  3964. * and the result is returned.
  3965. */
  3966. struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
  3967. const size_t *sizes, int nr_vms,
  3968. size_t align)
  3969. {
  3970. const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
  3971. const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
  3972. struct vmap_area **vas, *va;
  3973. struct vm_struct **vms;
  3974. int area, area2, last_area, term_area;
  3975. unsigned long base, start, size, end, last_end, orig_start, orig_end;
  3976. bool purged = false;
  3977. /* verify parameters and allocate data structures */
  3978. BUG_ON(offset_in_page(align) || !is_power_of_2(align));
  3979. for (last_area = 0, area = 0; area < nr_vms; area++) {
  3980. start = offsets[area];
  3981. end = start + sizes[area];
  3982. /* is everything aligned properly? */
  3983. BUG_ON(!IS_ALIGNED(offsets[area], align));
  3984. BUG_ON(!IS_ALIGNED(sizes[area], align));
  3985. /* detect the area with the highest address */
  3986. if (start > offsets[last_area])
  3987. last_area = area;
  3988. for (area2 = area + 1; area2 < nr_vms; area2++) {
  3989. unsigned long start2 = offsets[area2];
  3990. unsigned long end2 = start2 + sizes[area2];
  3991. BUG_ON(start2 < end && start < end2);
  3992. }
  3993. }
  3994. last_end = offsets[last_area] + sizes[last_area];
  3995. if (vmalloc_end - vmalloc_start < last_end) {
  3996. WARN_ON(true);
  3997. return NULL;
  3998. }
  3999. vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
  4000. vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
  4001. if (!vas || !vms)
  4002. goto err_free2;
  4003. for (area = 0; area < nr_vms; area++) {
  4004. vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
  4005. vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
  4006. if (!vas[area] || !vms[area])
  4007. goto err_free;
  4008. }
  4009. retry:
  4010. spin_lock(&free_vmap_area_lock);
  4011. /* start scanning - we scan from the top, begin with the last area */
  4012. area = term_area = last_area;
  4013. start = offsets[area];
  4014. end = start + sizes[area];
  4015. va = pvm_find_va_enclose_addr(vmalloc_end);
  4016. base = pvm_determine_end_from_reverse(&va, align) - end;
  4017. while (true) {
  4018. /*
  4019. * base might have underflowed, add last_end before
  4020. * comparing.
  4021. */
  4022. if (base + last_end < vmalloc_start + last_end)
  4023. goto overflow;
  4024. /*
  4025. * Fitting base has not been found.
  4026. */
  4027. if (va == NULL)
  4028. goto overflow;
  4029. /*
  4030. * If required width exceeds current VA block, move
  4031. * base downwards and then recheck.
  4032. */
  4033. if (base + end > va->va_end) {
  4034. base = pvm_determine_end_from_reverse(&va, align) - end;
  4035. term_area = area;
  4036. continue;
  4037. }
  4038. /*
  4039. * If this VA does not fit, move base downwards and recheck.
  4040. */
  4041. if (base + start < va->va_start) {
  4042. va = node_to_va(rb_prev(&va->rb_node));
  4043. base = pvm_determine_end_from_reverse(&va, align) - end;
  4044. term_area = area;
  4045. continue;
  4046. }
  4047. /*
  4048. * This area fits, move on to the previous one. If
  4049. * the previous one is the terminal one, we're done.
  4050. */
  4051. area = (area + nr_vms - 1) % nr_vms;
  4052. if (area == term_area)
  4053. break;
  4054. start = offsets[area];
  4055. end = start + sizes[area];
  4056. va = pvm_find_va_enclose_addr(base + end);
  4057. }
  4058. /* we've found a fitting base, insert all va's */
  4059. for (area = 0; area < nr_vms; area++) {
  4060. int ret;
  4061. start = base + offsets[area];
  4062. size = sizes[area];
  4063. va = pvm_find_va_enclose_addr(start);
  4064. if (WARN_ON_ONCE(va == NULL))
  4065. /* It is a BUG(), but trigger recovery instead. */
  4066. goto recovery;
  4067. ret = va_clip(&free_vmap_area_root,
  4068. &free_vmap_area_list, va, start, size);
  4069. if (WARN_ON_ONCE(unlikely(ret)))
  4070. /* It is a BUG(), but trigger recovery instead. */
  4071. goto recovery;
  4072. /* Allocated area. */
  4073. va = vas[area];
  4074. va->va_start = start;
  4075. va->va_end = start + size;
  4076. }
  4077. spin_unlock(&free_vmap_area_lock);
  4078. /* populate the kasan shadow space */
  4079. for (area = 0; area < nr_vms; area++) {
  4080. if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area]))
  4081. goto err_free_shadow;
  4082. }
  4083. /* insert all vm's */
  4084. for (area = 0; area < nr_vms; area++) {
  4085. struct vmap_node *vn = addr_to_node(vas[area]->va_start);
  4086. spin_lock(&vn->busy.lock);
  4087. insert_vmap_area(vas[area], &vn->busy.root, &vn->busy.head);
  4088. setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
  4089. pcpu_get_vm_areas);
  4090. spin_unlock(&vn->busy.lock);
  4091. }
  4092. /*
  4093. * Mark allocated areas as accessible. Do it now as a best-effort
  4094. * approach, as they can be mapped outside of vmalloc code.
  4095. * With hardware tag-based KASAN, marking is skipped for
  4096. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  4097. */
  4098. for (area = 0; area < nr_vms; area++)
  4099. vms[area]->addr = kasan_unpoison_vmalloc(vms[area]->addr,
  4100. vms[area]->size, KASAN_VMALLOC_PROT_NORMAL);
  4101. kfree(vas);
  4102. return vms;
  4103. recovery:
  4104. /*
  4105. * Remove previously allocated areas. There is no
  4106. * need in removing these areas from the busy tree,
  4107. * because they are inserted only on the final step
  4108. * and when pcpu_get_vm_areas() is success.
  4109. */
  4110. while (area--) {
  4111. orig_start = vas[area]->va_start;
  4112. orig_end = vas[area]->va_end;
  4113. va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
  4114. &free_vmap_area_list);
  4115. if (va)
  4116. kasan_release_vmalloc(orig_start, orig_end,
  4117. va->va_start, va->va_end,
  4118. KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH);
  4119. vas[area] = NULL;
  4120. }
  4121. overflow:
  4122. spin_unlock(&free_vmap_area_lock);
  4123. if (!purged) {
  4124. reclaim_and_purge_vmap_areas();
  4125. purged = true;
  4126. /* Before "retry", check if we recover. */
  4127. for (area = 0; area < nr_vms; area++) {
  4128. if (vas[area])
  4129. continue;
  4130. vas[area] = kmem_cache_zalloc(
  4131. vmap_area_cachep, GFP_KERNEL);
  4132. if (!vas[area])
  4133. goto err_free;
  4134. }
  4135. goto retry;
  4136. }
  4137. err_free:
  4138. for (area = 0; area < nr_vms; area++) {
  4139. if (vas[area])
  4140. kmem_cache_free(vmap_area_cachep, vas[area]);
  4141. kfree(vms[area]);
  4142. }
  4143. err_free2:
  4144. kfree(vas);
  4145. kfree(vms);
  4146. return NULL;
  4147. err_free_shadow:
  4148. spin_lock(&free_vmap_area_lock);
  4149. /*
  4150. * We release all the vmalloc shadows, even the ones for regions that
  4151. * hadn't been successfully added. This relies on kasan_release_vmalloc
  4152. * being able to tolerate this case.
  4153. */
  4154. for (area = 0; area < nr_vms; area++) {
  4155. orig_start = vas[area]->va_start;
  4156. orig_end = vas[area]->va_end;
  4157. va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
  4158. &free_vmap_area_list);
  4159. if (va)
  4160. kasan_release_vmalloc(orig_start, orig_end,
  4161. va->va_start, va->va_end,
  4162. KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH);
  4163. vas[area] = NULL;
  4164. kfree(vms[area]);
  4165. }
  4166. spin_unlock(&free_vmap_area_lock);
  4167. kfree(vas);
  4168. kfree(vms);
  4169. return NULL;
  4170. }
  4171. /**
  4172. * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
  4173. * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
  4174. * @nr_vms: the number of allocated areas
  4175. *
  4176. * Free vm_structs and the array allocated by pcpu_get_vm_areas().
  4177. */
  4178. void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
  4179. {
  4180. int i;
  4181. for (i = 0; i < nr_vms; i++)
  4182. free_vm_area(vms[i]);
  4183. kfree(vms);
  4184. }
  4185. #endif /* CONFIG_SMP */
  4186. #ifdef CONFIG_PRINTK
  4187. bool vmalloc_dump_obj(void *object)
  4188. {
  4189. const void *caller;
  4190. struct vm_struct *vm;
  4191. struct vmap_area *va;
  4192. struct vmap_node *vn;
  4193. unsigned long addr;
  4194. unsigned int nr_pages;
  4195. addr = PAGE_ALIGN((unsigned long) object);
  4196. vn = addr_to_node(addr);
  4197. if (!spin_trylock(&vn->busy.lock))
  4198. return false;
  4199. va = __find_vmap_area(addr, &vn->busy.root);
  4200. if (!va || !va->vm) {
  4201. spin_unlock(&vn->busy.lock);
  4202. return false;
  4203. }
  4204. vm = va->vm;
  4205. addr = (unsigned long) vm->addr;
  4206. caller = vm->caller;
  4207. nr_pages = vm->nr_pages;
  4208. spin_unlock(&vn->busy.lock);
  4209. pr_cont(" %u-page vmalloc region starting at %#lx allocated at %pS\n",
  4210. nr_pages, addr, caller);
  4211. return true;
  4212. }
  4213. #endif
  4214. #ifdef CONFIG_PROC_FS
  4215. /*
  4216. * Print number of pages allocated on each memory node.
  4217. *
  4218. * This function can only be called if CONFIG_NUMA is enabled
  4219. * and VM_UNINITIALIZED bit in v->flags is disabled.
  4220. */
  4221. static void show_numa_info(struct seq_file *m, struct vm_struct *v,
  4222. unsigned int *counters)
  4223. {
  4224. unsigned int nr;
  4225. unsigned int step = 1U << vm_area_page_order(v);
  4226. if (!counters)
  4227. return;
  4228. memset(counters, 0, nr_node_ids * sizeof(unsigned int));
  4229. for (nr = 0; nr < v->nr_pages; nr += step)
  4230. counters[page_to_nid(v->pages[nr])] += step;
  4231. for_each_node_state(nr, N_HIGH_MEMORY)
  4232. if (counters[nr])
  4233. seq_printf(m, " N%u=%u", nr, counters[nr]);
  4234. }
  4235. static void show_purge_info(struct seq_file *m)
  4236. {
  4237. struct vmap_node *vn;
  4238. struct vmap_area *va;
  4239. int i;
  4240. for (i = 0; i < nr_vmap_nodes; i++) {
  4241. vn = &vmap_nodes[i];
  4242. spin_lock(&vn->lazy.lock);
  4243. list_for_each_entry(va, &vn->lazy.head, list) {
  4244. seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
  4245. (void *)va->va_start, (void *)va->va_end,
  4246. va_size(va));
  4247. }
  4248. spin_unlock(&vn->lazy.lock);
  4249. }
  4250. }
  4251. static int vmalloc_info_show(struct seq_file *m, void *p)
  4252. {
  4253. struct vmap_node *vn;
  4254. struct vmap_area *va;
  4255. struct vm_struct *v;
  4256. int i;
  4257. unsigned int *counters;
  4258. if (IS_ENABLED(CONFIG_NUMA))
  4259. counters = kmalloc(nr_node_ids * sizeof(unsigned int), GFP_KERNEL);
  4260. for (i = 0; i < nr_vmap_nodes; i++) {
  4261. vn = &vmap_nodes[i];
  4262. spin_lock(&vn->busy.lock);
  4263. list_for_each_entry(va, &vn->busy.head, list) {
  4264. if (!va->vm) {
  4265. if (va->flags & VMAP_RAM)
  4266. seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
  4267. (void *)va->va_start, (void *)va->va_end,
  4268. va_size(va));
  4269. continue;
  4270. }
  4271. v = va->vm;
  4272. if (v->flags & VM_UNINITIALIZED)
  4273. continue;
  4274. /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
  4275. smp_rmb();
  4276. seq_printf(m, "0x%pK-0x%pK %7ld",
  4277. v->addr, v->addr + v->size, v->size);
  4278. if (v->caller)
  4279. seq_printf(m, " %pS", v->caller);
  4280. if (v->nr_pages)
  4281. seq_printf(m, " pages=%d", v->nr_pages);
  4282. if (v->phys_addr)
  4283. seq_printf(m, " phys=%pa", &v->phys_addr);
  4284. if (v->flags & VM_IOREMAP)
  4285. seq_puts(m, " ioremap");
  4286. if (v->flags & VM_SPARSE)
  4287. seq_puts(m, " sparse");
  4288. if (v->flags & VM_ALLOC)
  4289. seq_puts(m, " vmalloc");
  4290. if (v->flags & VM_MAP)
  4291. seq_puts(m, " vmap");
  4292. if (v->flags & VM_USERMAP)
  4293. seq_puts(m, " user");
  4294. if (v->flags & VM_DMA_COHERENT)
  4295. seq_puts(m, " dma-coherent");
  4296. if (is_vmalloc_addr(v->pages))
  4297. seq_puts(m, " vpages");
  4298. if (IS_ENABLED(CONFIG_NUMA))
  4299. show_numa_info(m, v, counters);
  4300. seq_putc(m, '\n');
  4301. }
  4302. spin_unlock(&vn->busy.lock);
  4303. }
  4304. /*
  4305. * As a final step, dump "unpurged" areas.
  4306. */
  4307. show_purge_info(m);
  4308. if (IS_ENABLED(CONFIG_NUMA))
  4309. kfree(counters);
  4310. return 0;
  4311. }
  4312. static int __init proc_vmalloc_init(void)
  4313. {
  4314. proc_create_single("vmallocinfo", 0400, NULL, vmalloc_info_show);
  4315. return 0;
  4316. }
  4317. module_init(proc_vmalloc_init);
  4318. #endif
  4319. static void __init vmap_init_free_space(void)
  4320. {
  4321. unsigned long vmap_start = 1;
  4322. const unsigned long vmap_end = ULONG_MAX;
  4323. struct vmap_area *free;
  4324. struct vm_struct *busy;
  4325. /*
  4326. * B F B B B F
  4327. * -|-----|.....|-----|-----|-----|.....|-
  4328. * | The KVA space |
  4329. * |<--------------------------------->|
  4330. */
  4331. for (busy = vmlist; busy; busy = busy->next) {
  4332. if ((unsigned long) busy->addr - vmap_start > 0) {
  4333. free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4334. if (!WARN_ON_ONCE(!free)) {
  4335. free->va_start = vmap_start;
  4336. free->va_end = (unsigned long) busy->addr;
  4337. insert_vmap_area_augment(free, NULL,
  4338. &free_vmap_area_root,
  4339. &free_vmap_area_list);
  4340. }
  4341. }
  4342. vmap_start = (unsigned long) busy->addr + busy->size;
  4343. }
  4344. if (vmap_end - vmap_start > 0) {
  4345. free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4346. if (!WARN_ON_ONCE(!free)) {
  4347. free->va_start = vmap_start;
  4348. free->va_end = vmap_end;
  4349. insert_vmap_area_augment(free, NULL,
  4350. &free_vmap_area_root,
  4351. &free_vmap_area_list);
  4352. }
  4353. }
  4354. }
  4355. static void vmap_init_nodes(void)
  4356. {
  4357. struct vmap_node *vn;
  4358. int i, n;
  4359. #if BITS_PER_LONG == 64
  4360. /*
  4361. * A high threshold of max nodes is fixed and bound to 128,
  4362. * thus a scale factor is 1 for systems where number of cores
  4363. * are less or equal to specified threshold.
  4364. *
  4365. * As for NUMA-aware notes. For bigger systems, for example
  4366. * NUMA with multi-sockets, where we can end-up with thousands
  4367. * of cores in total, a "sub-numa-clustering" should be added.
  4368. *
  4369. * In this case a NUMA domain is considered as a single entity
  4370. * with dedicated sub-nodes in it which describe one group or
  4371. * set of cores. Therefore a per-domain purging is supposed to
  4372. * be added as well as a per-domain balancing.
  4373. */
  4374. n = clamp_t(unsigned int, num_possible_cpus(), 1, 128);
  4375. if (n > 1) {
  4376. vn = kmalloc_array(n, sizeof(*vn), GFP_NOWAIT | __GFP_NOWARN);
  4377. if (vn) {
  4378. /* Node partition is 16 pages. */
  4379. vmap_zone_size = (1 << 4) * PAGE_SIZE;
  4380. nr_vmap_nodes = n;
  4381. vmap_nodes = vn;
  4382. } else {
  4383. pr_err("Failed to allocate an array. Disable a node layer\n");
  4384. }
  4385. }
  4386. #endif
  4387. for (n = 0; n < nr_vmap_nodes; n++) {
  4388. vn = &vmap_nodes[n];
  4389. vn->busy.root = RB_ROOT;
  4390. INIT_LIST_HEAD(&vn->busy.head);
  4391. spin_lock_init(&vn->busy.lock);
  4392. vn->lazy.root = RB_ROOT;
  4393. INIT_LIST_HEAD(&vn->lazy.head);
  4394. spin_lock_init(&vn->lazy.lock);
  4395. for (i = 0; i < MAX_VA_SIZE_PAGES; i++) {
  4396. INIT_LIST_HEAD(&vn->pool[i].head);
  4397. WRITE_ONCE(vn->pool[i].len, 0);
  4398. }
  4399. spin_lock_init(&vn->pool_lock);
  4400. }
  4401. }
  4402. static unsigned long
  4403. vmap_node_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  4404. {
  4405. unsigned long count;
  4406. struct vmap_node *vn;
  4407. int i, j;
  4408. for (count = 0, i = 0; i < nr_vmap_nodes; i++) {
  4409. vn = &vmap_nodes[i];
  4410. for (j = 0; j < MAX_VA_SIZE_PAGES; j++)
  4411. count += READ_ONCE(vn->pool[j].len);
  4412. }
  4413. return count ? count : SHRINK_EMPTY;
  4414. }
  4415. static unsigned long
  4416. vmap_node_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  4417. {
  4418. int i;
  4419. for (i = 0; i < nr_vmap_nodes; i++)
  4420. decay_va_pool_node(&vmap_nodes[i], true);
  4421. return SHRINK_STOP;
  4422. }
  4423. void __init vmalloc_init(void)
  4424. {
  4425. struct shrinker *vmap_node_shrinker;
  4426. struct vmap_area *va;
  4427. struct vmap_node *vn;
  4428. struct vm_struct *tmp;
  4429. int i;
  4430. /*
  4431. * Create the cache for vmap_area objects.
  4432. */
  4433. vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
  4434. for_each_possible_cpu(i) {
  4435. struct vmap_block_queue *vbq;
  4436. struct vfree_deferred *p;
  4437. vbq = &per_cpu(vmap_block_queue, i);
  4438. spin_lock_init(&vbq->lock);
  4439. INIT_LIST_HEAD(&vbq->free);
  4440. p = &per_cpu(vfree_deferred, i);
  4441. init_llist_head(&p->list);
  4442. INIT_WORK(&p->wq, delayed_vfree_work);
  4443. xa_init(&vbq->vmap_blocks);
  4444. }
  4445. /*
  4446. * Setup nodes before importing vmlist.
  4447. */
  4448. vmap_init_nodes();
  4449. /* Import existing vmlist entries. */
  4450. for (tmp = vmlist; tmp; tmp = tmp->next) {
  4451. va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4452. if (WARN_ON_ONCE(!va))
  4453. continue;
  4454. va->va_start = (unsigned long)tmp->addr;
  4455. va->va_end = va->va_start + tmp->size;
  4456. va->vm = tmp;
  4457. vn = addr_to_node(va->va_start);
  4458. insert_vmap_area(va, &vn->busy.root, &vn->busy.head);
  4459. }
  4460. /*
  4461. * Now we can initialize a free vmap space.
  4462. */
  4463. vmap_init_free_space();
  4464. vmap_initialized = true;
  4465. vmap_node_shrinker = shrinker_alloc(0, "vmap-node");
  4466. if (!vmap_node_shrinker) {
  4467. pr_err("Failed to allocate vmap-node shrinker!\n");
  4468. return;
  4469. }
  4470. vmap_node_shrinker->count_objects = vmap_node_shrink_count;
  4471. vmap_node_shrinker->scan_objects = vmap_node_shrink_scan;
  4472. shrinker_register(vmap_node_shrinker);
  4473. }