uma_core.c 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981
  1. /*-
  2. * SPDX-License-Identifier: BSD-2-Clause
  3. *
  4. * Copyright (c) 2002-2019 Jeffrey Roberson <jeff@FreeBSD.org>
  5. * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
  6. * Copyright (c) 2004-2006 Robert N. M. Watson
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice unmodified, this list of conditions, and the following
  14. * disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  21. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  23. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  24. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /*
  31. * uma_core.c Implementation of the Universal Memory allocator
  32. *
  33. * This allocator is intended to replace the multitude of similar object caches
  34. * in the standard FreeBSD kernel. The intent is to be flexible as well as
  35. * efficient. A primary design goal is to return unused memory to the rest of
  36. * the system. This will make the system as a whole more flexible due to the
  37. * ability to move memory to subsystems which most need it instead of leaving
  38. * pools of reserved memory unused.
  39. *
  40. * The basic ideas stem from similar slab/zone based allocators whose algorithms
  41. * are well known.
  42. *
  43. */
  44. /*
  45. * TODO:
  46. * - Improve memory usage for large allocations
  47. * - Investigate cache size adjustments
  48. */
  49. #include <sys/cdefs.h>
  50. #include "opt_ddb.h"
  51. #include "opt_param.h"
  52. #include "opt_vm.h"
  53. #include <sys/param.h>
  54. #include <sys/systm.h>
  55. #include <sys/asan.h>
  56. #include <sys/bitset.h>
  57. #include <sys/domainset.h>
  58. #include <sys/eventhandler.h>
  59. #include <sys/kernel.h>
  60. #include <sys/types.h>
  61. #include <sys/limits.h>
  62. #include <sys/queue.h>
  63. #include <sys/malloc.h>
  64. #include <sys/ktr.h>
  65. #include <sys/lock.h>
  66. #include <sys/msan.h>
  67. #include <sys/mutex.h>
  68. #include <sys/proc.h>
  69. #include <sys/random.h>
  70. #include <sys/rwlock.h>
  71. #include <sys/sbuf.h>
  72. #include <sys/sched.h>
  73. #include <sys/sleepqueue.h>
  74. #include <sys/smp.h>
  75. #include <sys/smr.h>
  76. #include <sys/sysctl.h>
  77. #include <sys/taskqueue.h>
  78. #include <sys/vmmeter.h>
  79. #include <vm/vm.h>
  80. #include <vm/vm_param.h>
  81. #include <vm/vm_domainset.h>
  82. #include <vm/vm_object.h>
  83. #include <vm/vm_page.h>
  84. #include <vm/vm_pageout.h>
  85. #include <vm/vm_phys.h>
  86. #include <vm/vm_pagequeue.h>
  87. #include <vm/vm_map.h>
  88. #include <vm/vm_kern.h>
  89. #include <vm/vm_extern.h>
  90. #include <vm/vm_dumpset.h>
  91. #include <vm/uma.h>
  92. #include <vm/uma_int.h>
  93. #include <vm/uma_dbg.h>
  94. #include <ddb/ddb.h>
  95. #ifdef DEBUG_MEMGUARD
  96. #include <vm/memguard.h>
  97. #endif
  98. #include <machine/md_var.h>
  99. #ifdef INVARIANTS
  100. #define UMA_ALWAYS_CTORDTOR 1
  101. #else
  102. #define UMA_ALWAYS_CTORDTOR 0
  103. #endif
  104. /*
  105. * This is the zone and keg from which all zones are spawned.
  106. */
  107. static uma_zone_t kegs;
  108. static uma_zone_t zones;
  109. /*
  110. * On INVARIANTS builds, the slab contains a second bitset of the same size,
  111. * "dbg_bits", which is laid out immediately after us_free.
  112. */
  113. #ifdef INVARIANTS
  114. #define SLAB_BITSETS 2
  115. #else
  116. #define SLAB_BITSETS 1
  117. #endif
  118. /*
  119. * These are the two zones from which all offpage uma_slab_ts are allocated.
  120. *
  121. * One zone is for slab headers that can represent a larger number of items,
  122. * making the slabs themselves more efficient, and the other zone is for
  123. * headers that are smaller and represent fewer items, making the headers more
  124. * efficient.
  125. */
  126. #define SLABZONE_SIZE(setsize) \
  127. (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
  128. #define SLABZONE0_SETSIZE (PAGE_SIZE / 16)
  129. #define SLABZONE1_SETSIZE SLAB_MAX_SETSIZE
  130. #define SLABZONE0_SIZE SLABZONE_SIZE(SLABZONE0_SETSIZE)
  131. #define SLABZONE1_SIZE SLABZONE_SIZE(SLABZONE1_SETSIZE)
  132. static uma_zone_t slabzones[2];
  133. /*
  134. * The initial hash tables come out of this zone so they can be allocated
  135. * prior to malloc coming up.
  136. */
  137. static uma_zone_t hashzone;
  138. /* The boot-time adjusted value for cache line alignment. */
  139. static unsigned int uma_cache_align_mask = 64 - 1;
  140. static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
  141. static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
  142. /*
  143. * Are we allowed to allocate buckets?
  144. */
  145. static int bucketdisable = 1;
  146. /* Linked list of all kegs in the system */
  147. static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
  148. /* Linked list of all cache-only zones in the system */
  149. static LIST_HEAD(,uma_zone) uma_cachezones =
  150. LIST_HEAD_INITIALIZER(uma_cachezones);
  151. /*
  152. * Mutex for global lists: uma_kegs, uma_cachezones, and the per-keg list of
  153. * zones.
  154. */
  155. static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
  156. static struct sx uma_reclaim_lock;
  157. /*
  158. * First available virual address for boot time allocations.
  159. */
  160. static vm_offset_t bootstart;
  161. static vm_offset_t bootmem;
  162. /*
  163. * kmem soft limit, initialized by uma_set_limit(). Ensure that early
  164. * allocations don't trigger a wakeup of the reclaim thread.
  165. */
  166. unsigned long uma_kmem_limit = LONG_MAX;
  167. SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
  168. "UMA kernel memory soft limit");
  169. unsigned long uma_kmem_total;
  170. SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
  171. "UMA kernel memory usage");
  172. /* Is the VM done starting up? */
  173. static enum {
  174. BOOT_COLD,
  175. BOOT_KVA,
  176. BOOT_PCPU,
  177. BOOT_RUNNING,
  178. BOOT_SHUTDOWN,
  179. } booted = BOOT_COLD;
  180. /*
  181. * This is the handle used to schedule events that need to happen
  182. * outside of the allocation fast path.
  183. */
  184. static struct timeout_task uma_timeout_task;
  185. #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
  186. /*
  187. * This structure is passed as the zone ctor arg so that I don't have to create
  188. * a special allocation function just for zones.
  189. */
  190. struct uma_zctor_args {
  191. const char *name;
  192. size_t size;
  193. uma_ctor ctor;
  194. uma_dtor dtor;
  195. uma_init uminit;
  196. uma_fini fini;
  197. uma_import import;
  198. uma_release release;
  199. void *arg;
  200. uma_keg_t keg;
  201. int align;
  202. uint32_t flags;
  203. };
  204. struct uma_kctor_args {
  205. uma_zone_t zone;
  206. size_t size;
  207. uma_init uminit;
  208. uma_fini fini;
  209. int align;
  210. uint32_t flags;
  211. };
  212. struct uma_bucket_zone {
  213. uma_zone_t ubz_zone;
  214. const char *ubz_name;
  215. int ubz_entries; /* Number of items it can hold. */
  216. int ubz_maxsize; /* Maximum allocation size per-item. */
  217. };
  218. /*
  219. * Compute the actual number of bucket entries to pack them in power
  220. * of two sizes for more efficient space utilization.
  221. */
  222. #define BUCKET_SIZE(n) \
  223. (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
  224. #define BUCKET_MAX BUCKET_SIZE(256)
  225. struct uma_bucket_zone bucket_zones[] = {
  226. /* Literal bucket sizes. */
  227. { NULL, "2 Bucket", 2, 4096 },
  228. { NULL, "4 Bucket", 4, 3072 },
  229. { NULL, "8 Bucket", 8, 2048 },
  230. { NULL, "16 Bucket", 16, 1024 },
  231. /* Rounded down power of 2 sizes for efficiency. */
  232. { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
  233. { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
  234. { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
  235. { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
  236. { NULL, NULL, 0}
  237. };
  238. /*
  239. * Flags and enumerations to be passed to internal functions.
  240. */
  241. enum zfreeskip {
  242. SKIP_NONE = 0,
  243. SKIP_CNT = 0x00000001,
  244. SKIP_DTOR = 0x00010000,
  245. SKIP_FINI = 0x00020000,
  246. };
  247. /* Prototypes.. */
  248. void uma_startup1(vm_offset_t);
  249. void uma_startup2(void);
  250. static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
  251. static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
  252. static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
  253. static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
  254. static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
  255. static void page_free(void *, vm_size_t, uint8_t);
  256. static void pcpu_page_free(void *, vm_size_t, uint8_t);
  257. static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
  258. static void cache_drain(uma_zone_t);
  259. static void bucket_drain(uma_zone_t, uma_bucket_t);
  260. static void bucket_cache_reclaim(uma_zone_t zone, bool, int);
  261. static bool bucket_cache_reclaim_domain(uma_zone_t, bool, bool, int);
  262. static int keg_ctor(void *, int, void *, int);
  263. static void keg_dtor(void *, int, void *);
  264. static void keg_drain(uma_keg_t keg, int domain);
  265. static int zone_ctor(void *, int, void *, int);
  266. static void zone_dtor(void *, int, void *);
  267. static inline void item_dtor(uma_zone_t zone, void *item, int size,
  268. void *udata, enum zfreeskip skip);
  269. static int zero_init(void *, int, int);
  270. static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
  271. int itemdomain, bool ws);
  272. static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
  273. static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
  274. static void zone_timeout(uma_zone_t zone, void *);
  275. static int hash_alloc(struct uma_hash *, u_int);
  276. static int hash_expand(struct uma_hash *, struct uma_hash *);
  277. static void hash_free(struct uma_hash *hash);
  278. static void uma_timeout(void *, int);
  279. static void uma_shutdown(void);
  280. static void *zone_alloc_item(uma_zone_t, void *, int, int);
  281. static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
  282. static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
  283. static void zone_free_limit(uma_zone_t zone, int count);
  284. static void bucket_enable(void);
  285. static void bucket_init(void);
  286. static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
  287. static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
  288. static void bucket_zone_drain(int domain);
  289. static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
  290. static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
  291. static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
  292. static size_t slab_sizeof(int nitems);
  293. static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
  294. uma_fini fini, int align, uint32_t flags);
  295. static int zone_import(void *, void **, int, int, int);
  296. static void zone_release(void *, void **, int);
  297. static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
  298. static bool cache_free(uma_zone_t, uma_cache_t, void *, int);
  299. static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
  300. static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
  301. static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
  302. static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
  303. static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
  304. static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
  305. static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
  306. static uint64_t uma_zone_get_allocs(uma_zone_t zone);
  307. static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
  308. "Memory allocation debugging");
  309. #ifdef INVARIANTS
  310. static uint64_t uma_keg_get_allocs(uma_keg_t zone);
  311. static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
  312. static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
  313. static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
  314. static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
  315. static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
  316. static u_int dbg_divisor = 1;
  317. SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
  318. CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
  319. "Debug & thrash every this item in memory allocator");
  320. static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
  321. static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
  322. SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
  323. &uma_dbg_cnt, "memory items debugged");
  324. SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
  325. &uma_skip_cnt, "memory items skipped, not debugged");
  326. #endif
  327. SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
  328. "Universal Memory Allocator");
  329. SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
  330. 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
  331. SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
  332. 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
  333. static int zone_warnings = 1;
  334. SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
  335. "Warn when UMA zones becomes full");
  336. static int multipage_slabs = 1;
  337. TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
  338. SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
  339. CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
  340. "UMA may choose larger slab sizes for better efficiency");
  341. /*
  342. * Select the slab zone for an offpage slab with the given maximum item count.
  343. */
  344. static inline uma_zone_t
  345. slabzone(int ipers)
  346. {
  347. return (slabzones[ipers > SLABZONE0_SETSIZE]);
  348. }
  349. /*
  350. * This routine checks to see whether or not it's safe to enable buckets.
  351. */
  352. static void
  353. bucket_enable(void)
  354. {
  355. KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
  356. bucketdisable = vm_page_count_min();
  357. }
  358. /*
  359. * Initialize bucket_zones, the array of zones of buckets of various sizes.
  360. *
  361. * For each zone, calculate the memory required for each bucket, consisting
  362. * of the header and an array of pointers.
  363. */
  364. static void
  365. bucket_init(void)
  366. {
  367. struct uma_bucket_zone *ubz;
  368. int size;
  369. for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
  370. size = roundup(sizeof(struct uma_bucket), sizeof(void *));
  371. size += sizeof(void *) * ubz->ubz_entries;
  372. ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
  373. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
  374. UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
  375. UMA_ZONE_FIRSTTOUCH);
  376. }
  377. }
  378. /*
  379. * Given a desired number of entries for a bucket, return the zone from which
  380. * to allocate the bucket.
  381. */
  382. static struct uma_bucket_zone *
  383. bucket_zone_lookup(int entries)
  384. {
  385. struct uma_bucket_zone *ubz;
  386. for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
  387. if (ubz->ubz_entries >= entries)
  388. return (ubz);
  389. ubz--;
  390. return (ubz);
  391. }
  392. static int
  393. bucket_select(int size)
  394. {
  395. struct uma_bucket_zone *ubz;
  396. ubz = &bucket_zones[0];
  397. if (size > ubz->ubz_maxsize)
  398. return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
  399. for (; ubz->ubz_entries != 0; ubz++)
  400. if (ubz->ubz_maxsize < size)
  401. break;
  402. ubz--;
  403. return (ubz->ubz_entries);
  404. }
  405. static uma_bucket_t
  406. bucket_alloc(uma_zone_t zone, void *udata, int flags)
  407. {
  408. struct uma_bucket_zone *ubz;
  409. uma_bucket_t bucket;
  410. /*
  411. * Don't allocate buckets early in boot.
  412. */
  413. if (__predict_false(booted < BOOT_KVA))
  414. return (NULL);
  415. /*
  416. * To limit bucket recursion we store the original zone flags
  417. * in a cookie passed via zalloc_arg/zfree_arg. This allows the
  418. * NOVM flag to persist even through deep recursions. We also
  419. * store ZFLAG_BUCKET once we have recursed attempting to allocate
  420. * a bucket for a bucket zone so we do not allow infinite bucket
  421. * recursion. This cookie will even persist to frees of unused
  422. * buckets via the allocation path or bucket allocations in the
  423. * free path.
  424. */
  425. if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
  426. udata = (void *)(uintptr_t)zone->uz_flags;
  427. else {
  428. if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
  429. return (NULL);
  430. udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
  431. }
  432. if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
  433. flags |= M_NOVM;
  434. ubz = bucket_zone_lookup(atomic_load_16(&zone->uz_bucket_size));
  435. if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
  436. ubz++;
  437. bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
  438. if (bucket) {
  439. #ifdef INVARIANTS
  440. bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
  441. #endif
  442. bucket->ub_cnt = 0;
  443. bucket->ub_entries = min(ubz->ubz_entries,
  444. zone->uz_bucket_size_max);
  445. bucket->ub_seq = SMR_SEQ_INVALID;
  446. CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
  447. zone->uz_name, zone, bucket);
  448. }
  449. return (bucket);
  450. }
  451. static void
  452. bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
  453. {
  454. struct uma_bucket_zone *ubz;
  455. if (bucket->ub_cnt != 0)
  456. bucket_drain(zone, bucket);
  457. KASSERT(bucket->ub_cnt == 0,
  458. ("bucket_free: Freeing a non free bucket."));
  459. KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
  460. ("bucket_free: Freeing an SMR bucket."));
  461. if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
  462. udata = (void *)(uintptr_t)zone->uz_flags;
  463. ubz = bucket_zone_lookup(bucket->ub_entries);
  464. uma_zfree_arg(ubz->ubz_zone, bucket, udata);
  465. }
  466. static void
  467. bucket_zone_drain(int domain)
  468. {
  469. struct uma_bucket_zone *ubz;
  470. for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
  471. uma_zone_reclaim_domain(ubz->ubz_zone, UMA_RECLAIM_DRAIN,
  472. domain);
  473. }
  474. #ifdef KASAN
  475. _Static_assert(UMA_SMALLEST_UNIT % KASAN_SHADOW_SCALE == 0,
  476. "Base UMA allocation size not a multiple of the KASAN scale factor");
  477. static void
  478. kasan_mark_item_valid(uma_zone_t zone, void *item)
  479. {
  480. void *pcpu_item;
  481. size_t sz, rsz;
  482. int i;
  483. if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
  484. return;
  485. sz = zone->uz_size;
  486. rsz = roundup2(sz, KASAN_SHADOW_SCALE);
  487. if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
  488. kasan_mark(item, sz, rsz, KASAN_GENERIC_REDZONE);
  489. } else {
  490. pcpu_item = zpcpu_base_to_offset(item);
  491. for (i = 0; i <= mp_maxid; i++)
  492. kasan_mark(zpcpu_get_cpu(pcpu_item, i), sz, rsz,
  493. KASAN_GENERIC_REDZONE);
  494. }
  495. }
  496. static void
  497. kasan_mark_item_invalid(uma_zone_t zone, void *item)
  498. {
  499. void *pcpu_item;
  500. size_t sz;
  501. int i;
  502. if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
  503. return;
  504. sz = roundup2(zone->uz_size, KASAN_SHADOW_SCALE);
  505. if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
  506. kasan_mark(item, 0, sz, KASAN_UMA_FREED);
  507. } else {
  508. pcpu_item = zpcpu_base_to_offset(item);
  509. for (i = 0; i <= mp_maxid; i++)
  510. kasan_mark(zpcpu_get_cpu(pcpu_item, i), 0, sz,
  511. KASAN_UMA_FREED);
  512. }
  513. }
  514. static void
  515. kasan_mark_slab_valid(uma_keg_t keg, void *mem)
  516. {
  517. size_t sz;
  518. if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
  519. sz = keg->uk_ppera * PAGE_SIZE;
  520. kasan_mark(mem, sz, sz, 0);
  521. }
  522. }
  523. static void
  524. kasan_mark_slab_invalid(uma_keg_t keg, void *mem)
  525. {
  526. size_t sz;
  527. if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
  528. if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
  529. sz = keg->uk_ppera * PAGE_SIZE;
  530. else
  531. sz = keg->uk_pgoff;
  532. kasan_mark(mem, 0, sz, KASAN_UMA_FREED);
  533. }
  534. }
  535. #else /* !KASAN */
  536. static void
  537. kasan_mark_item_valid(uma_zone_t zone __unused, void *item __unused)
  538. {
  539. }
  540. static void
  541. kasan_mark_item_invalid(uma_zone_t zone __unused, void *item __unused)
  542. {
  543. }
  544. static void
  545. kasan_mark_slab_valid(uma_keg_t keg __unused, void *mem __unused)
  546. {
  547. }
  548. static void
  549. kasan_mark_slab_invalid(uma_keg_t keg __unused, void *mem __unused)
  550. {
  551. }
  552. #endif /* KASAN */
  553. #ifdef KMSAN
  554. static inline void
  555. kmsan_mark_item_uninitialized(uma_zone_t zone, void *item)
  556. {
  557. void *pcpu_item;
  558. size_t sz;
  559. int i;
  560. if ((zone->uz_flags &
  561. (UMA_ZFLAG_CACHE | UMA_ZONE_SECONDARY | UMA_ZONE_MALLOC)) != 0) {
  562. /*
  563. * Cache zones should not be instrumented by default, as UMA
  564. * does not have enough information to do so correctly.
  565. * Consumers can mark items themselves if it makes sense to do
  566. * so.
  567. *
  568. * Items from secondary zones are initialized by the parent
  569. * zone and thus cannot safely be marked by UMA.
  570. *
  571. * malloc zones are handled directly by malloc(9) and friends,
  572. * since they can provide more precise origin tracking.
  573. */
  574. return;
  575. }
  576. if (zone->uz_keg->uk_init != NULL) {
  577. /*
  578. * By definition, initialized items cannot be marked. The
  579. * best we can do is mark items from these zones after they
  580. * are freed to the keg.
  581. */
  582. return;
  583. }
  584. sz = zone->uz_size;
  585. if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
  586. kmsan_orig(item, sz, KMSAN_TYPE_UMA, KMSAN_RET_ADDR);
  587. kmsan_mark(item, sz, KMSAN_STATE_UNINIT);
  588. } else {
  589. pcpu_item = zpcpu_base_to_offset(item);
  590. for (i = 0; i <= mp_maxid; i++) {
  591. kmsan_orig(zpcpu_get_cpu(pcpu_item, i), sz,
  592. KMSAN_TYPE_UMA, KMSAN_RET_ADDR);
  593. kmsan_mark(zpcpu_get_cpu(pcpu_item, i), sz,
  594. KMSAN_STATE_INITED);
  595. }
  596. }
  597. }
  598. #else /* !KMSAN */
  599. static inline void
  600. kmsan_mark_item_uninitialized(uma_zone_t zone __unused, void *item __unused)
  601. {
  602. }
  603. #endif /* KMSAN */
  604. /*
  605. * Acquire the domain lock and record contention.
  606. */
  607. static uma_zone_domain_t
  608. zone_domain_lock(uma_zone_t zone, int domain)
  609. {
  610. uma_zone_domain_t zdom;
  611. bool lockfail;
  612. zdom = ZDOM_GET(zone, domain);
  613. lockfail = false;
  614. if (ZDOM_OWNED(zdom))
  615. lockfail = true;
  616. ZDOM_LOCK(zdom);
  617. /* This is unsynchronized. The counter does not need to be precise. */
  618. if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
  619. zone->uz_bucket_size++;
  620. return (zdom);
  621. }
  622. /*
  623. * Search for the domain with the least cached items and return it if it
  624. * is out of balance with the preferred domain.
  625. */
  626. static __noinline int
  627. zone_domain_lowest(uma_zone_t zone, int pref)
  628. {
  629. long least, nitems, prefitems;
  630. int domain;
  631. int i;
  632. prefitems = least = LONG_MAX;
  633. domain = 0;
  634. for (i = 0; i < vm_ndomains; i++) {
  635. nitems = ZDOM_GET(zone, i)->uzd_nitems;
  636. if (nitems < least) {
  637. domain = i;
  638. least = nitems;
  639. }
  640. if (domain == pref)
  641. prefitems = nitems;
  642. }
  643. if (prefitems < least * 2)
  644. return (pref);
  645. return (domain);
  646. }
  647. /*
  648. * Search for the domain with the most cached items and return it or the
  649. * preferred domain if it has enough to proceed.
  650. */
  651. static __noinline int
  652. zone_domain_highest(uma_zone_t zone, int pref)
  653. {
  654. long most, nitems;
  655. int domain;
  656. int i;
  657. if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
  658. return (pref);
  659. most = 0;
  660. domain = 0;
  661. for (i = 0; i < vm_ndomains; i++) {
  662. nitems = ZDOM_GET(zone, i)->uzd_nitems;
  663. if (nitems > most) {
  664. domain = i;
  665. most = nitems;
  666. }
  667. }
  668. return (domain);
  669. }
  670. /*
  671. * Set the maximum imax value.
  672. */
  673. static void
  674. zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
  675. {
  676. long old;
  677. old = zdom->uzd_imax;
  678. do {
  679. if (old >= nitems)
  680. return;
  681. } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
  682. /*
  683. * We are at new maximum, so do the last WSS update for the old
  684. * bimin and prepare to measure next allocation batch.
  685. */
  686. if (zdom->uzd_wss < old - zdom->uzd_bimin)
  687. zdom->uzd_wss = old - zdom->uzd_bimin;
  688. zdom->uzd_bimin = nitems;
  689. }
  690. /*
  691. * Attempt to satisfy an allocation by retrieving a full bucket from one of the
  692. * zone's caches. If a bucket is found the zone is not locked on return.
  693. */
  694. static uma_bucket_t
  695. zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
  696. {
  697. uma_bucket_t bucket;
  698. long cnt;
  699. int i;
  700. bool dtor = false;
  701. ZDOM_LOCK_ASSERT(zdom);
  702. if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
  703. return (NULL);
  704. /* SMR Buckets can not be re-used until readers expire. */
  705. if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
  706. bucket->ub_seq != SMR_SEQ_INVALID) {
  707. if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
  708. return (NULL);
  709. bucket->ub_seq = SMR_SEQ_INVALID;
  710. dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
  711. if (STAILQ_NEXT(bucket, ub_link) != NULL)
  712. zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
  713. }
  714. STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
  715. KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
  716. ("%s: item count underflow (%ld, %d)",
  717. __func__, zdom->uzd_nitems, bucket->ub_cnt));
  718. KASSERT(bucket->ub_cnt > 0,
  719. ("%s: empty bucket in bucket cache", __func__));
  720. zdom->uzd_nitems -= bucket->ub_cnt;
  721. if (reclaim) {
  722. /*
  723. * Shift the bounds of the current WSS interval to avoid
  724. * perturbing the estimates.
  725. */
  726. cnt = lmin(zdom->uzd_bimin, bucket->ub_cnt);
  727. atomic_subtract_long(&zdom->uzd_imax, cnt);
  728. zdom->uzd_bimin -= cnt;
  729. zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
  730. if (zdom->uzd_limin >= bucket->ub_cnt) {
  731. zdom->uzd_limin -= bucket->ub_cnt;
  732. } else {
  733. zdom->uzd_limin = 0;
  734. zdom->uzd_timin = 0;
  735. }
  736. } else if (zdom->uzd_bimin > zdom->uzd_nitems) {
  737. zdom->uzd_bimin = zdom->uzd_nitems;
  738. if (zdom->uzd_imin > zdom->uzd_nitems)
  739. zdom->uzd_imin = zdom->uzd_nitems;
  740. }
  741. ZDOM_UNLOCK(zdom);
  742. if (dtor)
  743. for (i = 0; i < bucket->ub_cnt; i++)
  744. item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
  745. NULL, SKIP_NONE);
  746. return (bucket);
  747. }
  748. /*
  749. * Insert a full bucket into the specified cache. The "ws" parameter indicates
  750. * whether the bucket's contents should be counted as part of the zone's working
  751. * set. The bucket may be freed if it exceeds the bucket limit.
  752. */
  753. static void
  754. zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
  755. const bool ws)
  756. {
  757. uma_zone_domain_t zdom;
  758. /* We don't cache empty buckets. This can happen after a reclaim. */
  759. if (bucket->ub_cnt == 0)
  760. goto out;
  761. zdom = zone_domain_lock(zone, domain);
  762. /*
  763. * Conditionally set the maximum number of items.
  764. */
  765. zdom->uzd_nitems += bucket->ub_cnt;
  766. if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
  767. if (ws) {
  768. zone_domain_imax_set(zdom, zdom->uzd_nitems);
  769. } else {
  770. /*
  771. * Shift the bounds of the current WSS interval to
  772. * avoid perturbing the estimates.
  773. */
  774. atomic_add_long(&zdom->uzd_imax, bucket->ub_cnt);
  775. zdom->uzd_imin += bucket->ub_cnt;
  776. zdom->uzd_bimin += bucket->ub_cnt;
  777. zdom->uzd_limin += bucket->ub_cnt;
  778. }
  779. if (STAILQ_EMPTY(&zdom->uzd_buckets))
  780. zdom->uzd_seq = bucket->ub_seq;
  781. /*
  782. * Try to promote reuse of recently used items. For items
  783. * protected by SMR, try to defer reuse to minimize polling.
  784. */
  785. if (bucket->ub_seq == SMR_SEQ_INVALID)
  786. STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
  787. else
  788. STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
  789. ZDOM_UNLOCK(zdom);
  790. return;
  791. }
  792. zdom->uzd_nitems -= bucket->ub_cnt;
  793. ZDOM_UNLOCK(zdom);
  794. out:
  795. bucket_free(zone, bucket, udata);
  796. }
  797. /* Pops an item out of a per-cpu cache bucket. */
  798. static inline void *
  799. cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
  800. {
  801. void *item;
  802. CRITICAL_ASSERT(curthread);
  803. bucket->ucb_cnt--;
  804. item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
  805. #ifdef INVARIANTS
  806. bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
  807. KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
  808. #endif
  809. cache->uc_allocs++;
  810. return (item);
  811. }
  812. /* Pushes an item into a per-cpu cache bucket. */
  813. static inline void
  814. cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
  815. {
  816. CRITICAL_ASSERT(curthread);
  817. KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
  818. ("uma_zfree: Freeing to non free bucket index."));
  819. bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
  820. bucket->ucb_cnt++;
  821. cache->uc_frees++;
  822. }
  823. /*
  824. * Unload a UMA bucket from a per-cpu cache.
  825. */
  826. static inline uma_bucket_t
  827. cache_bucket_unload(uma_cache_bucket_t bucket)
  828. {
  829. uma_bucket_t b;
  830. b = bucket->ucb_bucket;
  831. if (b != NULL) {
  832. MPASS(b->ub_entries == bucket->ucb_entries);
  833. b->ub_cnt = bucket->ucb_cnt;
  834. bucket->ucb_bucket = NULL;
  835. bucket->ucb_entries = bucket->ucb_cnt = 0;
  836. }
  837. return (b);
  838. }
  839. static inline uma_bucket_t
  840. cache_bucket_unload_alloc(uma_cache_t cache)
  841. {
  842. return (cache_bucket_unload(&cache->uc_allocbucket));
  843. }
  844. static inline uma_bucket_t
  845. cache_bucket_unload_free(uma_cache_t cache)
  846. {
  847. return (cache_bucket_unload(&cache->uc_freebucket));
  848. }
  849. static inline uma_bucket_t
  850. cache_bucket_unload_cross(uma_cache_t cache)
  851. {
  852. return (cache_bucket_unload(&cache->uc_crossbucket));
  853. }
  854. /*
  855. * Load a bucket into a per-cpu cache bucket.
  856. */
  857. static inline void
  858. cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
  859. {
  860. CRITICAL_ASSERT(curthread);
  861. MPASS(bucket->ucb_bucket == NULL);
  862. MPASS(b->ub_seq == SMR_SEQ_INVALID);
  863. bucket->ucb_bucket = b;
  864. bucket->ucb_cnt = b->ub_cnt;
  865. bucket->ucb_entries = b->ub_entries;
  866. }
  867. static inline void
  868. cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
  869. {
  870. cache_bucket_load(&cache->uc_allocbucket, b);
  871. }
  872. static inline void
  873. cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
  874. {
  875. cache_bucket_load(&cache->uc_freebucket, b);
  876. }
  877. #ifdef NUMA
  878. static inline void
  879. cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
  880. {
  881. cache_bucket_load(&cache->uc_crossbucket, b);
  882. }
  883. #endif
  884. /*
  885. * Copy and preserve ucb_spare.
  886. */
  887. static inline void
  888. cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
  889. {
  890. b1->ucb_bucket = b2->ucb_bucket;
  891. b1->ucb_entries = b2->ucb_entries;
  892. b1->ucb_cnt = b2->ucb_cnt;
  893. }
  894. /*
  895. * Swap two cache buckets.
  896. */
  897. static inline void
  898. cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
  899. {
  900. struct uma_cache_bucket b3;
  901. CRITICAL_ASSERT(curthread);
  902. cache_bucket_copy(&b3, b1);
  903. cache_bucket_copy(b1, b2);
  904. cache_bucket_copy(b2, &b3);
  905. }
  906. /*
  907. * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
  908. */
  909. static uma_bucket_t
  910. cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
  911. {
  912. uma_zone_domain_t zdom;
  913. uma_bucket_t bucket;
  914. smr_seq_t seq;
  915. /*
  916. * Avoid the lock if possible.
  917. */
  918. zdom = ZDOM_GET(zone, domain);
  919. if (zdom->uzd_nitems == 0)
  920. return (NULL);
  921. if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
  922. (seq = atomic_load_32(&zdom->uzd_seq)) != SMR_SEQ_INVALID &&
  923. !smr_poll(zone->uz_smr, seq, false))
  924. return (NULL);
  925. /*
  926. * Check the zone's cache of buckets.
  927. */
  928. zdom = zone_domain_lock(zone, domain);
  929. if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
  930. return (bucket);
  931. ZDOM_UNLOCK(zdom);
  932. return (NULL);
  933. }
  934. static void
  935. zone_log_warning(uma_zone_t zone)
  936. {
  937. static const struct timeval warninterval = { 300, 0 };
  938. if (!zone_warnings || zone->uz_warning == NULL)
  939. return;
  940. if (ratecheck(&zone->uz_ratecheck, &warninterval))
  941. printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
  942. }
  943. static inline void
  944. zone_maxaction(uma_zone_t zone)
  945. {
  946. if (zone->uz_maxaction.ta_func != NULL)
  947. taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
  948. }
  949. /*
  950. * Routine called by timeout which is used to fire off some time interval
  951. * based calculations. (stats, hash size, etc.)
  952. *
  953. * Arguments:
  954. * arg Unused
  955. *
  956. * Returns:
  957. * Nothing
  958. */
  959. static void
  960. uma_timeout(void *context __unused, int pending __unused)
  961. {
  962. bucket_enable();
  963. zone_foreach(zone_timeout, NULL);
  964. /* Reschedule this event */
  965. taskqueue_enqueue_timeout(taskqueue_thread, &uma_timeout_task,
  966. UMA_TIMEOUT * hz);
  967. }
  968. /*
  969. * Update the working set size estimates for the zone's bucket cache.
  970. * The constants chosen here are somewhat arbitrary.
  971. */
  972. static void
  973. zone_domain_update_wss(uma_zone_domain_t zdom)
  974. {
  975. long m;
  976. ZDOM_LOCK_ASSERT(zdom);
  977. MPASS(zdom->uzd_imax >= zdom->uzd_nitems);
  978. MPASS(zdom->uzd_nitems >= zdom->uzd_bimin);
  979. MPASS(zdom->uzd_bimin >= zdom->uzd_imin);
  980. /*
  981. * Estimate WSS as modified moving average of biggest allocation
  982. * batches for each period over few minutes (UMA_TIMEOUT of 20s).
  983. */
  984. zdom->uzd_wss = lmax(zdom->uzd_wss * 3 / 4,
  985. zdom->uzd_imax - zdom->uzd_bimin);
  986. /*
  987. * Estimate longtime minimum item count as a combination of recent
  988. * minimum item count, adjusted by WSS for safety, and the modified
  989. * moving average over the last several hours (UMA_TIMEOUT of 20s).
  990. * timin measures time since limin tried to go negative, that means
  991. * we were dangerously close to or got out of cache.
  992. */
  993. m = zdom->uzd_imin - zdom->uzd_wss;
  994. if (m >= 0) {
  995. if (zdom->uzd_limin >= m)
  996. zdom->uzd_limin = m;
  997. else
  998. zdom->uzd_limin = (m + zdom->uzd_limin * 255) / 256;
  999. zdom->uzd_timin++;
  1000. } else {
  1001. zdom->uzd_limin = 0;
  1002. zdom->uzd_timin = 0;
  1003. }
  1004. /* To reduce period edge effects on WSS keep half of the imax. */
  1005. atomic_subtract_long(&zdom->uzd_imax,
  1006. (zdom->uzd_imax - zdom->uzd_nitems + 1) / 2);
  1007. zdom->uzd_imin = zdom->uzd_bimin = zdom->uzd_nitems;
  1008. }
  1009. /*
  1010. * Routine to perform timeout driven calculations. This expands the
  1011. * hashes and does per cpu statistics aggregation.
  1012. *
  1013. * Returns nothing.
  1014. */
  1015. static void
  1016. zone_timeout(uma_zone_t zone, void *unused)
  1017. {
  1018. uma_keg_t keg;
  1019. u_int slabs, pages;
  1020. if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
  1021. goto trim;
  1022. keg = zone->uz_keg;
  1023. /*
  1024. * Hash zones are non-numa by definition so the first domain
  1025. * is the only one present.
  1026. */
  1027. KEG_LOCK(keg, 0);
  1028. pages = keg->uk_domain[0].ud_pages;
  1029. /*
  1030. * Expand the keg hash table.
  1031. *
  1032. * This is done if the number of slabs is larger than the hash size.
  1033. * What I'm trying to do here is completely reduce collisions. This
  1034. * may be a little aggressive. Should I allow for two collisions max?
  1035. */
  1036. if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
  1037. struct uma_hash newhash;
  1038. struct uma_hash oldhash;
  1039. int ret;
  1040. /*
  1041. * This is so involved because allocating and freeing
  1042. * while the keg lock is held will lead to deadlock.
  1043. * I have to do everything in stages and check for
  1044. * races.
  1045. */
  1046. KEG_UNLOCK(keg, 0);
  1047. ret = hash_alloc(&newhash, 1 << fls(slabs));
  1048. KEG_LOCK(keg, 0);
  1049. if (ret) {
  1050. if (hash_expand(&keg->uk_hash, &newhash)) {
  1051. oldhash = keg->uk_hash;
  1052. keg->uk_hash = newhash;
  1053. } else
  1054. oldhash = newhash;
  1055. KEG_UNLOCK(keg, 0);
  1056. hash_free(&oldhash);
  1057. goto trim;
  1058. }
  1059. }
  1060. KEG_UNLOCK(keg, 0);
  1061. trim:
  1062. /* Trim caches not used for a long time. */
  1063. if ((zone->uz_flags & UMA_ZONE_UNMANAGED) == 0) {
  1064. for (int i = 0; i < vm_ndomains; i++) {
  1065. if (bucket_cache_reclaim_domain(zone, false, false, i) &&
  1066. (zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
  1067. keg_drain(zone->uz_keg, i);
  1068. }
  1069. }
  1070. }
  1071. /*
  1072. * Allocate and zero fill the next sized hash table from the appropriate
  1073. * backing store.
  1074. *
  1075. * Arguments:
  1076. * hash A new hash structure with the old hash size in uh_hashsize
  1077. *
  1078. * Returns:
  1079. * 1 on success and 0 on failure.
  1080. */
  1081. static int
  1082. hash_alloc(struct uma_hash *hash, u_int size)
  1083. {
  1084. size_t alloc;
  1085. KASSERT(powerof2(size), ("hash size must be power of 2"));
  1086. if (size > UMA_HASH_SIZE_INIT) {
  1087. hash->uh_hashsize = size;
  1088. alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
  1089. hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
  1090. } else {
  1091. alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
  1092. hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
  1093. UMA_ANYDOMAIN, M_WAITOK);
  1094. hash->uh_hashsize = UMA_HASH_SIZE_INIT;
  1095. }
  1096. if (hash->uh_slab_hash) {
  1097. bzero(hash->uh_slab_hash, alloc);
  1098. hash->uh_hashmask = hash->uh_hashsize - 1;
  1099. return (1);
  1100. }
  1101. return (0);
  1102. }
  1103. /*
  1104. * Expands the hash table for HASH zones. This is done from zone_timeout
  1105. * to reduce collisions. This must not be done in the regular allocation
  1106. * path, otherwise, we can recurse on the vm while allocating pages.
  1107. *
  1108. * Arguments:
  1109. * oldhash The hash you want to expand
  1110. * newhash The hash structure for the new table
  1111. *
  1112. * Returns:
  1113. * Nothing
  1114. *
  1115. * Discussion:
  1116. */
  1117. static int
  1118. hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
  1119. {
  1120. uma_hash_slab_t slab;
  1121. u_int hval;
  1122. u_int idx;
  1123. if (!newhash->uh_slab_hash)
  1124. return (0);
  1125. if (oldhash->uh_hashsize >= newhash->uh_hashsize)
  1126. return (0);
  1127. /*
  1128. * I need to investigate hash algorithms for resizing without a
  1129. * full rehash.
  1130. */
  1131. for (idx = 0; idx < oldhash->uh_hashsize; idx++)
  1132. while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
  1133. slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
  1134. LIST_REMOVE(slab, uhs_hlink);
  1135. hval = UMA_HASH(newhash, slab->uhs_data);
  1136. LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
  1137. slab, uhs_hlink);
  1138. }
  1139. return (1);
  1140. }
  1141. /*
  1142. * Free the hash bucket to the appropriate backing store.
  1143. *
  1144. * Arguments:
  1145. * slab_hash The hash bucket we're freeing
  1146. * hashsize The number of entries in that hash bucket
  1147. *
  1148. * Returns:
  1149. * Nothing
  1150. */
  1151. static void
  1152. hash_free(struct uma_hash *hash)
  1153. {
  1154. if (hash->uh_slab_hash == NULL)
  1155. return;
  1156. if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
  1157. zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
  1158. else
  1159. free(hash->uh_slab_hash, M_UMAHASH);
  1160. }
  1161. /*
  1162. * Frees all outstanding items in a bucket
  1163. *
  1164. * Arguments:
  1165. * zone The zone to free to, must be unlocked.
  1166. * bucket The free/alloc bucket with items.
  1167. *
  1168. * Returns:
  1169. * Nothing
  1170. */
  1171. static void
  1172. bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
  1173. {
  1174. int i;
  1175. if (bucket->ub_cnt == 0)
  1176. return;
  1177. if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
  1178. bucket->ub_seq != SMR_SEQ_INVALID) {
  1179. smr_wait(zone->uz_smr, bucket->ub_seq);
  1180. bucket->ub_seq = SMR_SEQ_INVALID;
  1181. for (i = 0; i < bucket->ub_cnt; i++)
  1182. item_dtor(zone, bucket->ub_bucket[i],
  1183. zone->uz_size, NULL, SKIP_NONE);
  1184. }
  1185. if (zone->uz_fini)
  1186. for (i = 0; i < bucket->ub_cnt; i++) {
  1187. kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
  1188. zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
  1189. kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
  1190. }
  1191. zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
  1192. if (zone->uz_max_items > 0)
  1193. zone_free_limit(zone, bucket->ub_cnt);
  1194. #ifdef INVARIANTS
  1195. bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
  1196. #endif
  1197. bucket->ub_cnt = 0;
  1198. }
  1199. /*
  1200. * Drains the per cpu caches for a zone.
  1201. *
  1202. * NOTE: This may only be called while the zone is being torn down, and not
  1203. * during normal operation. This is necessary in order that we do not have
  1204. * to migrate CPUs to drain the per-CPU caches.
  1205. *
  1206. * Arguments:
  1207. * zone The zone to drain, must be unlocked.
  1208. *
  1209. * Returns:
  1210. * Nothing
  1211. */
  1212. static void
  1213. cache_drain(uma_zone_t zone)
  1214. {
  1215. uma_cache_t cache;
  1216. uma_bucket_t bucket;
  1217. smr_seq_t seq;
  1218. int cpu;
  1219. /*
  1220. * XXX: It is safe to not lock the per-CPU caches, because we're
  1221. * tearing down the zone anyway. I.e., there will be no further use
  1222. * of the caches at this point.
  1223. *
  1224. * XXX: It would good to be able to assert that the zone is being
  1225. * torn down to prevent improper use of cache_drain().
  1226. */
  1227. seq = SMR_SEQ_INVALID;
  1228. if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
  1229. seq = smr_advance(zone->uz_smr);
  1230. CPU_FOREACH(cpu) {
  1231. cache = &zone->uz_cpu[cpu];
  1232. bucket = cache_bucket_unload_alloc(cache);
  1233. if (bucket != NULL)
  1234. bucket_free(zone, bucket, NULL);
  1235. bucket = cache_bucket_unload_free(cache);
  1236. if (bucket != NULL) {
  1237. bucket->ub_seq = seq;
  1238. bucket_free(zone, bucket, NULL);
  1239. }
  1240. bucket = cache_bucket_unload_cross(cache);
  1241. if (bucket != NULL) {
  1242. bucket->ub_seq = seq;
  1243. bucket_free(zone, bucket, NULL);
  1244. }
  1245. }
  1246. bucket_cache_reclaim(zone, true, UMA_ANYDOMAIN);
  1247. }
  1248. static void
  1249. cache_shrink(uma_zone_t zone, void *unused)
  1250. {
  1251. if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
  1252. return;
  1253. ZONE_LOCK(zone);
  1254. zone->uz_bucket_size =
  1255. (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
  1256. ZONE_UNLOCK(zone);
  1257. }
  1258. static void
  1259. cache_drain_safe_cpu(uma_zone_t zone, void *unused)
  1260. {
  1261. uma_cache_t cache;
  1262. uma_bucket_t b1, b2, b3;
  1263. int domain;
  1264. if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
  1265. return;
  1266. b1 = b2 = b3 = NULL;
  1267. critical_enter();
  1268. cache = &zone->uz_cpu[curcpu];
  1269. domain = PCPU_GET(domain);
  1270. b1 = cache_bucket_unload_alloc(cache);
  1271. /*
  1272. * Don't flush SMR zone buckets. This leaves the zone without a
  1273. * bucket and forces every free to synchronize().
  1274. */
  1275. if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
  1276. b2 = cache_bucket_unload_free(cache);
  1277. b3 = cache_bucket_unload_cross(cache);
  1278. }
  1279. critical_exit();
  1280. if (b1 != NULL)
  1281. zone_free_bucket(zone, b1, NULL, domain, false);
  1282. if (b2 != NULL)
  1283. zone_free_bucket(zone, b2, NULL, domain, false);
  1284. if (b3 != NULL) {
  1285. /* Adjust the domain so it goes to zone_free_cross. */
  1286. domain = (domain + 1) % vm_ndomains;
  1287. zone_free_bucket(zone, b3, NULL, domain, false);
  1288. }
  1289. }
  1290. /*
  1291. * Safely drain per-CPU caches of a zone(s) to alloc bucket.
  1292. * This is an expensive call because it needs to bind to all CPUs
  1293. * one by one and enter a critical section on each of them in order
  1294. * to safely access their cache buckets.
  1295. * Zone lock must not be held on call this function.
  1296. */
  1297. static void
  1298. pcpu_cache_drain_safe(uma_zone_t zone)
  1299. {
  1300. int cpu;
  1301. /*
  1302. * Polite bucket sizes shrinking was not enough, shrink aggressively.
  1303. */
  1304. if (zone)
  1305. cache_shrink(zone, NULL);
  1306. else
  1307. zone_foreach(cache_shrink, NULL);
  1308. CPU_FOREACH(cpu) {
  1309. thread_lock(curthread);
  1310. sched_bind(curthread, cpu);
  1311. thread_unlock(curthread);
  1312. if (zone)
  1313. cache_drain_safe_cpu(zone, NULL);
  1314. else
  1315. zone_foreach(cache_drain_safe_cpu, NULL);
  1316. }
  1317. thread_lock(curthread);
  1318. sched_unbind(curthread);
  1319. thread_unlock(curthread);
  1320. }
  1321. /*
  1322. * Reclaim cached buckets from a zone. All buckets are reclaimed if the caller
  1323. * requested a drain, otherwise the per-domain caches are trimmed to either
  1324. * estimated working set size.
  1325. */
  1326. static bool
  1327. bucket_cache_reclaim_domain(uma_zone_t zone, bool drain, bool trim, int domain)
  1328. {
  1329. uma_zone_domain_t zdom;
  1330. uma_bucket_t bucket;
  1331. long target;
  1332. bool done = false;
  1333. /*
  1334. * The cross bucket is partially filled and not part of
  1335. * the item count. Reclaim it individually here.
  1336. */
  1337. zdom = ZDOM_GET(zone, domain);
  1338. if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
  1339. ZONE_CROSS_LOCK(zone);
  1340. bucket = zdom->uzd_cross;
  1341. zdom->uzd_cross = NULL;
  1342. ZONE_CROSS_UNLOCK(zone);
  1343. if (bucket != NULL)
  1344. bucket_free(zone, bucket, NULL);
  1345. }
  1346. /*
  1347. * If we were asked to drain the zone, we are done only once
  1348. * this bucket cache is empty. If trim, we reclaim items in
  1349. * excess of the zone's estimated working set size. Multiple
  1350. * consecutive calls will shrink the WSS and so reclaim more.
  1351. * If neither drain nor trim, then voluntarily reclaim 1/4
  1352. * (to reduce first spike) of items not used for a long time.
  1353. */
  1354. ZDOM_LOCK(zdom);
  1355. zone_domain_update_wss(zdom);
  1356. if (drain)
  1357. target = 0;
  1358. else if (trim)
  1359. target = zdom->uzd_wss;
  1360. else if (zdom->uzd_timin > 900 / UMA_TIMEOUT)
  1361. target = zdom->uzd_nitems - zdom->uzd_limin / 4;
  1362. else {
  1363. ZDOM_UNLOCK(zdom);
  1364. return (done);
  1365. }
  1366. while ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) != NULL &&
  1367. zdom->uzd_nitems >= target + bucket->ub_cnt) {
  1368. bucket = zone_fetch_bucket(zone, zdom, true);
  1369. if (bucket == NULL)
  1370. break;
  1371. bucket_free(zone, bucket, NULL);
  1372. done = true;
  1373. ZDOM_LOCK(zdom);
  1374. }
  1375. ZDOM_UNLOCK(zdom);
  1376. return (done);
  1377. }
  1378. static void
  1379. bucket_cache_reclaim(uma_zone_t zone, bool drain, int domain)
  1380. {
  1381. int i;
  1382. /*
  1383. * Shrink the zone bucket size to ensure that the per-CPU caches
  1384. * don't grow too large.
  1385. */
  1386. if (zone->uz_bucket_size > zone->uz_bucket_size_min)
  1387. zone->uz_bucket_size--;
  1388. if (domain != UMA_ANYDOMAIN &&
  1389. (zone->uz_flags & UMA_ZONE_ROUNDROBIN) == 0) {
  1390. bucket_cache_reclaim_domain(zone, drain, true, domain);
  1391. } else {
  1392. for (i = 0; i < vm_ndomains; i++)
  1393. bucket_cache_reclaim_domain(zone, drain, true, i);
  1394. }
  1395. }
  1396. static void
  1397. keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
  1398. {
  1399. uint8_t *mem;
  1400. size_t size;
  1401. int i;
  1402. uint8_t flags;
  1403. CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
  1404. keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
  1405. mem = slab_data(slab, keg);
  1406. size = PAGE_SIZE * keg->uk_ppera;
  1407. kasan_mark_slab_valid(keg, mem);
  1408. if (keg->uk_fini != NULL) {
  1409. for (i = start - 1; i > -1; i--)
  1410. #ifdef INVARIANTS
  1411. /*
  1412. * trash_fini implies that dtor was trash_dtor. trash_fini
  1413. * would check that memory hasn't been modified since free,
  1414. * which executed trash_dtor.
  1415. * That's why we need to run uma_dbg_kskip() check here,
  1416. * albeit we don't make skip check for other init/fini
  1417. * invocations.
  1418. */
  1419. if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
  1420. keg->uk_fini != trash_fini)
  1421. #endif
  1422. keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
  1423. }
  1424. flags = slab->us_flags;
  1425. if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
  1426. zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
  1427. NULL, SKIP_NONE);
  1428. }
  1429. keg->uk_freef(mem, size, flags);
  1430. uma_total_dec(size);
  1431. }
  1432. static void
  1433. keg_drain_domain(uma_keg_t keg, int domain)
  1434. {
  1435. struct slabhead freeslabs;
  1436. uma_domain_t dom;
  1437. uma_slab_t slab, tmp;
  1438. uint32_t i, stofree, stokeep, partial;
  1439. dom = &keg->uk_domain[domain];
  1440. LIST_INIT(&freeslabs);
  1441. CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
  1442. keg->uk_name, keg, domain, dom->ud_free_items);
  1443. KEG_LOCK(keg, domain);
  1444. /*
  1445. * Are the free items in partially allocated slabs sufficient to meet
  1446. * the reserve? If not, compute the number of fully free slabs that must
  1447. * be kept.
  1448. */
  1449. partial = dom->ud_free_items - dom->ud_free_slabs * keg->uk_ipers;
  1450. if (partial < keg->uk_reserve) {
  1451. stokeep = min(dom->ud_free_slabs,
  1452. howmany(keg->uk_reserve - partial, keg->uk_ipers));
  1453. } else {
  1454. stokeep = 0;
  1455. }
  1456. stofree = dom->ud_free_slabs - stokeep;
  1457. /*
  1458. * Partition the free slabs into two sets: those that must be kept in
  1459. * order to maintain the reserve, and those that may be released back to
  1460. * the system. Since one set may be much larger than the other,
  1461. * populate the smaller of the two sets and swap them if necessary.
  1462. */
  1463. for (i = min(stofree, stokeep); i > 0; i--) {
  1464. slab = LIST_FIRST(&dom->ud_free_slab);
  1465. LIST_REMOVE(slab, us_link);
  1466. LIST_INSERT_HEAD(&freeslabs, slab, us_link);
  1467. }
  1468. if (stofree > stokeep)
  1469. LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
  1470. if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
  1471. LIST_FOREACH(slab, &freeslabs, us_link)
  1472. UMA_HASH_REMOVE(&keg->uk_hash, slab);
  1473. }
  1474. dom->ud_free_items -= stofree * keg->uk_ipers;
  1475. dom->ud_free_slabs -= stofree;
  1476. dom->ud_pages -= stofree * keg->uk_ppera;
  1477. KEG_UNLOCK(keg, domain);
  1478. LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
  1479. keg_free_slab(keg, slab, keg->uk_ipers);
  1480. }
  1481. /*
  1482. * Frees pages from a keg back to the system. This is done on demand from
  1483. * the pageout daemon.
  1484. *
  1485. * Returns nothing.
  1486. */
  1487. static void
  1488. keg_drain(uma_keg_t keg, int domain)
  1489. {
  1490. int i;
  1491. if ((keg->uk_flags & UMA_ZONE_NOFREE) != 0)
  1492. return;
  1493. if (domain != UMA_ANYDOMAIN) {
  1494. keg_drain_domain(keg, domain);
  1495. } else {
  1496. for (i = 0; i < vm_ndomains; i++)
  1497. keg_drain_domain(keg, i);
  1498. }
  1499. }
  1500. static void
  1501. zone_reclaim(uma_zone_t zone, int domain, int waitok, bool drain)
  1502. {
  1503. /*
  1504. * Count active reclaim operations in order to interlock with
  1505. * zone_dtor(), which removes the zone from global lists before
  1506. * attempting to reclaim items itself.
  1507. *
  1508. * The zone may be destroyed while sleeping, so only zone_dtor() should
  1509. * specify M_WAITOK.
  1510. */
  1511. ZONE_LOCK(zone);
  1512. if (waitok == M_WAITOK) {
  1513. while (zone->uz_reclaimers > 0)
  1514. msleep(zone, ZONE_LOCKPTR(zone), PVM, "zonedrain", 1);
  1515. }
  1516. zone->uz_reclaimers++;
  1517. ZONE_UNLOCK(zone);
  1518. bucket_cache_reclaim(zone, drain, domain);
  1519. if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
  1520. keg_drain(zone->uz_keg, domain);
  1521. ZONE_LOCK(zone);
  1522. zone->uz_reclaimers--;
  1523. if (zone->uz_reclaimers == 0)
  1524. wakeup(zone);
  1525. ZONE_UNLOCK(zone);
  1526. }
  1527. /*
  1528. * Allocate a new slab for a keg and inserts it into the partial slab list.
  1529. * The keg should be unlocked on entry. If the allocation succeeds it will
  1530. * be locked on return.
  1531. *
  1532. * Arguments:
  1533. * flags Wait flags for the item initialization routine
  1534. * aflags Wait flags for the slab allocation
  1535. *
  1536. * Returns:
  1537. * The slab that was allocated or NULL if there is no memory and the
  1538. * caller specified M_NOWAIT.
  1539. */
  1540. static uma_slab_t
  1541. keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
  1542. int aflags)
  1543. {
  1544. uma_domain_t dom;
  1545. uma_slab_t slab;
  1546. unsigned long size;
  1547. uint8_t *mem;
  1548. uint8_t sflags;
  1549. int i;
  1550. TSENTER();
  1551. KASSERT(domain >= 0 && domain < vm_ndomains,
  1552. ("keg_alloc_slab: domain %d out of range", domain));
  1553. slab = NULL;
  1554. mem = NULL;
  1555. if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
  1556. uma_hash_slab_t hslab;
  1557. hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
  1558. domain, aflags);
  1559. if (hslab == NULL)
  1560. goto fail;
  1561. slab = &hslab->uhs_slab;
  1562. }
  1563. /*
  1564. * This reproduces the old vm_zone behavior of zero filling pages the
  1565. * first time they are added to a zone.
  1566. *
  1567. * Malloced items are zeroed in uma_zalloc.
  1568. */
  1569. if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
  1570. aflags |= M_ZERO;
  1571. else
  1572. aflags &= ~M_ZERO;
  1573. if (keg->uk_flags & UMA_ZONE_NODUMP)
  1574. aflags |= M_NODUMP;
  1575. /* zone is passed for legacy reasons. */
  1576. size = keg->uk_ppera * PAGE_SIZE;
  1577. mem = keg->uk_allocf(zone, size, domain, &sflags, aflags);
  1578. if (mem == NULL) {
  1579. if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
  1580. zone_free_item(slabzone(keg->uk_ipers),
  1581. slab_tohashslab(slab), NULL, SKIP_NONE);
  1582. goto fail;
  1583. }
  1584. uma_total_inc(size);
  1585. /* For HASH zones all pages go to the same uma_domain. */
  1586. if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
  1587. domain = 0;
  1588. kmsan_mark(mem, size,
  1589. (aflags & M_ZERO) != 0 ? KMSAN_STATE_INITED : KMSAN_STATE_UNINIT);
  1590. /* Point the slab into the allocated memory */
  1591. if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
  1592. slab = (uma_slab_t)(mem + keg->uk_pgoff);
  1593. else
  1594. slab_tohashslab(slab)->uhs_data = mem;
  1595. if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
  1596. for (i = 0; i < keg->uk_ppera; i++)
  1597. vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
  1598. zone, slab);
  1599. slab->us_freecount = keg->uk_ipers;
  1600. slab->us_flags = sflags;
  1601. slab->us_domain = domain;
  1602. BIT_FILL(keg->uk_ipers, &slab->us_free);
  1603. #ifdef INVARIANTS
  1604. BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
  1605. #endif
  1606. if (keg->uk_init != NULL) {
  1607. for (i = 0; i < keg->uk_ipers; i++)
  1608. if (keg->uk_init(slab_item(slab, keg, i),
  1609. keg->uk_size, flags) != 0)
  1610. break;
  1611. if (i != keg->uk_ipers) {
  1612. keg_free_slab(keg, slab, i);
  1613. goto fail;
  1614. }
  1615. }
  1616. kasan_mark_slab_invalid(keg, mem);
  1617. KEG_LOCK(keg, domain);
  1618. CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
  1619. slab, keg->uk_name, keg);
  1620. if (keg->uk_flags & UMA_ZFLAG_HASH)
  1621. UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
  1622. /*
  1623. * If we got a slab here it's safe to mark it partially used
  1624. * and return. We assume that the caller is going to remove
  1625. * at least one item.
  1626. */
  1627. dom = &keg->uk_domain[domain];
  1628. LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
  1629. dom->ud_pages += keg->uk_ppera;
  1630. dom->ud_free_items += keg->uk_ipers;
  1631. TSEXIT();
  1632. return (slab);
  1633. fail:
  1634. return (NULL);
  1635. }
  1636. /*
  1637. * This function is intended to be used early on in place of page_alloc(). It
  1638. * performs contiguous physical memory allocations and uses a bump allocator for
  1639. * KVA, so is usable before the kernel map is initialized.
  1640. */
  1641. static void *
  1642. startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
  1643. int wait)
  1644. {
  1645. vm_paddr_t pa;
  1646. vm_page_t m;
  1647. int i, pages;
  1648. pages = howmany(bytes, PAGE_SIZE);
  1649. KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
  1650. *pflag = UMA_SLAB_BOOT;
  1651. m = vm_page_alloc_noobj_contig_domain(domain, malloc2vm_flags(wait) |
  1652. VM_ALLOC_WIRED, pages, (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0,
  1653. VM_MEMATTR_DEFAULT);
  1654. if (m == NULL)
  1655. return (NULL);
  1656. pa = VM_PAGE_TO_PHYS(m);
  1657. for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
  1658. #if MINIDUMP_PAGE_TRACKING && MINIDUMP_STARTUP_PAGE_TRACKING
  1659. if ((wait & M_NODUMP) == 0)
  1660. dump_add_page(pa);
  1661. #endif
  1662. }
  1663. /* Allocate KVA and indirectly advance bootmem. */
  1664. return ((void *)pmap_map(&bootmem, m->phys_addr,
  1665. m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE));
  1666. }
  1667. static void
  1668. startup_free(void *mem, vm_size_t bytes)
  1669. {
  1670. vm_offset_t va;
  1671. vm_page_t m;
  1672. va = (vm_offset_t)mem;
  1673. m = PHYS_TO_VM_PAGE(pmap_kextract(va));
  1674. /*
  1675. * startup_alloc() returns direct-mapped slabs on some platforms. Avoid
  1676. * unmapping ranges of the direct map.
  1677. */
  1678. if (va >= bootstart && va + bytes <= bootmem)
  1679. pmap_remove(kernel_pmap, va, va + bytes);
  1680. for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
  1681. #if MINIDUMP_PAGE_TRACKING && MINIDUMP_STARTUP_PAGE_TRACKING
  1682. dump_drop_page(VM_PAGE_TO_PHYS(m));
  1683. #endif
  1684. vm_page_unwire_noq(m);
  1685. vm_page_free(m);
  1686. }
  1687. }
  1688. /*
  1689. * Allocates a number of pages from the system
  1690. *
  1691. * Arguments:
  1692. * bytes The number of bytes requested
  1693. * wait Shall we wait?
  1694. *
  1695. * Returns:
  1696. * A pointer to the alloced memory or possibly
  1697. * NULL if M_NOWAIT is set.
  1698. */
  1699. static void *
  1700. page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
  1701. int wait)
  1702. {
  1703. void *p; /* Returned page */
  1704. *pflag = UMA_SLAB_KERNEL;
  1705. p = kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
  1706. return (p);
  1707. }
  1708. static void *
  1709. pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
  1710. int wait)
  1711. {
  1712. struct pglist alloctail;
  1713. vm_offset_t addr, zkva;
  1714. int cpu, flags;
  1715. vm_page_t p, p_next;
  1716. #ifdef NUMA
  1717. struct pcpu *pc;
  1718. #endif
  1719. MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
  1720. TAILQ_INIT(&alloctail);
  1721. flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | malloc2vm_flags(wait);
  1722. *pflag = UMA_SLAB_KERNEL;
  1723. for (cpu = 0; cpu <= mp_maxid; cpu++) {
  1724. if (CPU_ABSENT(cpu)) {
  1725. p = vm_page_alloc_noobj(flags);
  1726. } else {
  1727. #ifndef NUMA
  1728. p = vm_page_alloc_noobj(flags);
  1729. #else
  1730. pc = pcpu_find(cpu);
  1731. if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
  1732. p = NULL;
  1733. else
  1734. p = vm_page_alloc_noobj_domain(pc->pc_domain,
  1735. flags);
  1736. if (__predict_false(p == NULL))
  1737. p = vm_page_alloc_noobj(flags);
  1738. #endif
  1739. }
  1740. if (__predict_false(p == NULL))
  1741. goto fail;
  1742. TAILQ_INSERT_TAIL(&alloctail, p, listq);
  1743. }
  1744. if ((addr = kva_alloc(bytes)) == 0)
  1745. goto fail;
  1746. zkva = addr;
  1747. TAILQ_FOREACH(p, &alloctail, listq) {
  1748. pmap_qenter(zkva, &p, 1);
  1749. zkva += PAGE_SIZE;
  1750. }
  1751. return ((void*)addr);
  1752. fail:
  1753. TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
  1754. vm_page_unwire_noq(p);
  1755. vm_page_free(p);
  1756. }
  1757. return (NULL);
  1758. }
  1759. /*
  1760. * Allocates a number of pages not belonging to a VM object
  1761. *
  1762. * Arguments:
  1763. * bytes The number of bytes requested
  1764. * wait Shall we wait?
  1765. *
  1766. * Returns:
  1767. * A pointer to the alloced memory or possibly
  1768. * NULL if M_NOWAIT is set.
  1769. */
  1770. static void *
  1771. noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
  1772. int wait)
  1773. {
  1774. TAILQ_HEAD(, vm_page) alloctail;
  1775. u_long npages;
  1776. vm_offset_t retkva, zkva;
  1777. vm_page_t p, p_next;
  1778. uma_keg_t keg;
  1779. int req;
  1780. TAILQ_INIT(&alloctail);
  1781. keg = zone->uz_keg;
  1782. req = VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED;
  1783. if ((wait & M_WAITOK) != 0)
  1784. req |= VM_ALLOC_WAITOK;
  1785. npages = howmany(bytes, PAGE_SIZE);
  1786. while (npages > 0) {
  1787. p = vm_page_alloc_noobj_domain(domain, req);
  1788. if (p != NULL) {
  1789. /*
  1790. * Since the page does not belong to an object, its
  1791. * listq is unused.
  1792. */
  1793. TAILQ_INSERT_TAIL(&alloctail, p, listq);
  1794. npages--;
  1795. continue;
  1796. }
  1797. /*
  1798. * Page allocation failed, free intermediate pages and
  1799. * exit.
  1800. */
  1801. TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
  1802. vm_page_unwire_noq(p);
  1803. vm_page_free(p);
  1804. }
  1805. return (NULL);
  1806. }
  1807. *flags = UMA_SLAB_PRIV;
  1808. zkva = keg->uk_kva +
  1809. atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
  1810. retkva = zkva;
  1811. TAILQ_FOREACH(p, &alloctail, listq) {
  1812. pmap_qenter(zkva, &p, 1);
  1813. zkva += PAGE_SIZE;
  1814. }
  1815. return ((void *)retkva);
  1816. }
  1817. /*
  1818. * Allocate physically contiguous pages.
  1819. */
  1820. static void *
  1821. contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
  1822. int wait)
  1823. {
  1824. *pflag = UMA_SLAB_KERNEL;
  1825. return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
  1826. bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
  1827. }
  1828. #if defined(UMA_USE_DMAP) && !defined(UMA_MD_SMALL_ALLOC)
  1829. void *
  1830. uma_small_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
  1831. int wait)
  1832. {
  1833. vm_page_t m;
  1834. vm_paddr_t pa;
  1835. void *va;
  1836. *flags = UMA_SLAB_PRIV;
  1837. m = vm_page_alloc_noobj_domain(domain,
  1838. malloc2vm_flags(wait) | VM_ALLOC_WIRED);
  1839. if (m == NULL)
  1840. return (NULL);
  1841. pa = m->phys_addr;
  1842. if ((wait & M_NODUMP) == 0)
  1843. dump_add_page(pa);
  1844. va = (void *)PHYS_TO_DMAP(pa);
  1845. return (va);
  1846. }
  1847. #endif
  1848. /*
  1849. * Frees a number of pages to the system
  1850. *
  1851. * Arguments:
  1852. * mem A pointer to the memory to be freed
  1853. * size The size of the memory being freed
  1854. * flags The original p->us_flags field
  1855. *
  1856. * Returns:
  1857. * Nothing
  1858. */
  1859. static void
  1860. page_free(void *mem, vm_size_t size, uint8_t flags)
  1861. {
  1862. if ((flags & UMA_SLAB_BOOT) != 0) {
  1863. startup_free(mem, size);
  1864. return;
  1865. }
  1866. KASSERT((flags & UMA_SLAB_KERNEL) != 0,
  1867. ("UMA: page_free used with invalid flags %x", flags));
  1868. kmem_free(mem, size);
  1869. }
  1870. /*
  1871. * Frees pcpu zone allocations
  1872. *
  1873. * Arguments:
  1874. * mem A pointer to the memory to be freed
  1875. * size The size of the memory being freed
  1876. * flags The original p->us_flags field
  1877. *
  1878. * Returns:
  1879. * Nothing
  1880. */
  1881. static void
  1882. pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
  1883. {
  1884. vm_offset_t sva, curva;
  1885. vm_paddr_t paddr;
  1886. vm_page_t m;
  1887. MPASS(size == (mp_maxid+1)*PAGE_SIZE);
  1888. if ((flags & UMA_SLAB_BOOT) != 0) {
  1889. startup_free(mem, size);
  1890. return;
  1891. }
  1892. sva = (vm_offset_t)mem;
  1893. for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
  1894. paddr = pmap_kextract(curva);
  1895. m = PHYS_TO_VM_PAGE(paddr);
  1896. vm_page_unwire_noq(m);
  1897. vm_page_free(m);
  1898. }
  1899. pmap_qremove(sva, size >> PAGE_SHIFT);
  1900. kva_free(sva, size);
  1901. }
  1902. #if defined(UMA_USE_DMAP) && !defined(UMA_MD_SMALL_ALLOC)
  1903. void
  1904. uma_small_free(void *mem, vm_size_t size, uint8_t flags)
  1905. {
  1906. vm_page_t m;
  1907. vm_paddr_t pa;
  1908. pa = DMAP_TO_PHYS((vm_offset_t)mem);
  1909. dump_drop_page(pa);
  1910. m = PHYS_TO_VM_PAGE(pa);
  1911. vm_page_unwire_noq(m);
  1912. vm_page_free(m);
  1913. }
  1914. #endif
  1915. /*
  1916. * Zero fill initializer
  1917. *
  1918. * Arguments/Returns follow uma_init specifications
  1919. */
  1920. static int
  1921. zero_init(void *mem, int size, int flags)
  1922. {
  1923. bzero(mem, size);
  1924. return (0);
  1925. }
  1926. #ifdef INVARIANTS
  1927. static struct noslabbits *
  1928. slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
  1929. {
  1930. return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
  1931. }
  1932. #endif
  1933. /*
  1934. * Actual size of embedded struct slab (!OFFPAGE).
  1935. */
  1936. static size_t
  1937. slab_sizeof(int nitems)
  1938. {
  1939. size_t s;
  1940. s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
  1941. return (roundup(s, UMA_ALIGN_PTR + 1));
  1942. }
  1943. #define UMA_FIXPT_SHIFT 31
  1944. #define UMA_FRAC_FIXPT(n, d) \
  1945. ((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
  1946. #define UMA_FIXPT_PCT(f) \
  1947. ((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
  1948. #define UMA_PCT_FIXPT(pct) UMA_FRAC_FIXPT((pct), 100)
  1949. #define UMA_MIN_EFF UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
  1950. /*
  1951. * Compute the number of items that will fit in a slab. If hdr is true, the
  1952. * item count may be limited to provide space in the slab for an inline slab
  1953. * header. Otherwise, all slab space will be provided for item storage.
  1954. */
  1955. static u_int
  1956. slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
  1957. {
  1958. u_int ipers;
  1959. u_int padpi;
  1960. /* The padding between items is not needed after the last item. */
  1961. padpi = rsize - size;
  1962. if (hdr) {
  1963. /*
  1964. * Start with the maximum item count and remove items until
  1965. * the slab header first alongside the allocatable memory.
  1966. */
  1967. for (ipers = MIN(SLAB_MAX_SETSIZE,
  1968. (slabsize + padpi - slab_sizeof(1)) / rsize);
  1969. ipers > 0 &&
  1970. ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
  1971. ipers--)
  1972. continue;
  1973. } else {
  1974. ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
  1975. }
  1976. return (ipers);
  1977. }
  1978. struct keg_layout_result {
  1979. u_int format;
  1980. u_int slabsize;
  1981. u_int ipers;
  1982. u_int eff;
  1983. };
  1984. static void
  1985. keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
  1986. struct keg_layout_result *kl)
  1987. {
  1988. u_int total;
  1989. kl->format = fmt;
  1990. kl->slabsize = slabsize;
  1991. /* Handle INTERNAL as inline with an extra page. */
  1992. if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
  1993. kl->format &= ~UMA_ZFLAG_INTERNAL;
  1994. kl->slabsize += PAGE_SIZE;
  1995. }
  1996. kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
  1997. (fmt & UMA_ZFLAG_OFFPAGE) == 0);
  1998. /* Account for memory used by an offpage slab header. */
  1999. total = kl->slabsize;
  2000. if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
  2001. total += slabzone(kl->ipers)->uz_keg->uk_rsize;
  2002. kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
  2003. }
  2004. /*
  2005. * Determine the format of a uma keg. This determines where the slab header
  2006. * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
  2007. *
  2008. * Arguments
  2009. * keg The zone we should initialize
  2010. *
  2011. * Returns
  2012. * Nothing
  2013. */
  2014. static void
  2015. keg_layout(uma_keg_t keg)
  2016. {
  2017. struct keg_layout_result kl = {}, kl_tmp;
  2018. u_int fmts[2];
  2019. u_int alignsize;
  2020. u_int nfmt;
  2021. u_int pages;
  2022. u_int rsize;
  2023. u_int slabsize;
  2024. u_int i, j;
  2025. KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
  2026. (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
  2027. (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
  2028. ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
  2029. __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
  2030. PRINT_UMA_ZFLAGS));
  2031. KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
  2032. (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
  2033. ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
  2034. PRINT_UMA_ZFLAGS));
  2035. alignsize = keg->uk_align + 1;
  2036. #ifdef KASAN
  2037. /*
  2038. * ASAN requires that each allocation be aligned to the shadow map
  2039. * scale factor.
  2040. */
  2041. if (alignsize < KASAN_SHADOW_SCALE)
  2042. alignsize = KASAN_SHADOW_SCALE;
  2043. #endif
  2044. /*
  2045. * Calculate the size of each allocation (rsize) according to
  2046. * alignment. If the requested size is smaller than we have
  2047. * allocation bits for we round it up.
  2048. */
  2049. rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
  2050. rsize = roundup2(rsize, alignsize);
  2051. if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
  2052. /*
  2053. * We want one item to start on every align boundary in a page.
  2054. * To do this we will span pages. We will also extend the item
  2055. * by the size of align if it is an even multiple of align.
  2056. * Otherwise, it would fall on the same boundary every time.
  2057. */
  2058. if ((rsize & alignsize) == 0)
  2059. rsize += alignsize;
  2060. slabsize = rsize * (PAGE_SIZE / alignsize);
  2061. slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
  2062. slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
  2063. slabsize = round_page(slabsize);
  2064. } else {
  2065. /*
  2066. * Start with a slab size of as many pages as it takes to
  2067. * represent a single item. We will try to fit as many
  2068. * additional items into the slab as possible.
  2069. */
  2070. slabsize = round_page(keg->uk_size);
  2071. }
  2072. /* Build a list of all of the available formats for this keg. */
  2073. nfmt = 0;
  2074. /* Evaluate an inline slab layout. */
  2075. if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
  2076. fmts[nfmt++] = 0;
  2077. /* TODO: vm_page-embedded slab. */
  2078. /*
  2079. * We can't do OFFPAGE if we're internal or if we've been
  2080. * asked to not go to the VM for buckets. If we do this we
  2081. * may end up going to the VM for slabs which we do not want
  2082. * to do if we're UMA_ZONE_VM, which clearly forbids it.
  2083. * In those cases, evaluate a pseudo-format called INTERNAL
  2084. * which has an inline slab header and one extra page to
  2085. * guarantee that it fits.
  2086. *
  2087. * Otherwise, see if using an OFFPAGE slab will improve our
  2088. * efficiency.
  2089. */
  2090. if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
  2091. fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
  2092. else
  2093. fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
  2094. /*
  2095. * Choose a slab size and format which satisfy the minimum efficiency.
  2096. * Prefer the smallest slab size that meets the constraints.
  2097. *
  2098. * Start with a minimum slab size, to accommodate CACHESPREAD. Then,
  2099. * for small items (up to PAGE_SIZE), the iteration increment is one
  2100. * page; and for large items, the increment is one item.
  2101. */
  2102. i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
  2103. KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
  2104. keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
  2105. rsize, i));
  2106. for ( ; ; i++) {
  2107. slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
  2108. round_page(rsize * (i - 1) + keg->uk_size);
  2109. for (j = 0; j < nfmt; j++) {
  2110. /* Only if we have no viable format yet. */
  2111. if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
  2112. kl.ipers > 0)
  2113. continue;
  2114. keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
  2115. if (kl_tmp.eff <= kl.eff)
  2116. continue;
  2117. kl = kl_tmp;
  2118. CTR6(KTR_UMA, "keg %s layout: format %#x "
  2119. "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
  2120. keg->uk_name, kl.format, kl.ipers, rsize,
  2121. kl.slabsize, UMA_FIXPT_PCT(kl.eff));
  2122. /* Stop when we reach the minimum efficiency. */
  2123. if (kl.eff >= UMA_MIN_EFF)
  2124. break;
  2125. }
  2126. if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
  2127. slabsize >= SLAB_MAX_SETSIZE * rsize ||
  2128. (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
  2129. break;
  2130. }
  2131. pages = atop(kl.slabsize);
  2132. if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
  2133. pages *= mp_maxid + 1;
  2134. keg->uk_rsize = rsize;
  2135. keg->uk_ipers = kl.ipers;
  2136. keg->uk_ppera = pages;
  2137. keg->uk_flags |= kl.format;
  2138. /*
  2139. * How do we find the slab header if it is offpage or if not all item
  2140. * start addresses are in the same page? We could solve the latter
  2141. * case with vaddr alignment, but we don't.
  2142. */
  2143. if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
  2144. (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
  2145. if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
  2146. keg->uk_flags |= UMA_ZFLAG_HASH;
  2147. else
  2148. keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
  2149. }
  2150. CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
  2151. __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
  2152. pages);
  2153. KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
  2154. ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
  2155. keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
  2156. keg->uk_ipers, pages));
  2157. }
  2158. /*
  2159. * Keg header ctor. This initializes all fields, locks, etc. And inserts
  2160. * the keg onto the global keg list.
  2161. *
  2162. * Arguments/Returns follow uma_ctor specifications
  2163. * udata Actually uma_kctor_args
  2164. */
  2165. static int
  2166. keg_ctor(void *mem, int size, void *udata, int flags)
  2167. {
  2168. struct uma_kctor_args *arg = udata;
  2169. uma_keg_t keg = mem;
  2170. uma_zone_t zone;
  2171. int i;
  2172. bzero(keg, size);
  2173. keg->uk_size = arg->size;
  2174. keg->uk_init = arg->uminit;
  2175. keg->uk_fini = arg->fini;
  2176. keg->uk_align = arg->align;
  2177. keg->uk_reserve = 0;
  2178. keg->uk_flags = arg->flags;
  2179. /*
  2180. * We use a global round-robin policy by default. Zones with
  2181. * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
  2182. * case the iterator is never run.
  2183. */
  2184. keg->uk_dr.dr_policy = DOMAINSET_RR();
  2185. keg->uk_dr.dr_iter = 0;
  2186. /*
  2187. * The primary zone is passed to us at keg-creation time.
  2188. */
  2189. zone = arg->zone;
  2190. keg->uk_name = zone->uz_name;
  2191. if (arg->flags & UMA_ZONE_ZINIT)
  2192. keg->uk_init = zero_init;
  2193. if (arg->flags & UMA_ZONE_MALLOC)
  2194. keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
  2195. #ifndef SMP
  2196. keg->uk_flags &= ~UMA_ZONE_PCPU;
  2197. #endif
  2198. keg_layout(keg);
  2199. /*
  2200. * Use a first-touch NUMA policy for kegs that pmap_extract() will
  2201. * work on. Use round-robin for everything else.
  2202. *
  2203. * Zones may override the default by specifying either.
  2204. */
  2205. #ifdef NUMA
  2206. if ((keg->uk_flags &
  2207. (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
  2208. keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
  2209. else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
  2210. keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
  2211. #endif
  2212. /*
  2213. * If we haven't booted yet we need allocations to go through the
  2214. * startup cache until the vm is ready.
  2215. */
  2216. #ifdef UMA_USE_DMAP
  2217. if (keg->uk_ppera == 1)
  2218. keg->uk_allocf = uma_small_alloc;
  2219. else
  2220. #endif
  2221. if (booted < BOOT_KVA)
  2222. keg->uk_allocf = startup_alloc;
  2223. else if (keg->uk_flags & UMA_ZONE_PCPU)
  2224. keg->uk_allocf = pcpu_page_alloc;
  2225. else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
  2226. keg->uk_allocf = contig_alloc;
  2227. else
  2228. keg->uk_allocf = page_alloc;
  2229. #ifdef UMA_USE_DMAP
  2230. if (keg->uk_ppera == 1)
  2231. keg->uk_freef = uma_small_free;
  2232. else
  2233. #endif
  2234. if (keg->uk_flags & UMA_ZONE_PCPU)
  2235. keg->uk_freef = pcpu_page_free;
  2236. else
  2237. keg->uk_freef = page_free;
  2238. /*
  2239. * Initialize keg's locks.
  2240. */
  2241. for (i = 0; i < vm_ndomains; i++)
  2242. KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
  2243. /*
  2244. * If we're putting the slab header in the actual page we need to
  2245. * figure out where in each page it goes. See slab_sizeof
  2246. * definition.
  2247. */
  2248. if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
  2249. size_t shsize;
  2250. shsize = slab_sizeof(keg->uk_ipers);
  2251. keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
  2252. /*
  2253. * The only way the following is possible is if with our
  2254. * UMA_ALIGN_PTR adjustments we are now bigger than
  2255. * UMA_SLAB_SIZE. I haven't checked whether this is
  2256. * mathematically possible for all cases, so we make
  2257. * sure here anyway.
  2258. */
  2259. KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
  2260. ("zone %s ipers %d rsize %d size %d slab won't fit",
  2261. zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
  2262. }
  2263. if (keg->uk_flags & UMA_ZFLAG_HASH)
  2264. hash_alloc(&keg->uk_hash, 0);
  2265. CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
  2266. LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
  2267. rw_wlock(&uma_rwlock);
  2268. LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
  2269. rw_wunlock(&uma_rwlock);
  2270. return (0);
  2271. }
  2272. static void
  2273. zone_kva_available(uma_zone_t zone, void *unused)
  2274. {
  2275. uma_keg_t keg;
  2276. if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
  2277. return;
  2278. KEG_GET(zone, keg);
  2279. if (keg->uk_allocf == startup_alloc) {
  2280. /* Switch to the real allocator. */
  2281. if (keg->uk_flags & UMA_ZONE_PCPU)
  2282. keg->uk_allocf = pcpu_page_alloc;
  2283. else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
  2284. keg->uk_ppera > 1)
  2285. keg->uk_allocf = contig_alloc;
  2286. else
  2287. keg->uk_allocf = page_alloc;
  2288. }
  2289. }
  2290. static void
  2291. zone_alloc_counters(uma_zone_t zone, void *unused)
  2292. {
  2293. zone->uz_allocs = counter_u64_alloc(M_WAITOK);
  2294. zone->uz_frees = counter_u64_alloc(M_WAITOK);
  2295. zone->uz_fails = counter_u64_alloc(M_WAITOK);
  2296. zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
  2297. }
  2298. static void
  2299. zone_alloc_sysctl(uma_zone_t zone, void *unused)
  2300. {
  2301. uma_zone_domain_t zdom;
  2302. uma_domain_t dom;
  2303. uma_keg_t keg;
  2304. struct sysctl_oid *oid, *domainoid;
  2305. int domains, i, cnt;
  2306. static const char *nokeg = "cache zone";
  2307. char *c;
  2308. /*
  2309. * Make a sysctl safe copy of the zone name by removing
  2310. * any special characters and handling dups by appending
  2311. * an index.
  2312. */
  2313. if (zone->uz_namecnt != 0) {
  2314. /* Count the number of decimal digits and '_' separator. */
  2315. for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
  2316. cnt /= 10;
  2317. zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
  2318. M_UMA, M_WAITOK);
  2319. sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
  2320. zone->uz_namecnt);
  2321. } else
  2322. zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
  2323. for (c = zone->uz_ctlname; *c != '\0'; c++)
  2324. if (strchr("./\\ -", *c) != NULL)
  2325. *c = '_';
  2326. /*
  2327. * Basic parameters at the root.
  2328. */
  2329. zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
  2330. OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2331. oid = zone->uz_oid;
  2332. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2333. "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
  2334. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2335. "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
  2336. zone, 0, sysctl_handle_uma_zone_flags, "A",
  2337. "Allocator configuration flags");
  2338. SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2339. "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
  2340. "Desired per-cpu cache size");
  2341. SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2342. "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
  2343. "Maximum allowed per-cpu cache size");
  2344. /*
  2345. * keg if present.
  2346. */
  2347. if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
  2348. domains = vm_ndomains;
  2349. else
  2350. domains = 1;
  2351. oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
  2352. "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2353. keg = zone->uz_keg;
  2354. if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
  2355. SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2356. "name", CTLFLAG_RD, keg->uk_name, "Keg name");
  2357. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2358. "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
  2359. "Real object size with alignment");
  2360. SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2361. "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
  2362. "pages per-slab allocation");
  2363. SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2364. "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
  2365. "items available per-slab");
  2366. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2367. "align", CTLFLAG_RD, &keg->uk_align, 0,
  2368. "item alignment mask");
  2369. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2370. "reserve", CTLFLAG_RD, &keg->uk_reserve, 0,
  2371. "number of reserved items");
  2372. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2373. "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
  2374. keg, 0, sysctl_handle_uma_slab_efficiency, "I",
  2375. "Slab utilization (100 - internal fragmentation %)");
  2376. domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
  2377. OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2378. for (i = 0; i < domains; i++) {
  2379. dom = &keg->uk_domain[i];
  2380. oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
  2381. OID_AUTO, VM_DOMAIN(i)->vmd_name,
  2382. CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2383. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2384. "pages", CTLFLAG_RD, &dom->ud_pages, 0,
  2385. "Total pages currently allocated from VM");
  2386. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2387. "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
  2388. "Items free in the slab layer");
  2389. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2390. "free_slabs", CTLFLAG_RD, &dom->ud_free_slabs, 0,
  2391. "Unused slabs");
  2392. }
  2393. } else
  2394. SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2395. "name", CTLFLAG_RD, nokeg, "Keg name");
  2396. /*
  2397. * Information about zone limits.
  2398. */
  2399. oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
  2400. "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2401. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2402. "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
  2403. zone, 0, sysctl_handle_uma_zone_items, "QU",
  2404. "Current number of allocated items if limit is set");
  2405. SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2406. "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
  2407. "Maximum number of allocated and cached items");
  2408. SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2409. "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
  2410. "Number of threads sleeping at limit");
  2411. SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2412. "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
  2413. "Total zone limit sleeps");
  2414. SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2415. "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
  2416. "Maximum number of items in each domain's bucket cache");
  2417. /*
  2418. * Per-domain zone information.
  2419. */
  2420. domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
  2421. OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2422. for (i = 0; i < domains; i++) {
  2423. zdom = ZDOM_GET(zone, i);
  2424. oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
  2425. OID_AUTO, VM_DOMAIN(i)->vmd_name,
  2426. CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2427. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2428. "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
  2429. "number of items in this domain");
  2430. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2431. "imax", CTLFLAG_RD, &zdom->uzd_imax,
  2432. "maximum item count in this period");
  2433. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2434. "imin", CTLFLAG_RD, &zdom->uzd_imin,
  2435. "minimum item count in this period");
  2436. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2437. "bimin", CTLFLAG_RD, &zdom->uzd_bimin,
  2438. "Minimum item count in this batch");
  2439. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2440. "wss", CTLFLAG_RD, &zdom->uzd_wss,
  2441. "Working set size");
  2442. SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2443. "limin", CTLFLAG_RD, &zdom->uzd_limin,
  2444. "Long time minimum item count");
  2445. SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2446. "timin", CTLFLAG_RD, &zdom->uzd_timin, 0,
  2447. "Time since zero long time minimum item count");
  2448. }
  2449. /*
  2450. * General statistics.
  2451. */
  2452. oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
  2453. "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
  2454. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2455. "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
  2456. zone, 1, sysctl_handle_uma_zone_cur, "I",
  2457. "Current number of allocated items");
  2458. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2459. "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
  2460. zone, 0, sysctl_handle_uma_zone_allocs, "QU",
  2461. "Total allocation calls");
  2462. SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2463. "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
  2464. zone, 0, sysctl_handle_uma_zone_frees, "QU",
  2465. "Total free calls");
  2466. SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2467. "fails", CTLFLAG_RD, &zone->uz_fails,
  2468. "Number of allocation failures");
  2469. SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
  2470. "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
  2471. "Free calls from the wrong domain");
  2472. }
  2473. struct uma_zone_count {
  2474. const char *name;
  2475. int count;
  2476. };
  2477. static void
  2478. zone_count(uma_zone_t zone, void *arg)
  2479. {
  2480. struct uma_zone_count *cnt;
  2481. cnt = arg;
  2482. /*
  2483. * Some zones are rapidly created with identical names and
  2484. * destroyed out of order. This can lead to gaps in the count.
  2485. * Use one greater than the maximum observed for this name.
  2486. */
  2487. if (strcmp(zone->uz_name, cnt->name) == 0)
  2488. cnt->count = MAX(cnt->count,
  2489. zone->uz_namecnt + 1);
  2490. }
  2491. static void
  2492. zone_update_caches(uma_zone_t zone)
  2493. {
  2494. int i;
  2495. for (i = 0; i <= mp_maxid; i++) {
  2496. cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
  2497. cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
  2498. }
  2499. }
  2500. /*
  2501. * Zone header ctor. This initializes all fields, locks, etc.
  2502. *
  2503. * Arguments/Returns follow uma_ctor specifications
  2504. * udata Actually uma_zctor_args
  2505. */
  2506. static int
  2507. zone_ctor(void *mem, int size, void *udata, int flags)
  2508. {
  2509. struct uma_zone_count cnt;
  2510. struct uma_zctor_args *arg = udata;
  2511. uma_zone_domain_t zdom;
  2512. uma_zone_t zone = mem;
  2513. uma_zone_t z;
  2514. uma_keg_t keg;
  2515. int i;
  2516. bzero(zone, size);
  2517. zone->uz_name = arg->name;
  2518. zone->uz_ctor = arg->ctor;
  2519. zone->uz_dtor = arg->dtor;
  2520. zone->uz_init = NULL;
  2521. zone->uz_fini = NULL;
  2522. zone->uz_sleeps = 0;
  2523. zone->uz_bucket_size = 0;
  2524. zone->uz_bucket_size_min = 0;
  2525. zone->uz_bucket_size_max = BUCKET_MAX;
  2526. zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
  2527. zone->uz_warning = NULL;
  2528. /* The domain structures follow the cpu structures. */
  2529. zone->uz_bucket_max = ULONG_MAX;
  2530. timevalclear(&zone->uz_ratecheck);
  2531. /* Count the number of duplicate names. */
  2532. cnt.name = arg->name;
  2533. cnt.count = 0;
  2534. zone_foreach(zone_count, &cnt);
  2535. zone->uz_namecnt = cnt.count;
  2536. ZONE_CROSS_LOCK_INIT(zone);
  2537. for (i = 0; i < vm_ndomains; i++) {
  2538. zdom = ZDOM_GET(zone, i);
  2539. ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
  2540. STAILQ_INIT(&zdom->uzd_buckets);
  2541. }
  2542. #if defined(INVARIANTS) && !defined(KASAN) && !defined(KMSAN)
  2543. if (arg->uminit == trash_init && arg->fini == trash_fini)
  2544. zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
  2545. #elif defined(KASAN)
  2546. if ((arg->flags & (UMA_ZONE_NOFREE | UMA_ZFLAG_CACHE)) != 0)
  2547. arg->flags |= UMA_ZONE_NOKASAN;
  2548. #endif
  2549. /*
  2550. * This is a pure cache zone, no kegs.
  2551. */
  2552. if (arg->import) {
  2553. KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
  2554. ("zone_ctor: Import specified for non-cache zone."));
  2555. zone->uz_flags = arg->flags;
  2556. zone->uz_size = arg->size;
  2557. zone->uz_import = arg->import;
  2558. zone->uz_release = arg->release;
  2559. zone->uz_arg = arg->arg;
  2560. #ifdef NUMA
  2561. /*
  2562. * Cache zones are round-robin unless a policy is
  2563. * specified because they may have incompatible
  2564. * constraints.
  2565. */
  2566. if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
  2567. zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
  2568. #endif
  2569. rw_wlock(&uma_rwlock);
  2570. LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
  2571. rw_wunlock(&uma_rwlock);
  2572. goto out;
  2573. }
  2574. /*
  2575. * Use the regular zone/keg/slab allocator.
  2576. */
  2577. zone->uz_import = zone_import;
  2578. zone->uz_release = zone_release;
  2579. zone->uz_arg = zone;
  2580. keg = arg->keg;
  2581. if (arg->flags & UMA_ZONE_SECONDARY) {
  2582. KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
  2583. ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
  2584. KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
  2585. zone->uz_init = arg->uminit;
  2586. zone->uz_fini = arg->fini;
  2587. zone->uz_flags |= UMA_ZONE_SECONDARY;
  2588. rw_wlock(&uma_rwlock);
  2589. ZONE_LOCK(zone);
  2590. LIST_FOREACH(z, &keg->uk_zones, uz_link) {
  2591. if (LIST_NEXT(z, uz_link) == NULL) {
  2592. LIST_INSERT_AFTER(z, zone, uz_link);
  2593. break;
  2594. }
  2595. }
  2596. ZONE_UNLOCK(zone);
  2597. rw_wunlock(&uma_rwlock);
  2598. } else if (keg == NULL) {
  2599. if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
  2600. arg->align, arg->flags)) == NULL)
  2601. return (ENOMEM);
  2602. } else {
  2603. struct uma_kctor_args karg;
  2604. int error;
  2605. /* We should only be here from uma_startup() */
  2606. karg.size = arg->size;
  2607. karg.uminit = arg->uminit;
  2608. karg.fini = arg->fini;
  2609. karg.align = arg->align;
  2610. karg.flags = (arg->flags & ~UMA_ZONE_SMR);
  2611. karg.zone = zone;
  2612. error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
  2613. flags);
  2614. if (error)
  2615. return (error);
  2616. }
  2617. /* Inherit properties from the keg. */
  2618. zone->uz_keg = keg;
  2619. zone->uz_size = keg->uk_size;
  2620. zone->uz_flags |= (keg->uk_flags &
  2621. (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
  2622. out:
  2623. if (booted >= BOOT_PCPU) {
  2624. zone_alloc_counters(zone, NULL);
  2625. if (booted >= BOOT_RUNNING)
  2626. zone_alloc_sysctl(zone, NULL);
  2627. } else {
  2628. zone->uz_allocs = EARLY_COUNTER;
  2629. zone->uz_frees = EARLY_COUNTER;
  2630. zone->uz_fails = EARLY_COUNTER;
  2631. }
  2632. /* Caller requests a private SMR context. */
  2633. if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
  2634. zone->uz_smr = smr_create(zone->uz_name, 0, 0);
  2635. KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
  2636. (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
  2637. ("Invalid zone flag combination"));
  2638. if (arg->flags & UMA_ZFLAG_INTERNAL)
  2639. zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
  2640. if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
  2641. zone->uz_bucket_size = BUCKET_MAX;
  2642. else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
  2643. zone->uz_bucket_size = 0;
  2644. else
  2645. zone->uz_bucket_size = bucket_select(zone->uz_size);
  2646. zone->uz_bucket_size_min = zone->uz_bucket_size;
  2647. if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
  2648. zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
  2649. zone_update_caches(zone);
  2650. return (0);
  2651. }
  2652. /*
  2653. * Keg header dtor. This frees all data, destroys locks, frees the hash
  2654. * table and removes the keg from the global list.
  2655. *
  2656. * Arguments/Returns follow uma_dtor specifications
  2657. * udata unused
  2658. */
  2659. static void
  2660. keg_dtor(void *arg, int size, void *udata)
  2661. {
  2662. uma_keg_t keg;
  2663. uint32_t free, pages;
  2664. int i;
  2665. keg = (uma_keg_t)arg;
  2666. free = pages = 0;
  2667. for (i = 0; i < vm_ndomains; i++) {
  2668. free += keg->uk_domain[i].ud_free_items;
  2669. pages += keg->uk_domain[i].ud_pages;
  2670. KEG_LOCK_FINI(keg, i);
  2671. }
  2672. if (pages != 0)
  2673. printf("Freed UMA keg (%s) was not empty (%u items). "
  2674. " Lost %u pages of memory.\n",
  2675. keg->uk_name ? keg->uk_name : "",
  2676. pages / keg->uk_ppera * keg->uk_ipers - free, pages);
  2677. hash_free(&keg->uk_hash);
  2678. }
  2679. /*
  2680. * Zone header dtor.
  2681. *
  2682. * Arguments/Returns follow uma_dtor specifications
  2683. * udata unused
  2684. */
  2685. static void
  2686. zone_dtor(void *arg, int size, void *udata)
  2687. {
  2688. uma_zone_t zone;
  2689. uma_keg_t keg;
  2690. int i;
  2691. zone = (uma_zone_t)arg;
  2692. sysctl_remove_oid(zone->uz_oid, 1, 1);
  2693. if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
  2694. cache_drain(zone);
  2695. rw_wlock(&uma_rwlock);
  2696. LIST_REMOVE(zone, uz_link);
  2697. rw_wunlock(&uma_rwlock);
  2698. if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
  2699. keg = zone->uz_keg;
  2700. keg->uk_reserve = 0;
  2701. }
  2702. zone_reclaim(zone, UMA_ANYDOMAIN, M_WAITOK, true);
  2703. /*
  2704. * We only destroy kegs from non secondary/non cache zones.
  2705. */
  2706. if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
  2707. keg = zone->uz_keg;
  2708. rw_wlock(&uma_rwlock);
  2709. LIST_REMOVE(keg, uk_link);
  2710. rw_wunlock(&uma_rwlock);
  2711. zone_free_item(kegs, keg, NULL, SKIP_NONE);
  2712. }
  2713. counter_u64_free(zone->uz_allocs);
  2714. counter_u64_free(zone->uz_frees);
  2715. counter_u64_free(zone->uz_fails);
  2716. counter_u64_free(zone->uz_xdomain);
  2717. free(zone->uz_ctlname, M_UMA);
  2718. for (i = 0; i < vm_ndomains; i++)
  2719. ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
  2720. ZONE_CROSS_LOCK_FINI(zone);
  2721. }
  2722. static void
  2723. zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
  2724. {
  2725. uma_keg_t keg;
  2726. uma_zone_t zone;
  2727. LIST_FOREACH(keg, &uma_kegs, uk_link) {
  2728. LIST_FOREACH(zone, &keg->uk_zones, uz_link)
  2729. zfunc(zone, arg);
  2730. }
  2731. LIST_FOREACH(zone, &uma_cachezones, uz_link)
  2732. zfunc(zone, arg);
  2733. }
  2734. /*
  2735. * Traverses every zone in the system and calls a callback
  2736. *
  2737. * Arguments:
  2738. * zfunc A pointer to a function which accepts a zone
  2739. * as an argument.
  2740. *
  2741. * Returns:
  2742. * Nothing
  2743. */
  2744. static void
  2745. zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
  2746. {
  2747. rw_rlock(&uma_rwlock);
  2748. zone_foreach_unlocked(zfunc, arg);
  2749. rw_runlock(&uma_rwlock);
  2750. }
  2751. /*
  2752. * Initialize the kernel memory allocator. This is done after pages can be
  2753. * allocated but before general KVA is available.
  2754. */
  2755. void
  2756. uma_startup1(vm_offset_t virtual_avail)
  2757. {
  2758. struct uma_zctor_args args;
  2759. size_t ksize, zsize, size;
  2760. uma_keg_t primarykeg;
  2761. uintptr_t m;
  2762. int domain;
  2763. uint8_t pflag;
  2764. bootstart = bootmem = virtual_avail;
  2765. rw_init(&uma_rwlock, "UMA lock");
  2766. sx_init(&uma_reclaim_lock, "umareclaim");
  2767. ksize = sizeof(struct uma_keg) +
  2768. (sizeof(struct uma_domain) * vm_ndomains);
  2769. ksize = roundup(ksize, UMA_SUPER_ALIGN);
  2770. zsize = sizeof(struct uma_zone) +
  2771. (sizeof(struct uma_cache) * (mp_maxid + 1)) +
  2772. (sizeof(struct uma_zone_domain) * vm_ndomains);
  2773. zsize = roundup(zsize, UMA_SUPER_ALIGN);
  2774. /* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
  2775. size = (zsize * 2) + ksize;
  2776. for (domain = 0; domain < vm_ndomains; domain++) {
  2777. m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
  2778. M_NOWAIT | M_ZERO);
  2779. if (m != 0)
  2780. break;
  2781. }
  2782. zones = (uma_zone_t)m;
  2783. m += zsize;
  2784. kegs = (uma_zone_t)m;
  2785. m += zsize;
  2786. primarykeg = (uma_keg_t)m;
  2787. /* "manually" create the initial zone */
  2788. memset(&args, 0, sizeof(args));
  2789. args.name = "UMA Kegs";
  2790. args.size = ksize;
  2791. args.ctor = keg_ctor;
  2792. args.dtor = keg_dtor;
  2793. args.uminit = zero_init;
  2794. args.fini = NULL;
  2795. args.keg = primarykeg;
  2796. args.align = UMA_SUPER_ALIGN - 1;
  2797. args.flags = UMA_ZFLAG_INTERNAL;
  2798. zone_ctor(kegs, zsize, &args, M_WAITOK);
  2799. args.name = "UMA Zones";
  2800. args.size = zsize;
  2801. args.ctor = zone_ctor;
  2802. args.dtor = zone_dtor;
  2803. args.uminit = zero_init;
  2804. args.fini = NULL;
  2805. args.keg = NULL;
  2806. args.align = UMA_SUPER_ALIGN - 1;
  2807. args.flags = UMA_ZFLAG_INTERNAL;
  2808. zone_ctor(zones, zsize, &args, M_WAITOK);
  2809. /* Now make zones for slab headers */
  2810. slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
  2811. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
  2812. slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
  2813. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
  2814. hashzone = uma_zcreate("UMA Hash",
  2815. sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
  2816. NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
  2817. bucket_init();
  2818. smr_init();
  2819. }
  2820. #ifndef UMA_USE_DMAP
  2821. extern void vm_radix_reserve_kva(void);
  2822. #endif
  2823. /*
  2824. * Advertise the availability of normal kva allocations and switch to
  2825. * the default back-end allocator. Marks the KVA we consumed on startup
  2826. * as used in the map.
  2827. */
  2828. void
  2829. uma_startup2(void)
  2830. {
  2831. if (bootstart != bootmem) {
  2832. vm_map_lock(kernel_map);
  2833. (void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
  2834. VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
  2835. vm_map_unlock(kernel_map);
  2836. }
  2837. #ifndef UMA_USE_DMAP
  2838. /* Set up radix zone to use noobj_alloc. */
  2839. vm_radix_reserve_kva();
  2840. #endif
  2841. booted = BOOT_KVA;
  2842. zone_foreach_unlocked(zone_kva_available, NULL);
  2843. bucket_enable();
  2844. }
  2845. /*
  2846. * Allocate counters as early as possible so that boot-time allocations are
  2847. * accounted more precisely.
  2848. */
  2849. static void
  2850. uma_startup_pcpu(void *arg __unused)
  2851. {
  2852. zone_foreach_unlocked(zone_alloc_counters, NULL);
  2853. booted = BOOT_PCPU;
  2854. }
  2855. SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
  2856. /*
  2857. * Finish our initialization steps.
  2858. */
  2859. static void
  2860. uma_startup3(void *arg __unused)
  2861. {
  2862. #ifdef INVARIANTS
  2863. TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
  2864. uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
  2865. uma_skip_cnt = counter_u64_alloc(M_WAITOK);
  2866. #endif
  2867. zone_foreach_unlocked(zone_alloc_sysctl, NULL);
  2868. booted = BOOT_RUNNING;
  2869. EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
  2870. EVENTHANDLER_PRI_FIRST);
  2871. }
  2872. SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
  2873. static void
  2874. uma_startup4(void *arg __unused)
  2875. {
  2876. TIMEOUT_TASK_INIT(taskqueue_thread, &uma_timeout_task, 0, uma_timeout,
  2877. NULL);
  2878. taskqueue_enqueue_timeout(taskqueue_thread, &uma_timeout_task,
  2879. UMA_TIMEOUT * hz);
  2880. }
  2881. SYSINIT(uma_startup4, SI_SUB_TASKQ, SI_ORDER_ANY, uma_startup4, NULL);
  2882. static void
  2883. uma_shutdown(void)
  2884. {
  2885. booted = BOOT_SHUTDOWN;
  2886. }
  2887. static uma_keg_t
  2888. uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
  2889. int align, uint32_t flags)
  2890. {
  2891. struct uma_kctor_args args;
  2892. args.size = size;
  2893. args.uminit = uminit;
  2894. args.fini = fini;
  2895. args.align = align;
  2896. args.flags = flags;
  2897. args.zone = zone;
  2898. return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
  2899. }
  2900. static void
  2901. check_align_mask(unsigned int mask)
  2902. {
  2903. KASSERT(powerof2(mask + 1),
  2904. ("UMA: %s: Not the mask of a power of 2 (%#x)", __func__, mask));
  2905. /*
  2906. * Make sure the stored align mask doesn't have its highest bit set,
  2907. * which would cause implementation-defined behavior when passing it as
  2908. * the 'align' argument of uma_zcreate(). Such very large alignments do
  2909. * not make sense anyway.
  2910. */
  2911. KASSERT(mask <= INT_MAX,
  2912. ("UMA: %s: Mask too big (%#x)", __func__, mask));
  2913. }
  2914. /* Public functions */
  2915. /* See uma.h */
  2916. void
  2917. uma_set_cache_align_mask(unsigned int mask)
  2918. {
  2919. check_align_mask(mask);
  2920. uma_cache_align_mask = mask;
  2921. }
  2922. /* Returns the alignment mask to use to request cache alignment. */
  2923. unsigned int
  2924. uma_get_cache_align_mask(void)
  2925. {
  2926. return (uma_cache_align_mask);
  2927. }
  2928. /* See uma.h */
  2929. uma_zone_t
  2930. uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
  2931. uma_init uminit, uma_fini fini, int align, uint32_t flags)
  2932. {
  2933. struct uma_zctor_args args;
  2934. uma_zone_t res;
  2935. check_align_mask(align);
  2936. /* This stuff is essential for the zone ctor */
  2937. memset(&args, 0, sizeof(args));
  2938. args.name = name;
  2939. args.size = size;
  2940. args.ctor = ctor;
  2941. args.dtor = dtor;
  2942. args.uminit = uminit;
  2943. args.fini = fini;
  2944. #if defined(INVARIANTS) && !defined(KASAN) && !defined(KMSAN)
  2945. /*
  2946. * Inject procedures which check for memory use after free if we are
  2947. * allowed to scramble the memory while it is not allocated. This
  2948. * requires that: UMA is actually able to access the memory, no init
  2949. * or fini procedures, no dependency on the initial value of the
  2950. * memory, and no (legitimate) use of the memory after free. Note,
  2951. * the ctor and dtor do not need to be empty.
  2952. */
  2953. if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
  2954. UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
  2955. args.uminit = trash_init;
  2956. args.fini = trash_fini;
  2957. }
  2958. #endif
  2959. args.align = align;
  2960. args.flags = flags;
  2961. args.keg = NULL;
  2962. sx_xlock(&uma_reclaim_lock);
  2963. res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
  2964. sx_xunlock(&uma_reclaim_lock);
  2965. return (res);
  2966. }
  2967. /* See uma.h */
  2968. uma_zone_t
  2969. uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
  2970. uma_init zinit, uma_fini zfini, uma_zone_t primary)
  2971. {
  2972. struct uma_zctor_args args;
  2973. uma_keg_t keg;
  2974. uma_zone_t res;
  2975. keg = primary->uz_keg;
  2976. memset(&args, 0, sizeof(args));
  2977. args.name = name;
  2978. args.size = keg->uk_size;
  2979. args.ctor = ctor;
  2980. args.dtor = dtor;
  2981. args.uminit = zinit;
  2982. args.fini = zfini;
  2983. args.align = keg->uk_align;
  2984. args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
  2985. args.keg = keg;
  2986. sx_xlock(&uma_reclaim_lock);
  2987. res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
  2988. sx_xunlock(&uma_reclaim_lock);
  2989. return (res);
  2990. }
  2991. /* See uma.h */
  2992. uma_zone_t
  2993. uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
  2994. uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
  2995. void *arg, int flags)
  2996. {
  2997. struct uma_zctor_args args;
  2998. memset(&args, 0, sizeof(args));
  2999. args.name = name;
  3000. args.size = size;
  3001. args.ctor = ctor;
  3002. args.dtor = dtor;
  3003. args.uminit = zinit;
  3004. args.fini = zfini;
  3005. args.import = zimport;
  3006. args.release = zrelease;
  3007. args.arg = arg;
  3008. args.align = 0;
  3009. args.flags = flags | UMA_ZFLAG_CACHE;
  3010. return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
  3011. }
  3012. /* See uma.h */
  3013. void
  3014. uma_zdestroy(uma_zone_t zone)
  3015. {
  3016. /*
  3017. * Large slabs are expensive to reclaim, so don't bother doing
  3018. * unnecessary work if we're shutting down.
  3019. */
  3020. if (booted == BOOT_SHUTDOWN &&
  3021. zone->uz_fini == NULL && zone->uz_release == zone_release)
  3022. return;
  3023. sx_xlock(&uma_reclaim_lock);
  3024. zone_free_item(zones, zone, NULL, SKIP_NONE);
  3025. sx_xunlock(&uma_reclaim_lock);
  3026. }
  3027. void
  3028. uma_zwait(uma_zone_t zone)
  3029. {
  3030. if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
  3031. uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
  3032. else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
  3033. uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
  3034. else
  3035. uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
  3036. }
  3037. void *
  3038. uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
  3039. {
  3040. void *item, *pcpu_item;
  3041. #ifdef SMP
  3042. int i;
  3043. MPASS(zone->uz_flags & UMA_ZONE_PCPU);
  3044. #endif
  3045. item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
  3046. if (item == NULL)
  3047. return (NULL);
  3048. pcpu_item = zpcpu_base_to_offset(item);
  3049. if (flags & M_ZERO) {
  3050. #ifdef SMP
  3051. for (i = 0; i <= mp_maxid; i++)
  3052. bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
  3053. #else
  3054. bzero(item, zone->uz_size);
  3055. #endif
  3056. }
  3057. return (pcpu_item);
  3058. }
  3059. /*
  3060. * A stub while both regular and pcpu cases are identical.
  3061. */
  3062. void
  3063. uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
  3064. {
  3065. void *item;
  3066. #ifdef SMP
  3067. MPASS(zone->uz_flags & UMA_ZONE_PCPU);
  3068. #endif
  3069. /* uma_zfree_pcu_*(..., NULL) does nothing, to match free(9). */
  3070. if (pcpu_item == NULL)
  3071. return;
  3072. item = zpcpu_offset_to_base(pcpu_item);
  3073. uma_zfree_arg(zone, item, udata);
  3074. }
  3075. static inline void *
  3076. item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
  3077. void *item)
  3078. {
  3079. #ifdef INVARIANTS
  3080. bool skipdbg;
  3081. #endif
  3082. kasan_mark_item_valid(zone, item);
  3083. kmsan_mark_item_uninitialized(zone, item);
  3084. #ifdef INVARIANTS
  3085. skipdbg = uma_dbg_zskip(zone, item);
  3086. if (!skipdbg && (uz_flags & UMA_ZFLAG_TRASH) != 0 &&
  3087. zone->uz_ctor != trash_ctor)
  3088. trash_ctor(item, size, zone, flags);
  3089. #endif
  3090. /* Check flags before loading ctor pointer. */
  3091. if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
  3092. __predict_false(zone->uz_ctor != NULL) &&
  3093. zone->uz_ctor(item, size, udata, flags) != 0) {
  3094. counter_u64_add(zone->uz_fails, 1);
  3095. zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
  3096. return (NULL);
  3097. }
  3098. #ifdef INVARIANTS
  3099. if (!skipdbg)
  3100. uma_dbg_alloc(zone, NULL, item);
  3101. #endif
  3102. if (__predict_false(flags & M_ZERO))
  3103. return (memset(item, 0, size));
  3104. return (item);
  3105. }
  3106. static inline void
  3107. item_dtor(uma_zone_t zone, void *item, int size, void *udata,
  3108. enum zfreeskip skip)
  3109. {
  3110. #ifdef INVARIANTS
  3111. bool skipdbg;
  3112. skipdbg = uma_dbg_zskip(zone, item);
  3113. if (skip == SKIP_NONE && !skipdbg) {
  3114. if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
  3115. uma_dbg_free(zone, udata, item);
  3116. else
  3117. uma_dbg_free(zone, NULL, item);
  3118. }
  3119. #endif
  3120. if (__predict_true(skip < SKIP_DTOR)) {
  3121. if (zone->uz_dtor != NULL)
  3122. zone->uz_dtor(item, size, udata);
  3123. #ifdef INVARIANTS
  3124. if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
  3125. zone->uz_dtor != trash_dtor)
  3126. trash_dtor(item, size, zone);
  3127. #endif
  3128. }
  3129. kasan_mark_item_invalid(zone, item);
  3130. }
  3131. #ifdef NUMA
  3132. static int
  3133. item_domain(void *item)
  3134. {
  3135. int domain;
  3136. domain = vm_phys_domain(vtophys(item));
  3137. KASSERT(domain >= 0 && domain < vm_ndomains,
  3138. ("%s: unknown domain for item %p", __func__, item));
  3139. return (domain);
  3140. }
  3141. #endif
  3142. #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
  3143. #if defined(INVARIANTS) && (defined(DDB) || defined(STACK))
  3144. #include <sys/stack.h>
  3145. #endif
  3146. #define UMA_ZALLOC_DEBUG
  3147. static int
  3148. uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
  3149. {
  3150. int error;
  3151. error = 0;
  3152. #ifdef WITNESS
  3153. if (flags & M_WAITOK) {
  3154. WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
  3155. "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
  3156. }
  3157. #endif
  3158. #ifdef INVARIANTS
  3159. KASSERT((flags & M_EXEC) == 0,
  3160. ("uma_zalloc_debug: called with M_EXEC"));
  3161. KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
  3162. ("uma_zalloc_debug: called within spinlock or critical section"));
  3163. KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
  3164. ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
  3165. _Static_assert(M_NOWAIT != 0 && M_WAITOK != 0,
  3166. "M_NOWAIT and M_WAITOK must be non-zero for this assertion:");
  3167. #if 0
  3168. /*
  3169. * Give the #elif clause time to find problems, then remove it
  3170. * and enable this. (Remove <sys/stack.h> above, too.)
  3171. */
  3172. KASSERT((flags & (M_NOWAIT|M_WAITOK)) == M_NOWAIT ||
  3173. (flags & (M_NOWAIT|M_WAITOK)) == M_WAITOK,
  3174. ("uma_zalloc_debug: must pass one of M_NOWAIT or M_WAITOK"));
  3175. #elif defined(DDB) || defined(STACK)
  3176. if (__predict_false((flags & (M_NOWAIT|M_WAITOK)) != M_NOWAIT &&
  3177. (flags & (M_NOWAIT|M_WAITOK)) != M_WAITOK)) {
  3178. static int stack_count;
  3179. struct stack st;
  3180. if (stack_count < 10) {
  3181. ++stack_count;
  3182. printf("uma_zalloc* called with bad WAIT flags:\n");
  3183. stack_save(&st);
  3184. stack_print(&st);
  3185. }
  3186. }
  3187. #endif
  3188. #endif
  3189. #ifdef DEBUG_MEMGUARD
  3190. if ((zone->uz_flags & (UMA_ZONE_SMR | UMA_ZFLAG_CACHE)) == 0 &&
  3191. memguard_cmp_zone(zone)) {
  3192. void *item;
  3193. item = memguard_alloc(zone->uz_size, flags);
  3194. if (item != NULL) {
  3195. error = EJUSTRETURN;
  3196. if (zone->uz_init != NULL &&
  3197. zone->uz_init(item, zone->uz_size, flags) != 0) {
  3198. *itemp = NULL;
  3199. return (error);
  3200. }
  3201. if (zone->uz_ctor != NULL &&
  3202. zone->uz_ctor(item, zone->uz_size, udata,
  3203. flags) != 0) {
  3204. counter_u64_add(zone->uz_fails, 1);
  3205. if (zone->uz_fini != NULL)
  3206. zone->uz_fini(item, zone->uz_size);
  3207. *itemp = NULL;
  3208. return (error);
  3209. }
  3210. *itemp = item;
  3211. return (error);
  3212. }
  3213. /* This is unfortunate but should not be fatal. */
  3214. }
  3215. #endif
  3216. return (error);
  3217. }
  3218. static int
  3219. uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
  3220. {
  3221. KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
  3222. ("uma_zfree_debug: called with spinlock or critical section held"));
  3223. #ifdef DEBUG_MEMGUARD
  3224. if ((zone->uz_flags & (UMA_ZONE_SMR | UMA_ZFLAG_CACHE)) == 0 &&
  3225. is_memguard_addr(item)) {
  3226. if (zone->uz_dtor != NULL)
  3227. zone->uz_dtor(item, zone->uz_size, udata);
  3228. if (zone->uz_fini != NULL)
  3229. zone->uz_fini(item, zone->uz_size);
  3230. memguard_free(item);
  3231. return (EJUSTRETURN);
  3232. }
  3233. #endif
  3234. return (0);
  3235. }
  3236. #endif
  3237. static inline void *
  3238. cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
  3239. void *udata, int flags)
  3240. {
  3241. void *item;
  3242. int size, uz_flags;
  3243. item = cache_bucket_pop(cache, bucket);
  3244. size = cache_uz_size(cache);
  3245. uz_flags = cache_uz_flags(cache);
  3246. critical_exit();
  3247. return (item_ctor(zone, uz_flags, size, udata, flags, item));
  3248. }
  3249. static __noinline void *
  3250. cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
  3251. {
  3252. uma_cache_bucket_t bucket;
  3253. int domain;
  3254. while (cache_alloc(zone, cache, udata, flags)) {
  3255. cache = &zone->uz_cpu[curcpu];
  3256. bucket = &cache->uc_allocbucket;
  3257. if (__predict_false(bucket->ucb_cnt == 0))
  3258. continue;
  3259. return (cache_alloc_item(zone, cache, bucket, udata, flags));
  3260. }
  3261. critical_exit();
  3262. /*
  3263. * We can not get a bucket so try to return a single item.
  3264. */
  3265. if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
  3266. domain = PCPU_GET(domain);
  3267. else
  3268. domain = UMA_ANYDOMAIN;
  3269. return (zone_alloc_item(zone, udata, domain, flags));
  3270. }
  3271. /* See uma.h */
  3272. void *
  3273. uma_zalloc_smr(uma_zone_t zone, int flags)
  3274. {
  3275. uma_cache_bucket_t bucket;
  3276. uma_cache_t cache;
  3277. CTR3(KTR_UMA, "uma_zalloc_smr zone %s(%p) flags %d", zone->uz_name,
  3278. zone, flags);
  3279. #ifdef UMA_ZALLOC_DEBUG
  3280. void *item;
  3281. KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
  3282. ("uma_zalloc_arg: called with non-SMR zone."));
  3283. if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
  3284. return (item);
  3285. #endif
  3286. critical_enter();
  3287. cache = &zone->uz_cpu[curcpu];
  3288. bucket = &cache->uc_allocbucket;
  3289. if (__predict_false(bucket->ucb_cnt == 0))
  3290. return (cache_alloc_retry(zone, cache, NULL, flags));
  3291. return (cache_alloc_item(zone, cache, bucket, NULL, flags));
  3292. }
  3293. /* See uma.h */
  3294. void *
  3295. uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
  3296. {
  3297. uma_cache_bucket_t bucket;
  3298. uma_cache_t cache;
  3299. /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
  3300. random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
  3301. /* This is the fast path allocation */
  3302. CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
  3303. zone, flags);
  3304. #ifdef UMA_ZALLOC_DEBUG
  3305. void *item;
  3306. KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
  3307. ("uma_zalloc_arg: called with SMR zone."));
  3308. if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
  3309. return (item);
  3310. #endif
  3311. /*
  3312. * If possible, allocate from the per-CPU cache. There are two
  3313. * requirements for safe access to the per-CPU cache: (1) the thread
  3314. * accessing the cache must not be preempted or yield during access,
  3315. * and (2) the thread must not migrate CPUs without switching which
  3316. * cache it accesses. We rely on a critical section to prevent
  3317. * preemption and migration. We release the critical section in
  3318. * order to acquire the zone mutex if we are unable to allocate from
  3319. * the current cache; when we re-acquire the critical section, we
  3320. * must detect and handle migration if it has occurred.
  3321. */
  3322. critical_enter();
  3323. cache = &zone->uz_cpu[curcpu];
  3324. bucket = &cache->uc_allocbucket;
  3325. if (__predict_false(bucket->ucb_cnt == 0))
  3326. return (cache_alloc_retry(zone, cache, udata, flags));
  3327. return (cache_alloc_item(zone, cache, bucket, udata, flags));
  3328. }
  3329. /*
  3330. * Replenish an alloc bucket and possibly restore an old one. Called in
  3331. * a critical section. Returns in a critical section.
  3332. *
  3333. * A false return value indicates an allocation failure.
  3334. * A true return value indicates success and the caller should retry.
  3335. */
  3336. static __noinline bool
  3337. cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
  3338. {
  3339. uma_bucket_t bucket;
  3340. int curdomain, domain;
  3341. bool new;
  3342. CRITICAL_ASSERT(curthread);
  3343. /*
  3344. * If we have run out of items in our alloc bucket see
  3345. * if we can switch with the free bucket.
  3346. *
  3347. * SMR Zones can't re-use the free bucket until the sequence has
  3348. * expired.
  3349. */
  3350. if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
  3351. cache->uc_freebucket.ucb_cnt != 0) {
  3352. cache_bucket_swap(&cache->uc_freebucket,
  3353. &cache->uc_allocbucket);
  3354. return (true);
  3355. }
  3356. /*
  3357. * Discard any empty allocation bucket while we hold no locks.
  3358. */
  3359. bucket = cache_bucket_unload_alloc(cache);
  3360. critical_exit();
  3361. if (bucket != NULL) {
  3362. KASSERT(bucket->ub_cnt == 0,
  3363. ("cache_alloc: Entered with non-empty alloc bucket."));
  3364. bucket_free(zone, bucket, udata);
  3365. }
  3366. /*
  3367. * Attempt to retrieve the item from the per-CPU cache has failed, so
  3368. * we must go back to the zone. This requires the zdom lock, so we
  3369. * must drop the critical section, then re-acquire it when we go back
  3370. * to the cache. Since the critical section is released, we may be
  3371. * preempted or migrate. As such, make sure not to maintain any
  3372. * thread-local state specific to the cache from prior to releasing
  3373. * the critical section.
  3374. */
  3375. domain = PCPU_GET(domain);
  3376. if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
  3377. VM_DOMAIN_EMPTY(domain))
  3378. domain = zone_domain_highest(zone, domain);
  3379. bucket = cache_fetch_bucket(zone, cache, domain);
  3380. if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
  3381. bucket = zone_alloc_bucket(zone, udata, domain, flags);
  3382. new = true;
  3383. } else {
  3384. new = false;
  3385. }
  3386. CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
  3387. zone->uz_name, zone, bucket);
  3388. if (bucket == NULL) {
  3389. critical_enter();
  3390. return (false);
  3391. }
  3392. /*
  3393. * See if we lost the race or were migrated. Cache the
  3394. * initialized bucket to make this less likely or claim
  3395. * the memory directly.
  3396. */
  3397. critical_enter();
  3398. cache = &zone->uz_cpu[curcpu];
  3399. if (cache->uc_allocbucket.ucb_bucket == NULL &&
  3400. ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
  3401. (curdomain = PCPU_GET(domain)) == domain ||
  3402. VM_DOMAIN_EMPTY(curdomain))) {
  3403. if (new)
  3404. atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
  3405. bucket->ub_cnt);
  3406. cache_bucket_load_alloc(cache, bucket);
  3407. return (true);
  3408. }
  3409. /*
  3410. * We lost the race, release this bucket and start over.
  3411. */
  3412. critical_exit();
  3413. zone_put_bucket(zone, domain, bucket, udata, !new);
  3414. critical_enter();
  3415. return (true);
  3416. }
  3417. void *
  3418. uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
  3419. {
  3420. #ifdef NUMA
  3421. uma_bucket_t bucket;
  3422. uma_zone_domain_t zdom;
  3423. void *item;
  3424. #endif
  3425. /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
  3426. random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
  3427. /* This is the fast path allocation */
  3428. CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
  3429. zone->uz_name, zone, domain, flags);
  3430. KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
  3431. ("uma_zalloc_domain: called with SMR zone."));
  3432. #ifdef NUMA
  3433. KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
  3434. ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
  3435. if (vm_ndomains == 1)
  3436. return (uma_zalloc_arg(zone, udata, flags));
  3437. #ifdef UMA_ZALLOC_DEBUG
  3438. if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
  3439. return (item);
  3440. #endif
  3441. /*
  3442. * Try to allocate from the bucket cache before falling back to the keg.
  3443. * We could try harder and attempt to allocate from per-CPU caches or
  3444. * the per-domain cross-domain buckets, but the complexity is probably
  3445. * not worth it. It is more important that frees of previous
  3446. * cross-domain allocations do not blow up the cache.
  3447. */
  3448. zdom = zone_domain_lock(zone, domain);
  3449. if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
  3450. item = bucket->ub_bucket[bucket->ub_cnt - 1];
  3451. #ifdef INVARIANTS
  3452. bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
  3453. #endif
  3454. bucket->ub_cnt--;
  3455. zone_put_bucket(zone, domain, bucket, udata, true);
  3456. item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
  3457. flags, item);
  3458. if (item != NULL) {
  3459. KASSERT(item_domain(item) == domain,
  3460. ("%s: bucket cache item %p from wrong domain",
  3461. __func__, item));
  3462. counter_u64_add(zone->uz_allocs, 1);
  3463. }
  3464. return (item);
  3465. }
  3466. ZDOM_UNLOCK(zdom);
  3467. return (zone_alloc_item(zone, udata, domain, flags));
  3468. #else
  3469. return (uma_zalloc_arg(zone, udata, flags));
  3470. #endif
  3471. }
  3472. /*
  3473. * Find a slab with some space. Prefer slabs that are partially used over those
  3474. * that are totally full. This helps to reduce fragmentation.
  3475. *
  3476. * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
  3477. * only 'domain'.
  3478. */
  3479. static uma_slab_t
  3480. keg_first_slab(uma_keg_t keg, int domain, bool rr)
  3481. {
  3482. uma_domain_t dom;
  3483. uma_slab_t slab;
  3484. int start;
  3485. KASSERT(domain >= 0 && domain < vm_ndomains,
  3486. ("keg_first_slab: domain %d out of range", domain));
  3487. KEG_LOCK_ASSERT(keg, domain);
  3488. slab = NULL;
  3489. start = domain;
  3490. do {
  3491. dom = &keg->uk_domain[domain];
  3492. if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
  3493. return (slab);
  3494. if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
  3495. LIST_REMOVE(slab, us_link);
  3496. dom->ud_free_slabs--;
  3497. LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
  3498. return (slab);
  3499. }
  3500. if (rr)
  3501. domain = (domain + 1) % vm_ndomains;
  3502. } while (domain != start);
  3503. return (NULL);
  3504. }
  3505. /*
  3506. * Fetch an existing slab from a free or partial list. Returns with the
  3507. * keg domain lock held if a slab was found or unlocked if not.
  3508. */
  3509. static uma_slab_t
  3510. keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
  3511. {
  3512. uma_slab_t slab;
  3513. uint32_t reserve;
  3514. /* HASH has a single free list. */
  3515. if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
  3516. domain = 0;
  3517. KEG_LOCK(keg, domain);
  3518. reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
  3519. if (keg->uk_domain[domain].ud_free_items <= reserve ||
  3520. (slab = keg_first_slab(keg, domain, rr)) == NULL) {
  3521. KEG_UNLOCK(keg, domain);
  3522. return (NULL);
  3523. }
  3524. return (slab);
  3525. }
  3526. static uma_slab_t
  3527. keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
  3528. {
  3529. struct vm_domainset_iter di;
  3530. uma_slab_t slab;
  3531. int aflags, domain;
  3532. bool rr;
  3533. KASSERT((flags & (M_WAITOK | M_NOVM)) != (M_WAITOK | M_NOVM),
  3534. ("%s: invalid flags %#x", __func__, flags));
  3535. restart:
  3536. /*
  3537. * Use the keg's policy if upper layers haven't already specified a
  3538. * domain (as happens with first-touch zones).
  3539. *
  3540. * To avoid races we run the iterator with the keg lock held, but that
  3541. * means that we cannot allow the vm_domainset layer to sleep. Thus,
  3542. * clear M_WAITOK and handle low memory conditions locally.
  3543. */
  3544. rr = rdomain == UMA_ANYDOMAIN;
  3545. if (rr) {
  3546. aflags = (flags & ~M_WAITOK) | M_NOWAIT;
  3547. vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
  3548. &aflags);
  3549. } else {
  3550. aflags = flags;
  3551. domain = rdomain;
  3552. }
  3553. for (;;) {
  3554. slab = keg_fetch_free_slab(keg, domain, rr, flags);
  3555. if (slab != NULL)
  3556. return (slab);
  3557. /*
  3558. * M_NOVM is used to break the recursion that can otherwise
  3559. * occur if low-level memory management routines use UMA.
  3560. */
  3561. if ((flags & M_NOVM) == 0) {
  3562. slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
  3563. if (slab != NULL)
  3564. return (slab);
  3565. }
  3566. if (!rr) {
  3567. if ((flags & M_USE_RESERVE) != 0) {
  3568. /*
  3569. * Drain reserves from other domains before
  3570. * giving up or sleeping. It may be useful to
  3571. * support per-domain reserves eventually.
  3572. */
  3573. rdomain = UMA_ANYDOMAIN;
  3574. goto restart;
  3575. }
  3576. if ((flags & M_WAITOK) == 0)
  3577. break;
  3578. vm_wait_domain(domain);
  3579. } else if (vm_domainset_iter_policy(&di, &domain) != 0) {
  3580. if ((flags & M_WAITOK) != 0) {
  3581. vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
  3582. goto restart;
  3583. }
  3584. break;
  3585. }
  3586. }
  3587. /*
  3588. * We might not have been able to get a slab but another cpu
  3589. * could have while we were unlocked. Check again before we
  3590. * fail.
  3591. */
  3592. if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
  3593. return (slab);
  3594. return (NULL);
  3595. }
  3596. static void *
  3597. slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
  3598. {
  3599. uma_domain_t dom;
  3600. void *item;
  3601. int freei;
  3602. KEG_LOCK_ASSERT(keg, slab->us_domain);
  3603. dom = &keg->uk_domain[slab->us_domain];
  3604. freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
  3605. BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
  3606. item = slab_item(slab, keg, freei);
  3607. slab->us_freecount--;
  3608. dom->ud_free_items--;
  3609. /*
  3610. * Move this slab to the full list. It must be on the partial list, so
  3611. * we do not need to update the free slab count. In particular,
  3612. * keg_fetch_slab() always returns slabs on the partial list.
  3613. */
  3614. if (slab->us_freecount == 0) {
  3615. LIST_REMOVE(slab, us_link);
  3616. LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
  3617. }
  3618. return (item);
  3619. }
  3620. static int
  3621. zone_import(void *arg, void **bucket, int max, int domain, int flags)
  3622. {
  3623. uma_domain_t dom;
  3624. uma_zone_t zone;
  3625. uma_slab_t slab;
  3626. uma_keg_t keg;
  3627. #ifdef NUMA
  3628. int stripe;
  3629. #endif
  3630. int i;
  3631. zone = arg;
  3632. slab = NULL;
  3633. keg = zone->uz_keg;
  3634. /* Try to keep the buckets totally full */
  3635. for (i = 0; i < max; ) {
  3636. if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
  3637. break;
  3638. #ifdef NUMA
  3639. stripe = howmany(max, vm_ndomains);
  3640. #endif
  3641. dom = &keg->uk_domain[slab->us_domain];
  3642. do {
  3643. bucket[i++] = slab_alloc_item(keg, slab);
  3644. if (keg->uk_reserve > 0 &&
  3645. dom->ud_free_items <= keg->uk_reserve) {
  3646. /*
  3647. * Avoid depleting the reserve after a
  3648. * successful item allocation, even if
  3649. * M_USE_RESERVE is specified.
  3650. */
  3651. KEG_UNLOCK(keg, slab->us_domain);
  3652. goto out;
  3653. }
  3654. #ifdef NUMA
  3655. /*
  3656. * If the zone is striped we pick a new slab for every
  3657. * N allocations. Eliminating this conditional will
  3658. * instead pick a new domain for each bucket rather
  3659. * than stripe within each bucket. The current option
  3660. * produces more fragmentation and requires more cpu
  3661. * time but yields better distribution.
  3662. */
  3663. if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
  3664. vm_ndomains > 1 && --stripe == 0)
  3665. break;
  3666. #endif
  3667. } while (slab->us_freecount != 0 && i < max);
  3668. KEG_UNLOCK(keg, slab->us_domain);
  3669. /* Don't block if we allocated any successfully. */
  3670. flags &= ~M_WAITOK;
  3671. flags |= M_NOWAIT;
  3672. }
  3673. out:
  3674. return i;
  3675. }
  3676. static int
  3677. zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
  3678. {
  3679. uint64_t old, new, total, max;
  3680. /*
  3681. * The hard case. We're going to sleep because there were existing
  3682. * sleepers or because we ran out of items. This routine enforces
  3683. * fairness by keeping fifo order.
  3684. *
  3685. * First release our ill gotten gains and make some noise.
  3686. */
  3687. for (;;) {
  3688. zone_free_limit(zone, count);
  3689. zone_log_warning(zone);
  3690. zone_maxaction(zone);
  3691. if (flags & M_NOWAIT)
  3692. return (0);
  3693. /*
  3694. * We need to allocate an item or set ourself as a sleeper
  3695. * while the sleepq lock is held to avoid wakeup races. This
  3696. * is essentially a home rolled semaphore.
  3697. */
  3698. sleepq_lock(&zone->uz_max_items);
  3699. old = zone->uz_items;
  3700. do {
  3701. MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
  3702. /* Cache the max since we will evaluate twice. */
  3703. max = zone->uz_max_items;
  3704. if (UZ_ITEMS_SLEEPERS(old) != 0 ||
  3705. UZ_ITEMS_COUNT(old) >= max)
  3706. new = old + UZ_ITEMS_SLEEPER;
  3707. else
  3708. new = old + MIN(count, max - old);
  3709. } while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
  3710. /* We may have successfully allocated under the sleepq lock. */
  3711. if (UZ_ITEMS_SLEEPERS(new) == 0) {
  3712. sleepq_release(&zone->uz_max_items);
  3713. return (new - old);
  3714. }
  3715. /*
  3716. * This is in a different cacheline from uz_items so that we
  3717. * don't constantly invalidate the fastpath cacheline when we
  3718. * adjust item counts. This could be limited to toggling on
  3719. * transitions.
  3720. */
  3721. atomic_add_32(&zone->uz_sleepers, 1);
  3722. atomic_add_64(&zone->uz_sleeps, 1);
  3723. /*
  3724. * We have added ourselves as a sleeper. The sleepq lock
  3725. * protects us from wakeup races. Sleep now and then retry.
  3726. */
  3727. sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
  3728. sleepq_wait(&zone->uz_max_items, PVM);
  3729. /*
  3730. * After wakeup, remove ourselves as a sleeper and try
  3731. * again. We no longer have the sleepq lock for protection.
  3732. *
  3733. * Subract ourselves as a sleeper while attempting to add
  3734. * our count.
  3735. */
  3736. atomic_subtract_32(&zone->uz_sleepers, 1);
  3737. old = atomic_fetchadd_64(&zone->uz_items,
  3738. -(UZ_ITEMS_SLEEPER - count));
  3739. /* We're no longer a sleeper. */
  3740. old -= UZ_ITEMS_SLEEPER;
  3741. /*
  3742. * If we're still at the limit, restart. Notably do not
  3743. * block on other sleepers. Cache the max value to protect
  3744. * against changes via sysctl.
  3745. */
  3746. total = UZ_ITEMS_COUNT(old);
  3747. max = zone->uz_max_items;
  3748. if (total >= max)
  3749. continue;
  3750. /* Truncate if necessary, otherwise wake other sleepers. */
  3751. if (total + count > max) {
  3752. zone_free_limit(zone, total + count - max);
  3753. count = max - total;
  3754. } else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
  3755. wakeup_one(&zone->uz_max_items);
  3756. return (count);
  3757. }
  3758. }
  3759. /*
  3760. * Allocate 'count' items from our max_items limit. Returns the number
  3761. * available. If M_NOWAIT is not specified it will sleep until at least
  3762. * one item can be allocated.
  3763. */
  3764. static int
  3765. zone_alloc_limit(uma_zone_t zone, int count, int flags)
  3766. {
  3767. uint64_t old;
  3768. uint64_t max;
  3769. max = zone->uz_max_items;
  3770. MPASS(max > 0);
  3771. /*
  3772. * We expect normal allocations to succeed with a simple
  3773. * fetchadd.
  3774. */
  3775. old = atomic_fetchadd_64(&zone->uz_items, count);
  3776. if (__predict_true(old + count <= max))
  3777. return (count);
  3778. /*
  3779. * If we had some items and no sleepers just return the
  3780. * truncated value. We have to release the excess space
  3781. * though because that may wake sleepers who weren't woken
  3782. * because we were temporarily over the limit.
  3783. */
  3784. if (old < max) {
  3785. zone_free_limit(zone, (old + count) - max);
  3786. return (max - old);
  3787. }
  3788. return (zone_alloc_limit_hard(zone, count, flags));
  3789. }
  3790. /*
  3791. * Free a number of items back to the limit.
  3792. */
  3793. static void
  3794. zone_free_limit(uma_zone_t zone, int count)
  3795. {
  3796. uint64_t old;
  3797. MPASS(count > 0);
  3798. /*
  3799. * In the common case we either have no sleepers or
  3800. * are still over the limit and can just return.
  3801. */
  3802. old = atomic_fetchadd_64(&zone->uz_items, -count);
  3803. if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
  3804. UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
  3805. return;
  3806. /*
  3807. * Moderate the rate of wakeups. Sleepers will continue
  3808. * to generate wakeups if necessary.
  3809. */
  3810. wakeup_one(&zone->uz_max_items);
  3811. }
  3812. static uma_bucket_t
  3813. zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
  3814. {
  3815. uma_bucket_t bucket;
  3816. int error, maxbucket, cnt;
  3817. CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
  3818. zone, domain);
  3819. /* Avoid allocs targeting empty domains. */
  3820. if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
  3821. domain = UMA_ANYDOMAIN;
  3822. else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
  3823. domain = UMA_ANYDOMAIN;
  3824. if (zone->uz_max_items > 0)
  3825. maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
  3826. M_NOWAIT);
  3827. else
  3828. maxbucket = zone->uz_bucket_size;
  3829. if (maxbucket == 0)
  3830. return (NULL);
  3831. /* Don't wait for buckets, preserve caller's NOVM setting. */
  3832. bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
  3833. if (bucket == NULL) {
  3834. cnt = 0;
  3835. goto out;
  3836. }
  3837. bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
  3838. MIN(maxbucket, bucket->ub_entries), domain, flags);
  3839. /*
  3840. * Initialize the memory if necessary.
  3841. */
  3842. if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
  3843. int i;
  3844. for (i = 0; i < bucket->ub_cnt; i++) {
  3845. kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
  3846. error = zone->uz_init(bucket->ub_bucket[i],
  3847. zone->uz_size, flags);
  3848. kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
  3849. if (error != 0)
  3850. break;
  3851. }
  3852. /*
  3853. * If we couldn't initialize the whole bucket, put the
  3854. * rest back onto the freelist.
  3855. */
  3856. if (i != bucket->ub_cnt) {
  3857. zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
  3858. bucket->ub_cnt - i);
  3859. #ifdef INVARIANTS
  3860. bzero(&bucket->ub_bucket[i],
  3861. sizeof(void *) * (bucket->ub_cnt - i));
  3862. #endif
  3863. bucket->ub_cnt = i;
  3864. }
  3865. }
  3866. cnt = bucket->ub_cnt;
  3867. if (bucket->ub_cnt == 0) {
  3868. bucket_free(zone, bucket, udata);
  3869. counter_u64_add(zone->uz_fails, 1);
  3870. bucket = NULL;
  3871. }
  3872. out:
  3873. if (zone->uz_max_items > 0 && cnt < maxbucket)
  3874. zone_free_limit(zone, maxbucket - cnt);
  3875. return (bucket);
  3876. }
  3877. /*
  3878. * Allocates a single item from a zone.
  3879. *
  3880. * Arguments
  3881. * zone The zone to alloc for.
  3882. * udata The data to be passed to the constructor.
  3883. * domain The domain to allocate from or UMA_ANYDOMAIN.
  3884. * flags M_WAITOK, M_NOWAIT, M_ZERO.
  3885. *
  3886. * Returns
  3887. * NULL if there is no memory and M_NOWAIT is set
  3888. * An item if successful
  3889. */
  3890. static void *
  3891. zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
  3892. {
  3893. void *item;
  3894. if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
  3895. counter_u64_add(zone->uz_fails, 1);
  3896. return (NULL);
  3897. }
  3898. /* Avoid allocs targeting empty domains. */
  3899. if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
  3900. domain = UMA_ANYDOMAIN;
  3901. if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
  3902. goto fail_cnt;
  3903. /*
  3904. * We have to call both the zone's init (not the keg's init)
  3905. * and the zone's ctor. This is because the item is going from
  3906. * a keg slab directly to the user, and the user is expecting it
  3907. * to be both zone-init'd as well as zone-ctor'd.
  3908. */
  3909. if (zone->uz_init != NULL) {
  3910. int error;
  3911. kasan_mark_item_valid(zone, item);
  3912. error = zone->uz_init(item, zone->uz_size, flags);
  3913. kasan_mark_item_invalid(zone, item);
  3914. if (error != 0) {
  3915. zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
  3916. goto fail_cnt;
  3917. }
  3918. }
  3919. item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
  3920. item);
  3921. if (item == NULL)
  3922. goto fail;
  3923. counter_u64_add(zone->uz_allocs, 1);
  3924. CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
  3925. zone->uz_name, zone);
  3926. return (item);
  3927. fail_cnt:
  3928. counter_u64_add(zone->uz_fails, 1);
  3929. fail:
  3930. if (zone->uz_max_items > 0)
  3931. zone_free_limit(zone, 1);
  3932. CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
  3933. zone->uz_name, zone);
  3934. return (NULL);
  3935. }
  3936. /* See uma.h */
  3937. void
  3938. uma_zfree_smr(uma_zone_t zone, void *item)
  3939. {
  3940. uma_cache_t cache;
  3941. uma_cache_bucket_t bucket;
  3942. int itemdomain;
  3943. #ifdef NUMA
  3944. int uz_flags;
  3945. #endif
  3946. CTR3(KTR_UMA, "uma_zfree_smr zone %s(%p) item %p",
  3947. zone->uz_name, zone, item);
  3948. #ifdef UMA_ZALLOC_DEBUG
  3949. KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
  3950. ("uma_zfree_smr: called with non-SMR zone."));
  3951. KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
  3952. SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
  3953. if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
  3954. return;
  3955. #endif
  3956. cache = &zone->uz_cpu[curcpu];
  3957. itemdomain = 0;
  3958. #ifdef NUMA
  3959. uz_flags = cache_uz_flags(cache);
  3960. if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
  3961. itemdomain = item_domain(item);
  3962. #endif
  3963. critical_enter();
  3964. do {
  3965. cache = &zone->uz_cpu[curcpu];
  3966. /* SMR Zones must free to the free bucket. */
  3967. bucket = &cache->uc_freebucket;
  3968. #ifdef NUMA
  3969. if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
  3970. PCPU_GET(domain) != itemdomain) {
  3971. bucket = &cache->uc_crossbucket;
  3972. }
  3973. #endif
  3974. if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
  3975. cache_bucket_push(cache, bucket, item);
  3976. critical_exit();
  3977. return;
  3978. }
  3979. } while (cache_free(zone, cache, NULL, itemdomain));
  3980. critical_exit();
  3981. /*
  3982. * If nothing else caught this, we'll just do an internal free.
  3983. */
  3984. zone_free_item(zone, item, NULL, SKIP_NONE);
  3985. }
  3986. /* See uma.h */
  3987. void
  3988. uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
  3989. {
  3990. uma_cache_t cache;
  3991. uma_cache_bucket_t bucket;
  3992. int itemdomain, uz_flags;
  3993. /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
  3994. random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
  3995. CTR3(KTR_UMA, "uma_zfree_arg zone %s(%p) item %p",
  3996. zone->uz_name, zone, item);
  3997. #ifdef UMA_ZALLOC_DEBUG
  3998. KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
  3999. ("uma_zfree_arg: called with SMR zone."));
  4000. if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
  4001. return;
  4002. #endif
  4003. /* uma_zfree(..., NULL) does nothing, to match free(9). */
  4004. if (item == NULL)
  4005. return;
  4006. /*
  4007. * We are accessing the per-cpu cache without a critical section to
  4008. * fetch size and flags. This is acceptable, if we are preempted we
  4009. * will simply read another cpu's line.
  4010. */
  4011. cache = &zone->uz_cpu[curcpu];
  4012. uz_flags = cache_uz_flags(cache);
  4013. if (UMA_ALWAYS_CTORDTOR ||
  4014. __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
  4015. item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
  4016. /*
  4017. * The race here is acceptable. If we miss it we'll just have to wait
  4018. * a little longer for the limits to be reset.
  4019. */
  4020. if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
  4021. if (atomic_load_32(&zone->uz_sleepers) > 0)
  4022. goto zfree_item;
  4023. }
  4024. /*
  4025. * If possible, free to the per-CPU cache. There are two
  4026. * requirements for safe access to the per-CPU cache: (1) the thread
  4027. * accessing the cache must not be preempted or yield during access,
  4028. * and (2) the thread must not migrate CPUs without switching which
  4029. * cache it accesses. We rely on a critical section to prevent
  4030. * preemption and migration. We release the critical section in
  4031. * order to acquire the zone mutex if we are unable to free to the
  4032. * current cache; when we re-acquire the critical section, we must
  4033. * detect and handle migration if it has occurred.
  4034. */
  4035. itemdomain = 0;
  4036. #ifdef NUMA
  4037. if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
  4038. itemdomain = item_domain(item);
  4039. #endif
  4040. critical_enter();
  4041. do {
  4042. cache = &zone->uz_cpu[curcpu];
  4043. /*
  4044. * Try to free into the allocbucket first to give LIFO
  4045. * ordering for cache-hot datastructures. Spill over
  4046. * into the freebucket if necessary. Alloc will swap
  4047. * them if one runs dry.
  4048. */
  4049. bucket = &cache->uc_allocbucket;
  4050. #ifdef NUMA
  4051. if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
  4052. PCPU_GET(domain) != itemdomain) {
  4053. bucket = &cache->uc_crossbucket;
  4054. } else
  4055. #endif
  4056. if (bucket->ucb_cnt == bucket->ucb_entries &&
  4057. cache->uc_freebucket.ucb_cnt <
  4058. cache->uc_freebucket.ucb_entries)
  4059. cache_bucket_swap(&cache->uc_freebucket,
  4060. &cache->uc_allocbucket);
  4061. if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
  4062. cache_bucket_push(cache, bucket, item);
  4063. critical_exit();
  4064. return;
  4065. }
  4066. } while (cache_free(zone, cache, udata, itemdomain));
  4067. critical_exit();
  4068. /*
  4069. * If nothing else caught this, we'll just do an internal free.
  4070. */
  4071. zfree_item:
  4072. zone_free_item(zone, item, udata, SKIP_DTOR);
  4073. }
  4074. #ifdef NUMA
  4075. /*
  4076. * sort crossdomain free buckets to domain correct buckets and cache
  4077. * them.
  4078. */
  4079. static void
  4080. zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
  4081. {
  4082. struct uma_bucketlist emptybuckets, fullbuckets;
  4083. uma_zone_domain_t zdom;
  4084. uma_bucket_t b;
  4085. smr_seq_t seq;
  4086. void *item;
  4087. int domain;
  4088. CTR3(KTR_UMA,
  4089. "uma_zfree: zone %s(%p) draining cross bucket %p",
  4090. zone->uz_name, zone, bucket);
  4091. /*
  4092. * It is possible for buckets to arrive here out of order so we fetch
  4093. * the current smr seq rather than accepting the bucket's.
  4094. */
  4095. seq = SMR_SEQ_INVALID;
  4096. if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
  4097. seq = smr_advance(zone->uz_smr);
  4098. /*
  4099. * To avoid having ndomain * ndomain buckets for sorting we have a
  4100. * lock on the current crossfree bucket. A full matrix with
  4101. * per-domain locking could be used if necessary.
  4102. */
  4103. STAILQ_INIT(&emptybuckets);
  4104. STAILQ_INIT(&fullbuckets);
  4105. ZONE_CROSS_LOCK(zone);
  4106. for (; bucket->ub_cnt > 0; bucket->ub_cnt--) {
  4107. item = bucket->ub_bucket[bucket->ub_cnt - 1];
  4108. domain = item_domain(item);
  4109. zdom = ZDOM_GET(zone, domain);
  4110. if (zdom->uzd_cross == NULL) {
  4111. if ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
  4112. STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
  4113. zdom->uzd_cross = b;
  4114. } else {
  4115. /*
  4116. * Avoid allocating a bucket with the cross lock
  4117. * held, since allocation can trigger a
  4118. * cross-domain free and bucket zones may
  4119. * allocate from each other.
  4120. */
  4121. ZONE_CROSS_UNLOCK(zone);
  4122. b = bucket_alloc(zone, udata, M_NOWAIT);
  4123. if (b == NULL)
  4124. goto out;
  4125. ZONE_CROSS_LOCK(zone);
  4126. if (zdom->uzd_cross != NULL) {
  4127. STAILQ_INSERT_HEAD(&emptybuckets, b,
  4128. ub_link);
  4129. } else {
  4130. zdom->uzd_cross = b;
  4131. }
  4132. }
  4133. }
  4134. b = zdom->uzd_cross;
  4135. b->ub_bucket[b->ub_cnt++] = item;
  4136. b->ub_seq = seq;
  4137. if (b->ub_cnt == b->ub_entries) {
  4138. STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
  4139. if ((b = STAILQ_FIRST(&emptybuckets)) != NULL)
  4140. STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
  4141. zdom->uzd_cross = b;
  4142. }
  4143. }
  4144. ZONE_CROSS_UNLOCK(zone);
  4145. out:
  4146. if (bucket->ub_cnt == 0)
  4147. bucket->ub_seq = SMR_SEQ_INVALID;
  4148. bucket_free(zone, bucket, udata);
  4149. while ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
  4150. STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
  4151. bucket_free(zone, b, udata);
  4152. }
  4153. while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
  4154. STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
  4155. domain = item_domain(b->ub_bucket[0]);
  4156. zone_put_bucket(zone, domain, b, udata, true);
  4157. }
  4158. }
  4159. #endif
  4160. static void
  4161. zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
  4162. int itemdomain, bool ws)
  4163. {
  4164. #ifdef NUMA
  4165. /*
  4166. * Buckets coming from the wrong domain will be entirely for the
  4167. * only other domain on two domain systems. In this case we can
  4168. * simply cache them. Otherwise we need to sort them back to
  4169. * correct domains.
  4170. */
  4171. if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
  4172. vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
  4173. zone_free_cross(zone, bucket, udata);
  4174. return;
  4175. }
  4176. #endif
  4177. /*
  4178. * Attempt to save the bucket in the zone's domain bucket cache.
  4179. */
  4180. CTR3(KTR_UMA,
  4181. "uma_zfree: zone %s(%p) putting bucket %p on free list",
  4182. zone->uz_name, zone, bucket);
  4183. /* ub_cnt is pointing to the last free item */
  4184. if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
  4185. itemdomain = zone_domain_lowest(zone, itemdomain);
  4186. zone_put_bucket(zone, itemdomain, bucket, udata, ws);
  4187. }
  4188. /*
  4189. * Populate a free or cross bucket for the current cpu cache. Free any
  4190. * existing full bucket either to the zone cache or back to the slab layer.
  4191. *
  4192. * Enters and returns in a critical section. false return indicates that
  4193. * we can not satisfy this free in the cache layer. true indicates that
  4194. * the caller should retry.
  4195. */
  4196. static __noinline bool
  4197. cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, int itemdomain)
  4198. {
  4199. uma_cache_bucket_t cbucket;
  4200. uma_bucket_t newbucket, bucket;
  4201. CRITICAL_ASSERT(curthread);
  4202. if (zone->uz_bucket_size == 0)
  4203. return false;
  4204. cache = &zone->uz_cpu[curcpu];
  4205. newbucket = NULL;
  4206. /*
  4207. * FIRSTTOUCH domains need to free to the correct zdom. When
  4208. * enabled this is the zdom of the item. The bucket is the
  4209. * cross bucket if the current domain and itemdomain do not match.
  4210. */
  4211. cbucket = &cache->uc_freebucket;
  4212. #ifdef NUMA
  4213. if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
  4214. if (PCPU_GET(domain) != itemdomain) {
  4215. cbucket = &cache->uc_crossbucket;
  4216. if (cbucket->ucb_cnt != 0)
  4217. counter_u64_add(zone->uz_xdomain,
  4218. cbucket->ucb_cnt);
  4219. }
  4220. }
  4221. #endif
  4222. bucket = cache_bucket_unload(cbucket);
  4223. KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
  4224. ("cache_free: Entered with non-full free bucket."));
  4225. /* We are no longer associated with this CPU. */
  4226. critical_exit();
  4227. /*
  4228. * Don't let SMR zones operate without a free bucket. Force
  4229. * a synchronize and re-use this one. We will only degrade
  4230. * to a synchronize every bucket_size items rather than every
  4231. * item if we fail to allocate a bucket.
  4232. */
  4233. if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
  4234. if (bucket != NULL)
  4235. bucket->ub_seq = smr_advance(zone->uz_smr);
  4236. newbucket = bucket_alloc(zone, udata, M_NOWAIT);
  4237. if (newbucket == NULL && bucket != NULL) {
  4238. bucket_drain(zone, bucket);
  4239. newbucket = bucket;
  4240. bucket = NULL;
  4241. }
  4242. } else if (!bucketdisable)
  4243. newbucket = bucket_alloc(zone, udata, M_NOWAIT);
  4244. if (bucket != NULL)
  4245. zone_free_bucket(zone, bucket, udata, itemdomain, true);
  4246. critical_enter();
  4247. if ((bucket = newbucket) == NULL)
  4248. return (false);
  4249. cache = &zone->uz_cpu[curcpu];
  4250. #ifdef NUMA
  4251. /*
  4252. * Check to see if we should be populating the cross bucket. If it
  4253. * is already populated we will fall through and attempt to populate
  4254. * the free bucket.
  4255. */
  4256. if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
  4257. if (PCPU_GET(domain) != itemdomain &&
  4258. cache->uc_crossbucket.ucb_bucket == NULL) {
  4259. cache_bucket_load_cross(cache, bucket);
  4260. return (true);
  4261. }
  4262. }
  4263. #endif
  4264. /*
  4265. * We may have lost the race to fill the bucket or switched CPUs.
  4266. */
  4267. if (cache->uc_freebucket.ucb_bucket != NULL) {
  4268. critical_exit();
  4269. bucket_free(zone, bucket, udata);
  4270. critical_enter();
  4271. } else
  4272. cache_bucket_load_free(cache, bucket);
  4273. return (true);
  4274. }
  4275. static void
  4276. slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
  4277. {
  4278. uma_keg_t keg;
  4279. uma_domain_t dom;
  4280. int freei;
  4281. keg = zone->uz_keg;
  4282. KEG_LOCK_ASSERT(keg, slab->us_domain);
  4283. /* Do we need to remove from any lists? */
  4284. dom = &keg->uk_domain[slab->us_domain];
  4285. if (slab->us_freecount + 1 == keg->uk_ipers) {
  4286. LIST_REMOVE(slab, us_link);
  4287. LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
  4288. dom->ud_free_slabs++;
  4289. } else if (slab->us_freecount == 0) {
  4290. LIST_REMOVE(slab, us_link);
  4291. LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
  4292. }
  4293. /* Slab management. */
  4294. freei = slab_item_index(slab, keg, item);
  4295. BIT_SET(keg->uk_ipers, freei, &slab->us_free);
  4296. slab->us_freecount++;
  4297. /* Keg statistics. */
  4298. dom->ud_free_items++;
  4299. }
  4300. static void
  4301. zone_release(void *arg, void **bucket, int cnt)
  4302. {
  4303. struct mtx *lock;
  4304. uma_zone_t zone;
  4305. uma_slab_t slab;
  4306. uma_keg_t keg;
  4307. uint8_t *mem;
  4308. void *item;
  4309. int i;
  4310. zone = arg;
  4311. keg = zone->uz_keg;
  4312. lock = NULL;
  4313. if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
  4314. lock = KEG_LOCK(keg, 0);
  4315. for (i = 0; i < cnt; i++) {
  4316. item = bucket[i];
  4317. if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
  4318. slab = vtoslab((vm_offset_t)item);
  4319. } else {
  4320. mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
  4321. if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
  4322. slab = hash_sfind(&keg->uk_hash, mem);
  4323. else
  4324. slab = (uma_slab_t)(mem + keg->uk_pgoff);
  4325. }
  4326. if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
  4327. if (lock != NULL)
  4328. mtx_unlock(lock);
  4329. lock = KEG_LOCK(keg, slab->us_domain);
  4330. }
  4331. slab_free_item(zone, slab, item);
  4332. }
  4333. if (lock != NULL)
  4334. mtx_unlock(lock);
  4335. }
  4336. /*
  4337. * Frees a single item to any zone.
  4338. *
  4339. * Arguments:
  4340. * zone The zone to free to
  4341. * item The item we're freeing
  4342. * udata User supplied data for the dtor
  4343. * skip Skip dtors and finis
  4344. */
  4345. static __noinline void
  4346. zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
  4347. {
  4348. /*
  4349. * If a free is sent directly to an SMR zone we have to
  4350. * synchronize immediately because the item can instantly
  4351. * be reallocated. This should only happen in degenerate
  4352. * cases when no memory is available for per-cpu caches.
  4353. */
  4354. if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
  4355. smr_synchronize(zone->uz_smr);
  4356. item_dtor(zone, item, zone->uz_size, udata, skip);
  4357. if (skip < SKIP_FINI && zone->uz_fini) {
  4358. kasan_mark_item_valid(zone, item);
  4359. zone->uz_fini(item, zone->uz_size);
  4360. kasan_mark_item_invalid(zone, item);
  4361. }
  4362. zone->uz_release(zone->uz_arg, &item, 1);
  4363. if (skip & SKIP_CNT)
  4364. return;
  4365. counter_u64_add(zone->uz_frees, 1);
  4366. if (zone->uz_max_items > 0)
  4367. zone_free_limit(zone, 1);
  4368. }
  4369. /* See uma.h */
  4370. int
  4371. uma_zone_set_max(uma_zone_t zone, int nitems)
  4372. {
  4373. /*
  4374. * If the limit is small, we may need to constrain the maximum per-CPU
  4375. * cache size, or disable caching entirely.
  4376. */
  4377. uma_zone_set_maxcache(zone, nitems);
  4378. /*
  4379. * XXX This can misbehave if the zone has any allocations with
  4380. * no limit and a limit is imposed. There is currently no
  4381. * way to clear a limit.
  4382. */
  4383. ZONE_LOCK(zone);
  4384. if (zone->uz_max_items == 0)
  4385. ZONE_ASSERT_COLD(zone);
  4386. zone->uz_max_items = nitems;
  4387. zone->uz_flags |= UMA_ZFLAG_LIMIT;
  4388. zone_update_caches(zone);
  4389. /* We may need to wake waiters. */
  4390. wakeup(&zone->uz_max_items);
  4391. ZONE_UNLOCK(zone);
  4392. return (nitems);
  4393. }
  4394. /* See uma.h */
  4395. void
  4396. uma_zone_set_maxcache(uma_zone_t zone, int nitems)
  4397. {
  4398. int bpcpu, bpdom, bsize, nb;
  4399. ZONE_LOCK(zone);
  4400. /*
  4401. * Compute a lower bound on the number of items that may be cached in
  4402. * the zone. Each CPU gets at least two buckets, and for cross-domain
  4403. * frees we use an additional bucket per CPU and per domain. Select the
  4404. * largest bucket size that does not exceed half of the requested limit,
  4405. * with the left over space given to the full bucket cache.
  4406. */
  4407. bpdom = 0;
  4408. bpcpu = 2;
  4409. #ifdef NUMA
  4410. if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 && vm_ndomains > 1) {
  4411. bpcpu++;
  4412. bpdom++;
  4413. }
  4414. #endif
  4415. nb = bpcpu * mp_ncpus + bpdom * vm_ndomains;
  4416. bsize = nitems / nb / 2;
  4417. if (bsize > BUCKET_MAX)
  4418. bsize = BUCKET_MAX;
  4419. else if (bsize == 0 && nitems / nb > 0)
  4420. bsize = 1;
  4421. zone->uz_bucket_size_max = zone->uz_bucket_size = bsize;
  4422. if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
  4423. zone->uz_bucket_size_min = zone->uz_bucket_size_max;
  4424. zone->uz_bucket_max = nitems - nb * bsize;
  4425. ZONE_UNLOCK(zone);
  4426. }
  4427. /* See uma.h */
  4428. int
  4429. uma_zone_get_max(uma_zone_t zone)
  4430. {
  4431. int nitems;
  4432. nitems = atomic_load_64(&zone->uz_max_items);
  4433. return (nitems);
  4434. }
  4435. /* See uma.h */
  4436. void
  4437. uma_zone_set_warning(uma_zone_t zone, const char *warning)
  4438. {
  4439. ZONE_ASSERT_COLD(zone);
  4440. zone->uz_warning = warning;
  4441. }
  4442. /* See uma.h */
  4443. void
  4444. uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
  4445. {
  4446. ZONE_ASSERT_COLD(zone);
  4447. TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
  4448. }
  4449. /* See uma.h */
  4450. int
  4451. uma_zone_get_cur(uma_zone_t zone)
  4452. {
  4453. int64_t nitems;
  4454. u_int i;
  4455. nitems = 0;
  4456. if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
  4457. nitems = counter_u64_fetch(zone->uz_allocs) -
  4458. counter_u64_fetch(zone->uz_frees);
  4459. CPU_FOREACH(i)
  4460. nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
  4461. atomic_load_64(&zone->uz_cpu[i].uc_frees);
  4462. return (nitems < 0 ? 0 : nitems);
  4463. }
  4464. static uint64_t
  4465. uma_zone_get_allocs(uma_zone_t zone)
  4466. {
  4467. uint64_t nitems;
  4468. u_int i;
  4469. nitems = 0;
  4470. if (zone->uz_allocs != EARLY_COUNTER)
  4471. nitems = counter_u64_fetch(zone->uz_allocs);
  4472. CPU_FOREACH(i)
  4473. nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
  4474. return (nitems);
  4475. }
  4476. static uint64_t
  4477. uma_zone_get_frees(uma_zone_t zone)
  4478. {
  4479. uint64_t nitems;
  4480. u_int i;
  4481. nitems = 0;
  4482. if (zone->uz_frees != EARLY_COUNTER)
  4483. nitems = counter_u64_fetch(zone->uz_frees);
  4484. CPU_FOREACH(i)
  4485. nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
  4486. return (nitems);
  4487. }
  4488. #ifdef INVARIANTS
  4489. /* Used only for KEG_ASSERT_COLD(). */
  4490. static uint64_t
  4491. uma_keg_get_allocs(uma_keg_t keg)
  4492. {
  4493. uma_zone_t z;
  4494. uint64_t nitems;
  4495. nitems = 0;
  4496. LIST_FOREACH(z, &keg->uk_zones, uz_link)
  4497. nitems += uma_zone_get_allocs(z);
  4498. return (nitems);
  4499. }
  4500. #endif
  4501. /* See uma.h */
  4502. void
  4503. uma_zone_set_init(uma_zone_t zone, uma_init uminit)
  4504. {
  4505. uma_keg_t keg;
  4506. KEG_GET(zone, keg);
  4507. KEG_ASSERT_COLD(keg);
  4508. keg->uk_init = uminit;
  4509. }
  4510. /* See uma.h */
  4511. void
  4512. uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
  4513. {
  4514. uma_keg_t keg;
  4515. KEG_GET(zone, keg);
  4516. KEG_ASSERT_COLD(keg);
  4517. keg->uk_fini = fini;
  4518. }
  4519. /* See uma.h */
  4520. void
  4521. uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
  4522. {
  4523. ZONE_ASSERT_COLD(zone);
  4524. zone->uz_init = zinit;
  4525. }
  4526. /* See uma.h */
  4527. void
  4528. uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
  4529. {
  4530. ZONE_ASSERT_COLD(zone);
  4531. zone->uz_fini = zfini;
  4532. }
  4533. /* See uma.h */
  4534. void
  4535. uma_zone_set_freef(uma_zone_t zone, uma_free freef)
  4536. {
  4537. uma_keg_t keg;
  4538. KEG_GET(zone, keg);
  4539. KEG_ASSERT_COLD(keg);
  4540. keg->uk_freef = freef;
  4541. }
  4542. /* See uma.h */
  4543. void
  4544. uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
  4545. {
  4546. uma_keg_t keg;
  4547. KEG_GET(zone, keg);
  4548. KEG_ASSERT_COLD(keg);
  4549. keg->uk_allocf = allocf;
  4550. }
  4551. /* See uma.h */
  4552. void
  4553. uma_zone_set_smr(uma_zone_t zone, smr_t smr)
  4554. {
  4555. ZONE_ASSERT_COLD(zone);
  4556. KASSERT(smr != NULL, ("Got NULL smr"));
  4557. KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
  4558. ("zone %p (%s) already uses SMR", zone, zone->uz_name));
  4559. zone->uz_flags |= UMA_ZONE_SMR;
  4560. zone->uz_smr = smr;
  4561. zone_update_caches(zone);
  4562. }
  4563. smr_t
  4564. uma_zone_get_smr(uma_zone_t zone)
  4565. {
  4566. return (zone->uz_smr);
  4567. }
  4568. /* See uma.h */
  4569. void
  4570. uma_zone_reserve(uma_zone_t zone, int items)
  4571. {
  4572. uma_keg_t keg;
  4573. KEG_GET(zone, keg);
  4574. KEG_ASSERT_COLD(keg);
  4575. keg->uk_reserve = items;
  4576. }
  4577. /* See uma.h */
  4578. int
  4579. uma_zone_reserve_kva(uma_zone_t zone, int count)
  4580. {
  4581. uma_keg_t keg;
  4582. vm_offset_t kva;
  4583. u_int pages;
  4584. KEG_GET(zone, keg);
  4585. KEG_ASSERT_COLD(keg);
  4586. ZONE_ASSERT_COLD(zone);
  4587. pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
  4588. #ifdef UMA_USE_DMAP
  4589. if (keg->uk_ppera > 1) {
  4590. #else
  4591. if (1) {
  4592. #endif
  4593. kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
  4594. if (kva == 0)
  4595. return (0);
  4596. } else
  4597. kva = 0;
  4598. MPASS(keg->uk_kva == 0);
  4599. keg->uk_kva = kva;
  4600. keg->uk_offset = 0;
  4601. zone->uz_max_items = pages * keg->uk_ipers;
  4602. #ifdef UMA_USE_DMAP
  4603. keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
  4604. #else
  4605. keg->uk_allocf = noobj_alloc;
  4606. #endif
  4607. keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
  4608. zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
  4609. zone_update_caches(zone);
  4610. return (1);
  4611. }
  4612. /* See uma.h */
  4613. void
  4614. uma_prealloc(uma_zone_t zone, int items)
  4615. {
  4616. struct vm_domainset_iter di;
  4617. uma_domain_t dom;
  4618. uma_slab_t slab;
  4619. uma_keg_t keg;
  4620. int aflags, domain, slabs;
  4621. KEG_GET(zone, keg);
  4622. slabs = howmany(items, keg->uk_ipers);
  4623. while (slabs-- > 0) {
  4624. aflags = M_NOWAIT;
  4625. vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
  4626. &aflags);
  4627. for (;;) {
  4628. slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
  4629. aflags);
  4630. if (slab != NULL) {
  4631. dom = &keg->uk_domain[slab->us_domain];
  4632. /*
  4633. * keg_alloc_slab() always returns a slab on the
  4634. * partial list.
  4635. */
  4636. LIST_REMOVE(slab, us_link);
  4637. LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
  4638. us_link);
  4639. dom->ud_free_slabs++;
  4640. KEG_UNLOCK(keg, slab->us_domain);
  4641. break;
  4642. }
  4643. if (vm_domainset_iter_policy(&di, &domain) != 0)
  4644. vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
  4645. }
  4646. }
  4647. }
  4648. /*
  4649. * Returns a snapshot of memory consumption in bytes.
  4650. */
  4651. size_t
  4652. uma_zone_memory(uma_zone_t zone)
  4653. {
  4654. size_t sz;
  4655. int i;
  4656. sz = 0;
  4657. if (zone->uz_flags & UMA_ZFLAG_CACHE) {
  4658. for (i = 0; i < vm_ndomains; i++)
  4659. sz += ZDOM_GET(zone, i)->uzd_nitems;
  4660. return (sz * zone->uz_size);
  4661. }
  4662. for (i = 0; i < vm_ndomains; i++)
  4663. sz += zone->uz_keg->uk_domain[i].ud_pages;
  4664. return (sz * PAGE_SIZE);
  4665. }
  4666. struct uma_reclaim_args {
  4667. int domain;
  4668. int req;
  4669. };
  4670. static void
  4671. uma_reclaim_domain_cb(uma_zone_t zone, void *arg)
  4672. {
  4673. struct uma_reclaim_args *args;
  4674. args = arg;
  4675. if ((zone->uz_flags & UMA_ZONE_UNMANAGED) == 0)
  4676. uma_zone_reclaim_domain(zone, args->req, args->domain);
  4677. }
  4678. /* See uma.h */
  4679. void
  4680. uma_reclaim(int req)
  4681. {
  4682. uma_reclaim_domain(req, UMA_ANYDOMAIN);
  4683. }
  4684. void
  4685. uma_reclaim_domain(int req, int domain)
  4686. {
  4687. struct uma_reclaim_args args;
  4688. bucket_enable();
  4689. args.domain = domain;
  4690. args.req = req;
  4691. sx_slock(&uma_reclaim_lock);
  4692. switch (req) {
  4693. case UMA_RECLAIM_TRIM:
  4694. case UMA_RECLAIM_DRAIN:
  4695. zone_foreach(uma_reclaim_domain_cb, &args);
  4696. break;
  4697. case UMA_RECLAIM_DRAIN_CPU:
  4698. zone_foreach(uma_reclaim_domain_cb, &args);
  4699. pcpu_cache_drain_safe(NULL);
  4700. zone_foreach(uma_reclaim_domain_cb, &args);
  4701. break;
  4702. default:
  4703. panic("unhandled reclamation request %d", req);
  4704. }
  4705. /*
  4706. * Some slabs may have been freed but this zone will be visited early
  4707. * we visit again so that we can free pages that are empty once other
  4708. * zones are drained. We have to do the same for buckets.
  4709. */
  4710. uma_zone_reclaim_domain(slabzones[0], UMA_RECLAIM_DRAIN, domain);
  4711. uma_zone_reclaim_domain(slabzones[1], UMA_RECLAIM_DRAIN, domain);
  4712. bucket_zone_drain(domain);
  4713. sx_sunlock(&uma_reclaim_lock);
  4714. }
  4715. static volatile int uma_reclaim_needed;
  4716. void
  4717. uma_reclaim_wakeup(void)
  4718. {
  4719. if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
  4720. wakeup(uma_reclaim);
  4721. }
  4722. void
  4723. uma_reclaim_worker(void *arg __unused)
  4724. {
  4725. for (;;) {
  4726. sx_xlock(&uma_reclaim_lock);
  4727. while (atomic_load_int(&uma_reclaim_needed) == 0)
  4728. sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
  4729. hz);
  4730. sx_xunlock(&uma_reclaim_lock);
  4731. EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
  4732. uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
  4733. atomic_store_int(&uma_reclaim_needed, 0);
  4734. /* Don't fire more than once per-second. */
  4735. pause("umarclslp", hz);
  4736. }
  4737. }
  4738. /* See uma.h */
  4739. void
  4740. uma_zone_reclaim(uma_zone_t zone, int req)
  4741. {
  4742. uma_zone_reclaim_domain(zone, req, UMA_ANYDOMAIN);
  4743. }
  4744. void
  4745. uma_zone_reclaim_domain(uma_zone_t zone, int req, int domain)
  4746. {
  4747. switch (req) {
  4748. case UMA_RECLAIM_TRIM:
  4749. zone_reclaim(zone, domain, M_NOWAIT, false);
  4750. break;
  4751. case UMA_RECLAIM_DRAIN:
  4752. zone_reclaim(zone, domain, M_NOWAIT, true);
  4753. break;
  4754. case UMA_RECLAIM_DRAIN_CPU:
  4755. pcpu_cache_drain_safe(zone);
  4756. zone_reclaim(zone, domain, M_NOWAIT, true);
  4757. break;
  4758. default:
  4759. panic("unhandled reclamation request %d", req);
  4760. }
  4761. }
  4762. /* See uma.h */
  4763. int
  4764. uma_zone_exhausted(uma_zone_t zone)
  4765. {
  4766. return (atomic_load_32(&zone->uz_sleepers) > 0);
  4767. }
  4768. unsigned long
  4769. uma_limit(void)
  4770. {
  4771. return (uma_kmem_limit);
  4772. }
  4773. void
  4774. uma_set_limit(unsigned long limit)
  4775. {
  4776. uma_kmem_limit = limit;
  4777. }
  4778. unsigned long
  4779. uma_size(void)
  4780. {
  4781. return (atomic_load_long(&uma_kmem_total));
  4782. }
  4783. long
  4784. uma_avail(void)
  4785. {
  4786. return (uma_kmem_limit - uma_size());
  4787. }
  4788. #ifdef DDB
  4789. /*
  4790. * Generate statistics across both the zone and its per-cpu cache's. Return
  4791. * desired statistics if the pointer is non-NULL for that statistic.
  4792. *
  4793. * Note: does not update the zone statistics, as it can't safely clear the
  4794. * per-CPU cache statistic.
  4795. *
  4796. */
  4797. static void
  4798. uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
  4799. uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
  4800. {
  4801. uma_cache_t cache;
  4802. uint64_t allocs, frees, sleeps, xdomain;
  4803. int cachefree, cpu;
  4804. allocs = frees = sleeps = xdomain = 0;
  4805. cachefree = 0;
  4806. CPU_FOREACH(cpu) {
  4807. cache = &z->uz_cpu[cpu];
  4808. cachefree += cache->uc_allocbucket.ucb_cnt;
  4809. cachefree += cache->uc_freebucket.ucb_cnt;
  4810. xdomain += cache->uc_crossbucket.ucb_cnt;
  4811. cachefree += cache->uc_crossbucket.ucb_cnt;
  4812. allocs += cache->uc_allocs;
  4813. frees += cache->uc_frees;
  4814. }
  4815. allocs += counter_u64_fetch(z->uz_allocs);
  4816. frees += counter_u64_fetch(z->uz_frees);
  4817. xdomain += counter_u64_fetch(z->uz_xdomain);
  4818. sleeps += z->uz_sleeps;
  4819. if (cachefreep != NULL)
  4820. *cachefreep = cachefree;
  4821. if (allocsp != NULL)
  4822. *allocsp = allocs;
  4823. if (freesp != NULL)
  4824. *freesp = frees;
  4825. if (sleepsp != NULL)
  4826. *sleepsp = sleeps;
  4827. if (xdomainp != NULL)
  4828. *xdomainp = xdomain;
  4829. }
  4830. #endif /* DDB */
  4831. static int
  4832. sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
  4833. {
  4834. uma_keg_t kz;
  4835. uma_zone_t z;
  4836. int count;
  4837. count = 0;
  4838. rw_rlock(&uma_rwlock);
  4839. LIST_FOREACH(kz, &uma_kegs, uk_link) {
  4840. LIST_FOREACH(z, &kz->uk_zones, uz_link)
  4841. count++;
  4842. }
  4843. LIST_FOREACH(z, &uma_cachezones, uz_link)
  4844. count++;
  4845. rw_runlock(&uma_rwlock);
  4846. return (sysctl_handle_int(oidp, &count, 0, req));
  4847. }
  4848. static void
  4849. uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
  4850. struct uma_percpu_stat *ups, bool internal)
  4851. {
  4852. uma_zone_domain_t zdom;
  4853. uma_cache_t cache;
  4854. int i;
  4855. for (i = 0; i < vm_ndomains; i++) {
  4856. zdom = ZDOM_GET(z, i);
  4857. uth->uth_zone_free += zdom->uzd_nitems;
  4858. }
  4859. uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
  4860. uth->uth_frees = counter_u64_fetch(z->uz_frees);
  4861. uth->uth_fails = counter_u64_fetch(z->uz_fails);
  4862. uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
  4863. uth->uth_sleeps = z->uz_sleeps;
  4864. for (i = 0; i < mp_maxid + 1; i++) {
  4865. bzero(&ups[i], sizeof(*ups));
  4866. if (internal || CPU_ABSENT(i))
  4867. continue;
  4868. cache = &z->uz_cpu[i];
  4869. ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
  4870. ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
  4871. ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
  4872. ups[i].ups_allocs = cache->uc_allocs;
  4873. ups[i].ups_frees = cache->uc_frees;
  4874. }
  4875. }
  4876. static int
  4877. sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
  4878. {
  4879. struct uma_stream_header ush;
  4880. struct uma_type_header uth;
  4881. struct uma_percpu_stat *ups;
  4882. struct sbuf sbuf;
  4883. uma_keg_t kz;
  4884. uma_zone_t z;
  4885. uint64_t items;
  4886. uint32_t kfree, pages;
  4887. int count, error, i;
  4888. error = sysctl_wire_old_buffer(req, 0);
  4889. if (error != 0)
  4890. return (error);
  4891. sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
  4892. sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
  4893. ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
  4894. count = 0;
  4895. rw_rlock(&uma_rwlock);
  4896. LIST_FOREACH(kz, &uma_kegs, uk_link) {
  4897. LIST_FOREACH(z, &kz->uk_zones, uz_link)
  4898. count++;
  4899. }
  4900. LIST_FOREACH(z, &uma_cachezones, uz_link)
  4901. count++;
  4902. /*
  4903. * Insert stream header.
  4904. */
  4905. bzero(&ush, sizeof(ush));
  4906. ush.ush_version = UMA_STREAM_VERSION;
  4907. ush.ush_maxcpus = (mp_maxid + 1);
  4908. ush.ush_count = count;
  4909. (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
  4910. LIST_FOREACH(kz, &uma_kegs, uk_link) {
  4911. kfree = pages = 0;
  4912. for (i = 0; i < vm_ndomains; i++) {
  4913. kfree += kz->uk_domain[i].ud_free_items;
  4914. pages += kz->uk_domain[i].ud_pages;
  4915. }
  4916. LIST_FOREACH(z, &kz->uk_zones, uz_link) {
  4917. bzero(&uth, sizeof(uth));
  4918. strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
  4919. uth.uth_align = kz->uk_align;
  4920. uth.uth_size = kz->uk_size;
  4921. uth.uth_rsize = kz->uk_rsize;
  4922. if (z->uz_max_items > 0) {
  4923. items = UZ_ITEMS_COUNT(z->uz_items);
  4924. uth.uth_pages = (items / kz->uk_ipers) *
  4925. kz->uk_ppera;
  4926. } else
  4927. uth.uth_pages = pages;
  4928. uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
  4929. kz->uk_ppera;
  4930. uth.uth_limit = z->uz_max_items;
  4931. uth.uth_keg_free = kfree;
  4932. /*
  4933. * A zone is secondary is it is not the first entry
  4934. * on the keg's zone list.
  4935. */
  4936. if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
  4937. (LIST_FIRST(&kz->uk_zones) != z))
  4938. uth.uth_zone_flags = UTH_ZONE_SECONDARY;
  4939. uma_vm_zone_stats(&uth, z, &sbuf, ups,
  4940. kz->uk_flags & UMA_ZFLAG_INTERNAL);
  4941. (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
  4942. for (i = 0; i < mp_maxid + 1; i++)
  4943. (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
  4944. }
  4945. }
  4946. LIST_FOREACH(z, &uma_cachezones, uz_link) {
  4947. bzero(&uth, sizeof(uth));
  4948. strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
  4949. uth.uth_size = z->uz_size;
  4950. uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
  4951. (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
  4952. for (i = 0; i < mp_maxid + 1; i++)
  4953. (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
  4954. }
  4955. rw_runlock(&uma_rwlock);
  4956. error = sbuf_finish(&sbuf);
  4957. sbuf_delete(&sbuf);
  4958. free(ups, M_TEMP);
  4959. return (error);
  4960. }
  4961. int
  4962. sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
  4963. {
  4964. uma_zone_t zone = *(uma_zone_t *)arg1;
  4965. int error, max;
  4966. max = uma_zone_get_max(zone);
  4967. error = sysctl_handle_int(oidp, &max, 0, req);
  4968. if (error || !req->newptr)
  4969. return (error);
  4970. uma_zone_set_max(zone, max);
  4971. return (0);
  4972. }
  4973. int
  4974. sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
  4975. {
  4976. uma_zone_t zone;
  4977. int cur;
  4978. /*
  4979. * Some callers want to add sysctls for global zones that
  4980. * may not yet exist so they pass a pointer to a pointer.
  4981. */
  4982. if (arg2 == 0)
  4983. zone = *(uma_zone_t *)arg1;
  4984. else
  4985. zone = arg1;
  4986. cur = uma_zone_get_cur(zone);
  4987. return (sysctl_handle_int(oidp, &cur, 0, req));
  4988. }
  4989. static int
  4990. sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
  4991. {
  4992. uma_zone_t zone = arg1;
  4993. uint64_t cur;
  4994. cur = uma_zone_get_allocs(zone);
  4995. return (sysctl_handle_64(oidp, &cur, 0, req));
  4996. }
  4997. static int
  4998. sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
  4999. {
  5000. uma_zone_t zone = arg1;
  5001. uint64_t cur;
  5002. cur = uma_zone_get_frees(zone);
  5003. return (sysctl_handle_64(oidp, &cur, 0, req));
  5004. }
  5005. static int
  5006. sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
  5007. {
  5008. struct sbuf sbuf;
  5009. uma_zone_t zone = arg1;
  5010. int error;
  5011. sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
  5012. if (zone->uz_flags != 0)
  5013. sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
  5014. else
  5015. sbuf_printf(&sbuf, "0");
  5016. error = sbuf_finish(&sbuf);
  5017. sbuf_delete(&sbuf);
  5018. return (error);
  5019. }
  5020. static int
  5021. sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
  5022. {
  5023. uma_keg_t keg = arg1;
  5024. int avail, effpct, total;
  5025. total = keg->uk_ppera * PAGE_SIZE;
  5026. if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
  5027. total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
  5028. /*
  5029. * We consider the client's requested size and alignment here, not the
  5030. * real size determination uk_rsize, because we also adjust the real
  5031. * size for internal implementation reasons (max bitset size).
  5032. */
  5033. avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
  5034. if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
  5035. avail *= mp_maxid + 1;
  5036. effpct = 100 * avail / total;
  5037. return (sysctl_handle_int(oidp, &effpct, 0, req));
  5038. }
  5039. static int
  5040. sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
  5041. {
  5042. uma_zone_t zone = arg1;
  5043. uint64_t cur;
  5044. cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
  5045. return (sysctl_handle_64(oidp, &cur, 0, req));
  5046. }
  5047. #ifdef INVARIANTS
  5048. static uma_slab_t
  5049. uma_dbg_getslab(uma_zone_t zone, void *item)
  5050. {
  5051. uma_slab_t slab;
  5052. uma_keg_t keg;
  5053. uint8_t *mem;
  5054. /*
  5055. * It is safe to return the slab here even though the
  5056. * zone is unlocked because the item's allocation state
  5057. * essentially holds a reference.
  5058. */
  5059. mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
  5060. if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
  5061. return (NULL);
  5062. if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
  5063. return (vtoslab((vm_offset_t)mem));
  5064. keg = zone->uz_keg;
  5065. if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
  5066. return ((uma_slab_t)(mem + keg->uk_pgoff));
  5067. KEG_LOCK(keg, 0);
  5068. slab = hash_sfind(&keg->uk_hash, mem);
  5069. KEG_UNLOCK(keg, 0);
  5070. return (slab);
  5071. }
  5072. static bool
  5073. uma_dbg_zskip(uma_zone_t zone, void *mem)
  5074. {
  5075. if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
  5076. return (true);
  5077. return (uma_dbg_kskip(zone->uz_keg, mem));
  5078. }
  5079. static bool
  5080. uma_dbg_kskip(uma_keg_t keg, void *mem)
  5081. {
  5082. uintptr_t idx;
  5083. if (dbg_divisor == 0)
  5084. return (true);
  5085. if (dbg_divisor == 1)
  5086. return (false);
  5087. idx = (uintptr_t)mem >> PAGE_SHIFT;
  5088. if (keg->uk_ipers > 1) {
  5089. idx *= keg->uk_ipers;
  5090. idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
  5091. }
  5092. if ((idx / dbg_divisor) * dbg_divisor != idx) {
  5093. counter_u64_add(uma_skip_cnt, 1);
  5094. return (true);
  5095. }
  5096. counter_u64_add(uma_dbg_cnt, 1);
  5097. return (false);
  5098. }
  5099. /*
  5100. * Set up the slab's freei data such that uma_dbg_free can function.
  5101. *
  5102. */
  5103. static void
  5104. uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
  5105. {
  5106. uma_keg_t keg;
  5107. int freei;
  5108. if (slab == NULL) {
  5109. slab = uma_dbg_getslab(zone, item);
  5110. if (slab == NULL)
  5111. panic("uma: item %p did not belong to zone %s",
  5112. item, zone->uz_name);
  5113. }
  5114. keg = zone->uz_keg;
  5115. freei = slab_item_index(slab, keg, item);
  5116. if (BIT_TEST_SET_ATOMIC(keg->uk_ipers, freei,
  5117. slab_dbg_bits(slab, keg)))
  5118. panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
  5119. item, zone, zone->uz_name, slab, freei);
  5120. }
  5121. /*
  5122. * Verifies freed addresses. Checks for alignment, valid slab membership
  5123. * and duplicate frees.
  5124. *
  5125. */
  5126. static void
  5127. uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
  5128. {
  5129. uma_keg_t keg;
  5130. int freei;
  5131. if (slab == NULL) {
  5132. slab = uma_dbg_getslab(zone, item);
  5133. if (slab == NULL)
  5134. panic("uma: Freed item %p did not belong to zone %s",
  5135. item, zone->uz_name);
  5136. }
  5137. keg = zone->uz_keg;
  5138. freei = slab_item_index(slab, keg, item);
  5139. if (freei >= keg->uk_ipers)
  5140. panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
  5141. item, zone, zone->uz_name, slab, freei);
  5142. if (slab_item(slab, keg, freei) != item)
  5143. panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
  5144. item, zone, zone->uz_name, slab, freei);
  5145. if (!BIT_TEST_CLR_ATOMIC(keg->uk_ipers, freei,
  5146. slab_dbg_bits(slab, keg)))
  5147. panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
  5148. item, zone, zone->uz_name, slab, freei);
  5149. }
  5150. #endif /* INVARIANTS */
  5151. #ifdef DDB
  5152. static int64_t
  5153. get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
  5154. uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
  5155. {
  5156. uint64_t frees;
  5157. int i;
  5158. if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
  5159. *allocs = counter_u64_fetch(z->uz_allocs);
  5160. frees = counter_u64_fetch(z->uz_frees);
  5161. *sleeps = z->uz_sleeps;
  5162. *cachefree = 0;
  5163. *xdomain = 0;
  5164. } else
  5165. uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
  5166. xdomain);
  5167. for (i = 0; i < vm_ndomains; i++) {
  5168. *cachefree += ZDOM_GET(z, i)->uzd_nitems;
  5169. if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
  5170. (LIST_FIRST(&kz->uk_zones) != z)))
  5171. *cachefree += kz->uk_domain[i].ud_free_items;
  5172. }
  5173. *used = *allocs - frees;
  5174. return (((int64_t)*used + *cachefree) * kz->uk_size);
  5175. }
  5176. DB_SHOW_COMMAND_FLAGS(uma, db_show_uma, DB_CMD_MEMSAFE)
  5177. {
  5178. const char *fmt_hdr, *fmt_entry;
  5179. uma_keg_t kz;
  5180. uma_zone_t z;
  5181. uint64_t allocs, used, sleeps, xdomain;
  5182. long cachefree;
  5183. /* variables for sorting */
  5184. uma_keg_t cur_keg;
  5185. uma_zone_t cur_zone, last_zone;
  5186. int64_t cur_size, last_size, size;
  5187. int ties;
  5188. /* /i option produces machine-parseable CSV output */
  5189. if (modif[0] == 'i') {
  5190. fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
  5191. fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
  5192. } else {
  5193. fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
  5194. fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
  5195. }
  5196. db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
  5197. "Sleeps", "Bucket", "Total Mem", "XFree");
  5198. /* Sort the zones with largest size first. */
  5199. last_zone = NULL;
  5200. last_size = INT64_MAX;
  5201. for (;;) {
  5202. cur_zone = NULL;
  5203. cur_size = -1;
  5204. ties = 0;
  5205. LIST_FOREACH(kz, &uma_kegs, uk_link) {
  5206. LIST_FOREACH(z, &kz->uk_zones, uz_link) {
  5207. /*
  5208. * In the case of size ties, print out zones
  5209. * in the order they are encountered. That is,
  5210. * when we encounter the most recently output
  5211. * zone, we have already printed all preceding
  5212. * ties, and we must print all following ties.
  5213. */
  5214. if (z == last_zone) {
  5215. ties = 1;
  5216. continue;
  5217. }
  5218. size = get_uma_stats(kz, z, &allocs, &used,
  5219. &sleeps, &cachefree, &xdomain);
  5220. if (size > cur_size && size < last_size + ties)
  5221. {
  5222. cur_size = size;
  5223. cur_zone = z;
  5224. cur_keg = kz;
  5225. }
  5226. }
  5227. }
  5228. if (cur_zone == NULL)
  5229. break;
  5230. size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
  5231. &sleeps, &cachefree, &xdomain);
  5232. db_printf(fmt_entry, cur_zone->uz_name,
  5233. (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
  5234. (uintmax_t)allocs, (uintmax_t)sleeps,
  5235. (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
  5236. xdomain);
  5237. if (db_pager_quit)
  5238. return;
  5239. last_zone = cur_zone;
  5240. last_size = cur_size;
  5241. }
  5242. }
  5243. DB_SHOW_COMMAND_FLAGS(umacache, db_show_umacache, DB_CMD_MEMSAFE)
  5244. {
  5245. uma_zone_t z;
  5246. uint64_t allocs, frees;
  5247. long cachefree;
  5248. int i;
  5249. db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
  5250. "Requests", "Bucket");
  5251. LIST_FOREACH(z, &uma_cachezones, uz_link) {
  5252. uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
  5253. for (i = 0; i < vm_ndomains; i++)
  5254. cachefree += ZDOM_GET(z, i)->uzd_nitems;
  5255. db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
  5256. z->uz_name, (uintmax_t)z->uz_size,
  5257. (intmax_t)(allocs - frees), cachefree,
  5258. (uintmax_t)allocs, z->uz_bucket_size);
  5259. if (db_pager_quit)
  5260. return;
  5261. }
  5262. }
  5263. #endif /* DDB */