hugetlb.c 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Generic hugetlb support.
  4. * (C) Nadia Yvette Chambers, April 2004
  5. */
  6. #include <linux/list.h>
  7. #include <linux/init.h>
  8. #include <linux/mm.h>
  9. #include <linux/seq_file.h>
  10. #include <linux/highmem.h>
  11. #include <linux/mmu_notifier.h>
  12. #include <linux/nodemask.h>
  13. #include <linux/pagemap.h>
  14. #include <linux/mempolicy.h>
  15. #include <linux/compiler.h>
  16. #include <linux/cpumask.h>
  17. #include <linux/cpuset.h>
  18. #include <linux/mutex.h>
  19. #include <linux/memblock.h>
  20. #include <linux/minmax.h>
  21. #include <linux/slab.h>
  22. #include <linux/sched/mm.h>
  23. #include <linux/mmdebug.h>
  24. #include <linux/sched/signal.h>
  25. #include <linux/rmap.h>
  26. #include <linux/string_choices.h>
  27. #include <linux/string_helpers.h>
  28. #include <linux/swap.h>
  29. #include <linux/leafops.h>
  30. #include <linux/jhash.h>
  31. #include <linux/numa.h>
  32. #include <linux/llist.h>
  33. #include <linux/cma.h>
  34. #include <linux/migrate.h>
  35. #include <linux/nospec.h>
  36. #include <linux/delayacct.h>
  37. #include <linux/memory.h>
  38. #include <linux/mm_inline.h>
  39. #include <linux/padata.h>
  40. #include <linux/pgalloc.h>
  41. #include <asm/page.h>
  42. #include <asm/tlb.h>
  43. #include <asm/setup.h>
  44. #include <linux/io.h>
  45. #include <linux/node.h>
  46. #include <linux/page_owner.h>
  47. #include "internal.h"
  48. #include "hugetlb_vmemmap.h"
  49. #include "hugetlb_cma.h"
  50. #include "hugetlb_internal.h"
  51. #include <linux/page-isolation.h>
  52. int hugetlb_max_hstate __read_mostly;
  53. unsigned int default_hstate_idx;
  54. struct hstate hstates[HUGE_MAX_HSTATE];
  55. __initdata nodemask_t hugetlb_bootmem_nodes;
  56. __initdata struct list_head huge_boot_pages[MAX_NUMNODES];
  57. static unsigned long hstate_boot_nrinvalid[HUGE_MAX_HSTATE] __initdata;
  58. /*
  59. * Due to ordering constraints across the init code for various
  60. * architectures, hugetlb hstate cmdline parameters can't simply
  61. * be early_param. early_param might call the setup function
  62. * before valid hugetlb page sizes are determined, leading to
  63. * incorrect rejection of valid hugepagesz= options.
  64. *
  65. * So, record the parameters early and consume them whenever the
  66. * init code is ready for them, by calling hugetlb_parse_params().
  67. */
  68. /* one (hugepagesz=,hugepages=) pair per hstate, one default_hugepagesz */
  69. #define HUGE_MAX_CMDLINE_ARGS (2 * HUGE_MAX_HSTATE + 1)
  70. struct hugetlb_cmdline {
  71. char *val;
  72. int (*setup)(char *val);
  73. };
  74. /* for command line parsing */
  75. static struct hstate * __initdata parsed_hstate;
  76. static unsigned long __initdata default_hstate_max_huge_pages;
  77. static bool __initdata parsed_valid_hugepagesz = true;
  78. static bool __initdata parsed_default_hugepagesz;
  79. static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata;
  80. static unsigned long hugepage_allocation_threads __initdata;
  81. static char hstate_cmdline_buf[COMMAND_LINE_SIZE] __initdata;
  82. static int hstate_cmdline_index __initdata;
  83. static struct hugetlb_cmdline hugetlb_params[HUGE_MAX_CMDLINE_ARGS] __initdata;
  84. static int hugetlb_param_index __initdata;
  85. static __init int hugetlb_add_param(char *s, int (*setup)(char *val));
  86. static __init void hugetlb_parse_params(void);
  87. #define hugetlb_early_param(str, func) \
  88. static __init int func##args(char *s) \
  89. { \
  90. return hugetlb_add_param(s, func); \
  91. } \
  92. early_param(str, func##args)
  93. /*
  94. * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
  95. * free_huge_pages, and surplus_huge_pages.
  96. */
  97. __cacheline_aligned_in_smp DEFINE_SPINLOCK(hugetlb_lock);
  98. /*
  99. * Serializes faults on the same logical page. This is used to
  100. * prevent spurious OOMs when the hugepage pool is fully utilized.
  101. */
  102. static int num_fault_mutexes __ro_after_init;
  103. struct mutex *hugetlb_fault_mutex_table __ro_after_init;
  104. /* Forward declaration */
  105. static int hugetlb_acct_memory(struct hstate *h, long delta);
  106. static void hugetlb_vma_lock_free(struct vm_area_struct *vma);
  107. static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma);
  108. static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
  109. unsigned long start, unsigned long end, bool take_locks);
  110. static struct resv_map *vma_resv_map(struct vm_area_struct *vma);
  111. static inline bool subpool_is_free(struct hugepage_subpool *spool)
  112. {
  113. if (spool->count)
  114. return false;
  115. if (spool->max_hpages != -1)
  116. return spool->used_hpages == 0;
  117. if (spool->min_hpages != -1)
  118. return spool->rsv_hpages == spool->min_hpages;
  119. return true;
  120. }
  121. static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
  122. unsigned long irq_flags)
  123. {
  124. spin_unlock_irqrestore(&spool->lock, irq_flags);
  125. /* If no pages are used, and no other handles to the subpool
  126. * remain, give up any reservations based on minimum size and
  127. * free the subpool */
  128. if (subpool_is_free(spool)) {
  129. if (spool->min_hpages != -1)
  130. hugetlb_acct_memory(spool->hstate,
  131. -spool->min_hpages);
  132. kfree(spool);
  133. }
  134. }
  135. struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
  136. long min_hpages)
  137. {
  138. struct hugepage_subpool *spool;
  139. spool = kzalloc_obj(*spool);
  140. if (!spool)
  141. return NULL;
  142. spin_lock_init(&spool->lock);
  143. spool->count = 1;
  144. spool->max_hpages = max_hpages;
  145. spool->hstate = h;
  146. spool->min_hpages = min_hpages;
  147. if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
  148. kfree(spool);
  149. return NULL;
  150. }
  151. spool->rsv_hpages = min_hpages;
  152. return spool;
  153. }
  154. void hugepage_put_subpool(struct hugepage_subpool *spool)
  155. {
  156. unsigned long flags;
  157. spin_lock_irqsave(&spool->lock, flags);
  158. BUG_ON(!spool->count);
  159. spool->count--;
  160. unlock_or_release_subpool(spool, flags);
  161. }
  162. /*
  163. * Subpool accounting for allocating and reserving pages.
  164. * Return -ENOMEM if there are not enough resources to satisfy the
  165. * request. Otherwise, return the number of pages by which the
  166. * global pools must be adjusted (upward). The returned value may
  167. * only be different than the passed value (delta) in the case where
  168. * a subpool minimum size must be maintained.
  169. */
  170. static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
  171. long delta)
  172. {
  173. long ret = delta;
  174. if (!spool)
  175. return ret;
  176. spin_lock_irq(&spool->lock);
  177. if (spool->max_hpages != -1) { /* maximum size accounting */
  178. if ((spool->used_hpages + delta) <= spool->max_hpages)
  179. spool->used_hpages += delta;
  180. else {
  181. ret = -ENOMEM;
  182. goto unlock_ret;
  183. }
  184. }
  185. /* minimum size accounting */
  186. if (spool->min_hpages != -1 && spool->rsv_hpages) {
  187. if (delta > spool->rsv_hpages) {
  188. /*
  189. * Asking for more reserves than those already taken on
  190. * behalf of subpool. Return difference.
  191. */
  192. ret = delta - spool->rsv_hpages;
  193. spool->rsv_hpages = 0;
  194. } else {
  195. ret = 0; /* reserves already accounted for */
  196. spool->rsv_hpages -= delta;
  197. }
  198. }
  199. unlock_ret:
  200. spin_unlock_irq(&spool->lock);
  201. return ret;
  202. }
  203. /*
  204. * Subpool accounting for freeing and unreserving pages.
  205. * Return the number of global page reservations that must be dropped.
  206. * The return value may only be different than the passed value (delta)
  207. * in the case where a subpool minimum size must be maintained.
  208. */
  209. static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
  210. long delta)
  211. {
  212. long ret = delta;
  213. unsigned long flags;
  214. if (!spool)
  215. return delta;
  216. spin_lock_irqsave(&spool->lock, flags);
  217. if (spool->max_hpages != -1) /* maximum size accounting */
  218. spool->used_hpages -= delta;
  219. /* minimum size accounting */
  220. if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
  221. if (spool->rsv_hpages + delta <= spool->min_hpages)
  222. ret = 0;
  223. else
  224. ret = spool->rsv_hpages + delta - spool->min_hpages;
  225. spool->rsv_hpages += delta;
  226. if (spool->rsv_hpages > spool->min_hpages)
  227. spool->rsv_hpages = spool->min_hpages;
  228. }
  229. /*
  230. * If hugetlbfs_put_super couldn't free spool due to an outstanding
  231. * quota reference, free it now.
  232. */
  233. unlock_or_release_subpool(spool, flags);
  234. return ret;
  235. }
  236. static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
  237. {
  238. return subpool_inode(file_inode(vma->vm_file));
  239. }
  240. /*
  241. * hugetlb vma_lock helper routines
  242. */
  243. void hugetlb_vma_lock_read(struct vm_area_struct *vma)
  244. {
  245. if (__vma_shareable_lock(vma)) {
  246. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  247. down_read(&vma_lock->rw_sema);
  248. } else if (__vma_private_lock(vma)) {
  249. struct resv_map *resv_map = vma_resv_map(vma);
  250. down_read(&resv_map->rw_sema);
  251. }
  252. }
  253. void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
  254. {
  255. if (__vma_shareable_lock(vma)) {
  256. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  257. up_read(&vma_lock->rw_sema);
  258. } else if (__vma_private_lock(vma)) {
  259. struct resv_map *resv_map = vma_resv_map(vma);
  260. up_read(&resv_map->rw_sema);
  261. }
  262. }
  263. void hugetlb_vma_lock_write(struct vm_area_struct *vma)
  264. {
  265. if (__vma_shareable_lock(vma)) {
  266. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  267. down_write(&vma_lock->rw_sema);
  268. } else if (__vma_private_lock(vma)) {
  269. struct resv_map *resv_map = vma_resv_map(vma);
  270. down_write(&resv_map->rw_sema);
  271. }
  272. }
  273. void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
  274. {
  275. if (__vma_shareable_lock(vma)) {
  276. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  277. up_write(&vma_lock->rw_sema);
  278. } else if (__vma_private_lock(vma)) {
  279. struct resv_map *resv_map = vma_resv_map(vma);
  280. up_write(&resv_map->rw_sema);
  281. }
  282. }
  283. int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
  284. {
  285. if (__vma_shareable_lock(vma)) {
  286. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  287. return down_write_trylock(&vma_lock->rw_sema);
  288. } else if (__vma_private_lock(vma)) {
  289. struct resv_map *resv_map = vma_resv_map(vma);
  290. return down_write_trylock(&resv_map->rw_sema);
  291. }
  292. return 1;
  293. }
  294. void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
  295. {
  296. if (__vma_shareable_lock(vma)) {
  297. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  298. lockdep_assert_held(&vma_lock->rw_sema);
  299. } else if (__vma_private_lock(vma)) {
  300. struct resv_map *resv_map = vma_resv_map(vma);
  301. lockdep_assert_held(&resv_map->rw_sema);
  302. }
  303. }
  304. void hugetlb_vma_lock_release(struct kref *kref)
  305. {
  306. struct hugetlb_vma_lock *vma_lock = container_of(kref,
  307. struct hugetlb_vma_lock, refs);
  308. kfree(vma_lock);
  309. }
  310. static void __hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock *vma_lock)
  311. {
  312. struct vm_area_struct *vma = vma_lock->vma;
  313. /*
  314. * vma_lock structure may or not be released as a result of put,
  315. * it certainly will no longer be attached to vma so clear pointer.
  316. * Semaphore synchronizes access to vma_lock->vma field.
  317. */
  318. vma_lock->vma = NULL;
  319. vma->vm_private_data = NULL;
  320. up_write(&vma_lock->rw_sema);
  321. kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
  322. }
  323. static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma)
  324. {
  325. if (__vma_shareable_lock(vma)) {
  326. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  327. __hugetlb_vma_unlock_write_put(vma_lock);
  328. } else if (__vma_private_lock(vma)) {
  329. struct resv_map *resv_map = vma_resv_map(vma);
  330. /* no free for anon vmas, but still need to unlock */
  331. up_write(&resv_map->rw_sema);
  332. }
  333. }
  334. static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
  335. {
  336. /*
  337. * Only present in sharable vmas.
  338. */
  339. if (!vma || !__vma_shareable_lock(vma))
  340. return;
  341. if (vma->vm_private_data) {
  342. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  343. down_write(&vma_lock->rw_sema);
  344. __hugetlb_vma_unlock_write_put(vma_lock);
  345. }
  346. }
  347. /*
  348. * vma specific semaphore used for pmd sharing and fault/truncation
  349. * synchronization
  350. */
  351. int hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
  352. {
  353. struct hugetlb_vma_lock *vma_lock;
  354. /* Only establish in (flags) sharable vmas */
  355. if (!vma || !(vma->vm_flags & VM_MAYSHARE))
  356. return 0;
  357. /* Should never get here with non-NULL vm_private_data */
  358. if (vma->vm_private_data)
  359. return -EINVAL;
  360. vma_lock = kmalloc_obj(*vma_lock);
  361. if (!vma_lock) {
  362. /*
  363. * If we can not allocate structure, then vma can not
  364. * participate in pmd sharing. This is only a possible
  365. * performance enhancement and memory saving issue.
  366. * However, the lock is also used to synchronize page
  367. * faults with truncation. If the lock is not present,
  368. * unlikely races could leave pages in a file past i_size
  369. * until the file is removed. Warn in the unlikely case of
  370. * allocation failure.
  371. */
  372. pr_warn_once("HugeTLB: unable to allocate vma specific lock\n");
  373. return -EINVAL;
  374. }
  375. kref_init(&vma_lock->refs);
  376. init_rwsem(&vma_lock->rw_sema);
  377. vma_lock->vma = vma;
  378. vma->vm_private_data = vma_lock;
  379. return 0;
  380. }
  381. /* Helper that removes a struct file_region from the resv_map cache and returns
  382. * it for use.
  383. */
  384. static struct file_region *
  385. get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
  386. {
  387. struct file_region *nrg;
  388. VM_BUG_ON(resv->region_cache_count <= 0);
  389. resv->region_cache_count--;
  390. nrg = list_first_entry(&resv->region_cache, struct file_region, link);
  391. list_del(&nrg->link);
  392. nrg->from = from;
  393. nrg->to = to;
  394. return nrg;
  395. }
  396. static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
  397. struct file_region *rg)
  398. {
  399. #ifdef CONFIG_CGROUP_HUGETLB
  400. nrg->reservation_counter = rg->reservation_counter;
  401. nrg->css = rg->css;
  402. if (rg->css)
  403. css_get(rg->css);
  404. #endif
  405. }
  406. /* Helper that records hugetlb_cgroup uncharge info. */
  407. static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
  408. struct hstate *h,
  409. struct resv_map *resv,
  410. struct file_region *nrg)
  411. {
  412. #ifdef CONFIG_CGROUP_HUGETLB
  413. if (h_cg) {
  414. nrg->reservation_counter =
  415. &h_cg->rsvd_hugepage[hstate_index(h)];
  416. nrg->css = &h_cg->css;
  417. /*
  418. * The caller will hold exactly one h_cg->css reference for the
  419. * whole contiguous reservation region. But this area might be
  420. * scattered when there are already some file_regions reside in
  421. * it. As a result, many file_regions may share only one css
  422. * reference. In order to ensure that one file_region must hold
  423. * exactly one h_cg->css reference, we should do css_get for
  424. * each file_region and leave the reference held by caller
  425. * untouched.
  426. */
  427. css_get(&h_cg->css);
  428. if (!resv->pages_per_hpage)
  429. resv->pages_per_hpage = pages_per_huge_page(h);
  430. /* pages_per_hpage should be the same for all entries in
  431. * a resv_map.
  432. */
  433. VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
  434. } else {
  435. nrg->reservation_counter = NULL;
  436. nrg->css = NULL;
  437. }
  438. #endif
  439. }
  440. static void put_uncharge_info(struct file_region *rg)
  441. {
  442. #ifdef CONFIG_CGROUP_HUGETLB
  443. if (rg->css)
  444. css_put(rg->css);
  445. #endif
  446. }
  447. static bool has_same_uncharge_info(struct file_region *rg,
  448. struct file_region *org)
  449. {
  450. #ifdef CONFIG_CGROUP_HUGETLB
  451. return rg->reservation_counter == org->reservation_counter &&
  452. rg->css == org->css;
  453. #else
  454. return true;
  455. #endif
  456. }
  457. static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
  458. {
  459. struct file_region *nrg, *prg;
  460. prg = list_prev_entry(rg, link);
  461. if (&prg->link != &resv->regions && prg->to == rg->from &&
  462. has_same_uncharge_info(prg, rg)) {
  463. prg->to = rg->to;
  464. list_del(&rg->link);
  465. put_uncharge_info(rg);
  466. kfree(rg);
  467. rg = prg;
  468. }
  469. nrg = list_next_entry(rg, link);
  470. if (&nrg->link != &resv->regions && nrg->from == rg->to &&
  471. has_same_uncharge_info(nrg, rg)) {
  472. nrg->from = rg->from;
  473. list_del(&rg->link);
  474. put_uncharge_info(rg);
  475. kfree(rg);
  476. }
  477. }
  478. static inline long
  479. hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
  480. long to, struct hstate *h, struct hugetlb_cgroup *cg,
  481. long *regions_needed)
  482. {
  483. struct file_region *nrg;
  484. if (!regions_needed) {
  485. nrg = get_file_region_entry_from_cache(map, from, to);
  486. record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
  487. list_add(&nrg->link, rg);
  488. coalesce_file_region(map, nrg);
  489. } else {
  490. *regions_needed += 1;
  491. }
  492. return to - from;
  493. }
  494. /*
  495. * Must be called with resv->lock held.
  496. *
  497. * Calling this with regions_needed != NULL will count the number of pages
  498. * to be added but will not modify the linked list. And regions_needed will
  499. * indicate the number of file_regions needed in the cache to carry out to add
  500. * the regions for this range.
  501. */
  502. static long add_reservation_in_range(struct resv_map *resv, long f, long t,
  503. struct hugetlb_cgroup *h_cg,
  504. struct hstate *h, long *regions_needed)
  505. {
  506. long add = 0;
  507. struct list_head *head = &resv->regions;
  508. long last_accounted_offset = f;
  509. struct file_region *iter, *trg = NULL;
  510. struct list_head *rg = NULL;
  511. if (regions_needed)
  512. *regions_needed = 0;
  513. /* In this loop, we essentially handle an entry for the range
  514. * [last_accounted_offset, iter->from), at every iteration, with some
  515. * bounds checking.
  516. */
  517. list_for_each_entry_safe(iter, trg, head, link) {
  518. /* Skip irrelevant regions that start before our range. */
  519. if (iter->from < f) {
  520. /* If this region ends after the last accounted offset,
  521. * then we need to update last_accounted_offset.
  522. */
  523. if (iter->to > last_accounted_offset)
  524. last_accounted_offset = iter->to;
  525. continue;
  526. }
  527. /* When we find a region that starts beyond our range, we've
  528. * finished.
  529. */
  530. if (iter->from >= t) {
  531. rg = iter->link.prev;
  532. break;
  533. }
  534. /* Add an entry for last_accounted_offset -> iter->from, and
  535. * update last_accounted_offset.
  536. */
  537. if (iter->from > last_accounted_offset)
  538. add += hugetlb_resv_map_add(resv, iter->link.prev,
  539. last_accounted_offset,
  540. iter->from, h, h_cg,
  541. regions_needed);
  542. last_accounted_offset = iter->to;
  543. }
  544. /* Handle the case where our range extends beyond
  545. * last_accounted_offset.
  546. */
  547. if (!rg)
  548. rg = head->prev;
  549. if (last_accounted_offset < t)
  550. add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
  551. t, h, h_cg, regions_needed);
  552. return add;
  553. }
  554. /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
  555. */
  556. static int allocate_file_region_entries(struct resv_map *resv,
  557. int regions_needed)
  558. __must_hold(&resv->lock)
  559. {
  560. LIST_HEAD(allocated_regions);
  561. int to_allocate = 0, i = 0;
  562. struct file_region *trg = NULL, *rg = NULL;
  563. VM_BUG_ON(regions_needed < 0);
  564. /*
  565. * Check for sufficient descriptors in the cache to accommodate
  566. * the number of in progress add operations plus regions_needed.
  567. *
  568. * This is a while loop because when we drop the lock, some other call
  569. * to region_add or region_del may have consumed some region_entries,
  570. * so we keep looping here until we finally have enough entries for
  571. * (adds_in_progress + regions_needed).
  572. */
  573. while (resv->region_cache_count <
  574. (resv->adds_in_progress + regions_needed)) {
  575. to_allocate = resv->adds_in_progress + regions_needed -
  576. resv->region_cache_count;
  577. /* At this point, we should have enough entries in the cache
  578. * for all the existing adds_in_progress. We should only be
  579. * needing to allocate for regions_needed.
  580. */
  581. VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
  582. spin_unlock(&resv->lock);
  583. for (i = 0; i < to_allocate; i++) {
  584. trg = kmalloc_obj(*trg);
  585. if (!trg)
  586. goto out_of_memory;
  587. list_add(&trg->link, &allocated_regions);
  588. }
  589. spin_lock(&resv->lock);
  590. list_splice(&allocated_regions, &resv->region_cache);
  591. resv->region_cache_count += to_allocate;
  592. }
  593. return 0;
  594. out_of_memory:
  595. list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
  596. list_del(&rg->link);
  597. kfree(rg);
  598. }
  599. return -ENOMEM;
  600. }
  601. /*
  602. * Add the huge page range represented by [f, t) to the reserve
  603. * map. Regions will be taken from the cache to fill in this range.
  604. * Sufficient regions should exist in the cache due to the previous
  605. * call to region_chg with the same range, but in some cases the cache will not
  606. * have sufficient entries due to races with other code doing region_add or
  607. * region_del. The extra needed entries will be allocated.
  608. *
  609. * regions_needed is the out value provided by a previous call to region_chg.
  610. *
  611. * Return the number of new huge pages added to the map. This number is greater
  612. * than or equal to zero. If file_region entries needed to be allocated for
  613. * this operation and we were not able to allocate, it returns -ENOMEM.
  614. * region_add of regions of length 1 never allocate file_regions and cannot
  615. * fail; region_chg will always allocate at least 1 entry and a region_add for
  616. * 1 page will only require at most 1 entry.
  617. */
  618. static long region_add(struct resv_map *resv, long f, long t,
  619. long in_regions_needed, struct hstate *h,
  620. struct hugetlb_cgroup *h_cg)
  621. {
  622. long add = 0, actual_regions_needed = 0;
  623. spin_lock(&resv->lock);
  624. retry:
  625. /* Count how many regions are actually needed to execute this add. */
  626. add_reservation_in_range(resv, f, t, NULL, NULL,
  627. &actual_regions_needed);
  628. /*
  629. * Check for sufficient descriptors in the cache to accommodate
  630. * this add operation. Note that actual_regions_needed may be greater
  631. * than in_regions_needed, as the resv_map may have been modified since
  632. * the region_chg call. In this case, we need to make sure that we
  633. * allocate extra entries, such that we have enough for all the
  634. * existing adds_in_progress, plus the excess needed for this
  635. * operation.
  636. */
  637. if (actual_regions_needed > in_regions_needed &&
  638. resv->region_cache_count <
  639. resv->adds_in_progress +
  640. (actual_regions_needed - in_regions_needed)) {
  641. /* region_add operation of range 1 should never need to
  642. * allocate file_region entries.
  643. */
  644. VM_BUG_ON(t - f <= 1);
  645. if (allocate_file_region_entries(
  646. resv, actual_regions_needed - in_regions_needed)) {
  647. return -ENOMEM;
  648. }
  649. goto retry;
  650. }
  651. add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
  652. resv->adds_in_progress -= in_regions_needed;
  653. spin_unlock(&resv->lock);
  654. return add;
  655. }
  656. /*
  657. * Examine the existing reserve map and determine how many
  658. * huge pages in the specified range [f, t) are NOT currently
  659. * represented. This routine is called before a subsequent
  660. * call to region_add that will actually modify the reserve
  661. * map to add the specified range [f, t). region_chg does
  662. * not change the number of huge pages represented by the
  663. * map. A number of new file_region structures is added to the cache as a
  664. * placeholder, for the subsequent region_add call to use. At least 1
  665. * file_region structure is added.
  666. *
  667. * out_regions_needed is the number of regions added to the
  668. * resv->adds_in_progress. This value needs to be provided to a follow up call
  669. * to region_add or region_abort for proper accounting.
  670. *
  671. * Returns the number of huge pages that need to be added to the existing
  672. * reservation map for the range [f, t). This number is greater or equal to
  673. * zero. -ENOMEM is returned if a new file_region structure or cache entry
  674. * is needed and can not be allocated.
  675. */
  676. static long region_chg(struct resv_map *resv, long f, long t,
  677. long *out_regions_needed)
  678. {
  679. long chg = 0;
  680. spin_lock(&resv->lock);
  681. /* Count how many hugepages in this range are NOT represented. */
  682. chg = add_reservation_in_range(resv, f, t, NULL, NULL,
  683. out_regions_needed);
  684. if (*out_regions_needed == 0)
  685. *out_regions_needed = 1;
  686. if (allocate_file_region_entries(resv, *out_regions_needed))
  687. return -ENOMEM;
  688. resv->adds_in_progress += *out_regions_needed;
  689. spin_unlock(&resv->lock);
  690. return chg;
  691. }
  692. /*
  693. * Abort the in progress add operation. The adds_in_progress field
  694. * of the resv_map keeps track of the operations in progress between
  695. * calls to region_chg and region_add. Operations are sometimes
  696. * aborted after the call to region_chg. In such cases, region_abort
  697. * is called to decrement the adds_in_progress counter. regions_needed
  698. * is the value returned by the region_chg call, it is used to decrement
  699. * the adds_in_progress counter.
  700. *
  701. * NOTE: The range arguments [f, t) are not needed or used in this
  702. * routine. They are kept to make reading the calling code easier as
  703. * arguments will match the associated region_chg call.
  704. */
  705. static void region_abort(struct resv_map *resv, long f, long t,
  706. long regions_needed)
  707. {
  708. spin_lock(&resv->lock);
  709. VM_BUG_ON(!resv->region_cache_count);
  710. resv->adds_in_progress -= regions_needed;
  711. spin_unlock(&resv->lock);
  712. }
  713. /*
  714. * Delete the specified range [f, t) from the reserve map. If the
  715. * t parameter is LONG_MAX, this indicates that ALL regions after f
  716. * should be deleted. Locate the regions which intersect [f, t)
  717. * and either trim, delete or split the existing regions.
  718. *
  719. * Returns the number of huge pages deleted from the reserve map.
  720. * In the normal case, the return value is zero or more. In the
  721. * case where a region must be split, a new region descriptor must
  722. * be allocated. If the allocation fails, -ENOMEM will be returned.
  723. * NOTE: If the parameter t == LONG_MAX, then we will never split
  724. * a region and possibly return -ENOMEM. Callers specifying
  725. * t == LONG_MAX do not need to check for -ENOMEM error.
  726. */
  727. static long region_del(struct resv_map *resv, long f, long t)
  728. {
  729. struct list_head *head = &resv->regions;
  730. struct file_region *rg, *trg;
  731. struct file_region *nrg = NULL;
  732. long del = 0;
  733. retry:
  734. spin_lock(&resv->lock);
  735. list_for_each_entry_safe(rg, trg, head, link) {
  736. /*
  737. * Skip regions before the range to be deleted. file_region
  738. * ranges are normally of the form [from, to). However, there
  739. * may be a "placeholder" entry in the map which is of the form
  740. * (from, to) with from == to. Check for placeholder entries
  741. * at the beginning of the range to be deleted.
  742. */
  743. if (rg->to <= f && (rg->to != rg->from || rg->to != f))
  744. continue;
  745. if (rg->from >= t)
  746. break;
  747. if (f > rg->from && t < rg->to) { /* Must split region */
  748. /*
  749. * Check for an entry in the cache before dropping
  750. * lock and attempting allocation.
  751. */
  752. if (!nrg &&
  753. resv->region_cache_count > resv->adds_in_progress) {
  754. nrg = list_first_entry(&resv->region_cache,
  755. struct file_region,
  756. link);
  757. list_del(&nrg->link);
  758. resv->region_cache_count--;
  759. }
  760. if (!nrg) {
  761. spin_unlock(&resv->lock);
  762. nrg = kmalloc_obj(*nrg);
  763. if (!nrg)
  764. return -ENOMEM;
  765. goto retry;
  766. }
  767. del += t - f;
  768. hugetlb_cgroup_uncharge_file_region(
  769. resv, rg, t - f, false);
  770. /* New entry for end of split region */
  771. nrg->from = t;
  772. nrg->to = rg->to;
  773. copy_hugetlb_cgroup_uncharge_info(nrg, rg);
  774. INIT_LIST_HEAD(&nrg->link);
  775. /* Original entry is trimmed */
  776. rg->to = f;
  777. list_add(&nrg->link, &rg->link);
  778. nrg = NULL;
  779. break;
  780. }
  781. if (f <= rg->from && t >= rg->to) { /* Remove entire region */
  782. del += rg->to - rg->from;
  783. hugetlb_cgroup_uncharge_file_region(resv, rg,
  784. rg->to - rg->from, true);
  785. list_del(&rg->link);
  786. kfree(rg);
  787. continue;
  788. }
  789. if (f <= rg->from) { /* Trim beginning of region */
  790. hugetlb_cgroup_uncharge_file_region(resv, rg,
  791. t - rg->from, false);
  792. del += t - rg->from;
  793. rg->from = t;
  794. } else { /* Trim end of region */
  795. hugetlb_cgroup_uncharge_file_region(resv, rg,
  796. rg->to - f, false);
  797. del += rg->to - f;
  798. rg->to = f;
  799. }
  800. }
  801. spin_unlock(&resv->lock);
  802. kfree(nrg);
  803. return del;
  804. }
  805. /*
  806. * A rare out of memory error was encountered which prevented removal of
  807. * the reserve map region for a page. The huge page itself was free'ed
  808. * and removed from the page cache. This routine will adjust the subpool
  809. * usage count, and the global reserve count if needed. By incrementing
  810. * these counts, the reserve map entry which could not be deleted will
  811. * appear as a "reserved" entry instead of simply dangling with incorrect
  812. * counts.
  813. */
  814. void hugetlb_fix_reserve_counts(struct inode *inode)
  815. {
  816. struct hugepage_subpool *spool = subpool_inode(inode);
  817. long rsv_adjust;
  818. bool reserved = false;
  819. rsv_adjust = hugepage_subpool_get_pages(spool, 1);
  820. if (rsv_adjust > 0) {
  821. struct hstate *h = hstate_inode(inode);
  822. if (!hugetlb_acct_memory(h, 1))
  823. reserved = true;
  824. } else if (!rsv_adjust) {
  825. reserved = true;
  826. }
  827. if (!reserved)
  828. pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
  829. }
  830. /*
  831. * Count and return the number of huge pages in the reserve map
  832. * that intersect with the range [f, t).
  833. */
  834. static long region_count(struct resv_map *resv, long f, long t)
  835. {
  836. struct list_head *head = &resv->regions;
  837. struct file_region *rg;
  838. long chg = 0;
  839. spin_lock(&resv->lock);
  840. /* Locate each segment we overlap with, and count that overlap. */
  841. list_for_each_entry(rg, head, link) {
  842. long seg_from;
  843. long seg_to;
  844. if (rg->to <= f)
  845. continue;
  846. if (rg->from >= t)
  847. break;
  848. seg_from = max(rg->from, f);
  849. seg_to = min(rg->to, t);
  850. chg += seg_to - seg_from;
  851. }
  852. spin_unlock(&resv->lock);
  853. return chg;
  854. }
  855. /*
  856. * Convert the address within this vma to the page offset within
  857. * the mapping, huge page units here.
  858. */
  859. static pgoff_t vma_hugecache_offset(struct hstate *h,
  860. struct vm_area_struct *vma, unsigned long address)
  861. {
  862. return ((address - vma->vm_start) >> huge_page_shift(h)) +
  863. (vma->vm_pgoff >> huge_page_order(h));
  864. }
  865. /**
  866. * vma_kernel_pagesize - Page size granularity for this VMA.
  867. * @vma: The user mapping.
  868. *
  869. * Folios in this VMA will be aligned to, and at least the size of the
  870. * number of bytes returned by this function.
  871. *
  872. * Return: The default size of the folios allocated when backing a VMA.
  873. */
  874. unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
  875. {
  876. if (vma->vm_ops && vma->vm_ops->pagesize)
  877. return vma->vm_ops->pagesize(vma);
  878. return PAGE_SIZE;
  879. }
  880. EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
  881. /*
  882. * Return the page size being used by the MMU to back a VMA. In the majority
  883. * of cases, the page size used by the kernel matches the MMU size. On
  884. * architectures where it differs, an architecture-specific 'strong'
  885. * version of this symbol is required.
  886. */
  887. __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
  888. {
  889. return vma_kernel_pagesize(vma);
  890. }
  891. /*
  892. * Flags for MAP_PRIVATE reservations. These are stored in the bottom
  893. * bits of the reservation map pointer, which are always clear due to
  894. * alignment.
  895. */
  896. #define HPAGE_RESV_OWNER (1UL << 0)
  897. #define HPAGE_RESV_UNMAPPED (1UL << 1)
  898. #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
  899. /*
  900. * These helpers are used to track how many pages are reserved for
  901. * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
  902. * is guaranteed to have their future faults succeed.
  903. *
  904. * With the exception of hugetlb_dup_vma_private() which is called at fork(),
  905. * the reserve counters are updated with the hugetlb_lock held. It is safe
  906. * to reset the VMA at fork() time as it is not in use yet and there is no
  907. * chance of the global counters getting corrupted as a result of the values.
  908. *
  909. * The private mapping reservation is represented in a subtly different
  910. * manner to a shared mapping. A shared mapping has a region map associated
  911. * with the underlying file, this region map represents the backing file
  912. * pages which have ever had a reservation assigned which this persists even
  913. * after the page is instantiated. A private mapping has a region map
  914. * associated with the original mmap which is attached to all VMAs which
  915. * reference it, this region map represents those offsets which have consumed
  916. * reservation ie. where pages have been instantiated.
  917. */
  918. static unsigned long get_vma_private_data(struct vm_area_struct *vma)
  919. {
  920. return (unsigned long)vma->vm_private_data;
  921. }
  922. static void set_vma_private_data(struct vm_area_struct *vma,
  923. unsigned long value)
  924. {
  925. vma->vm_private_data = (void *)value;
  926. }
  927. static void
  928. resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
  929. struct hugetlb_cgroup *h_cg,
  930. struct hstate *h)
  931. {
  932. #ifdef CONFIG_CGROUP_HUGETLB
  933. if (!h_cg || !h) {
  934. resv_map->reservation_counter = NULL;
  935. resv_map->pages_per_hpage = 0;
  936. resv_map->css = NULL;
  937. } else {
  938. resv_map->reservation_counter =
  939. &h_cg->rsvd_hugepage[hstate_index(h)];
  940. resv_map->pages_per_hpage = pages_per_huge_page(h);
  941. resv_map->css = &h_cg->css;
  942. }
  943. #endif
  944. }
  945. struct resv_map *resv_map_alloc(void)
  946. {
  947. struct resv_map *resv_map = kmalloc_obj(*resv_map);
  948. struct file_region *rg = kmalloc_obj(*rg);
  949. if (!resv_map || !rg) {
  950. kfree(resv_map);
  951. kfree(rg);
  952. return NULL;
  953. }
  954. kref_init(&resv_map->refs);
  955. spin_lock_init(&resv_map->lock);
  956. INIT_LIST_HEAD(&resv_map->regions);
  957. init_rwsem(&resv_map->rw_sema);
  958. resv_map->adds_in_progress = 0;
  959. /*
  960. * Initialize these to 0. On shared mappings, 0's here indicate these
  961. * fields don't do cgroup accounting. On private mappings, these will be
  962. * re-initialized to the proper values, to indicate that hugetlb cgroup
  963. * reservations are to be un-charged from here.
  964. */
  965. resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
  966. INIT_LIST_HEAD(&resv_map->region_cache);
  967. list_add(&rg->link, &resv_map->region_cache);
  968. resv_map->region_cache_count = 1;
  969. return resv_map;
  970. }
  971. void resv_map_release(struct kref *ref)
  972. {
  973. struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
  974. struct list_head *head = &resv_map->region_cache;
  975. struct file_region *rg, *trg;
  976. /* Clear out any active regions before we release the map. */
  977. region_del(resv_map, 0, LONG_MAX);
  978. /* ... and any entries left in the cache */
  979. list_for_each_entry_safe(rg, trg, head, link) {
  980. list_del(&rg->link);
  981. kfree(rg);
  982. }
  983. VM_BUG_ON(resv_map->adds_in_progress);
  984. kfree(resv_map);
  985. }
  986. static inline struct resv_map *inode_resv_map(struct inode *inode)
  987. {
  988. /*
  989. * At inode evict time, i_mapping may not point to the original
  990. * address space within the inode. This original address space
  991. * contains the pointer to the resv_map. So, always use the
  992. * address space embedded within the inode.
  993. * The VERY common case is inode->mapping == &inode->i_data but,
  994. * this may not be true for device special inodes.
  995. */
  996. return (struct resv_map *)(&inode->i_data)->i_private_data;
  997. }
  998. static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
  999. {
  1000. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  1001. if (vma->vm_flags & VM_MAYSHARE) {
  1002. struct address_space *mapping = vma->vm_file->f_mapping;
  1003. struct inode *inode = mapping->host;
  1004. return inode_resv_map(inode);
  1005. } else {
  1006. return (struct resv_map *)(get_vma_private_data(vma) &
  1007. ~HPAGE_RESV_MASK);
  1008. }
  1009. }
  1010. static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
  1011. {
  1012. VM_WARN_ON_ONCE_VMA(!is_vm_hugetlb_page(vma), vma);
  1013. VM_WARN_ON_ONCE_VMA(vma->vm_flags & VM_MAYSHARE, vma);
  1014. set_vma_private_data(vma, get_vma_private_data(vma) | flags);
  1015. }
  1016. static void set_vma_desc_resv_map(struct vm_area_desc *desc, struct resv_map *map)
  1017. {
  1018. VM_WARN_ON_ONCE(!is_vma_hugetlb_flags(&desc->vma_flags));
  1019. VM_WARN_ON_ONCE(vma_desc_test_flags(desc, VMA_MAYSHARE_BIT));
  1020. desc->private_data = map;
  1021. }
  1022. static void set_vma_desc_resv_flags(struct vm_area_desc *desc, unsigned long flags)
  1023. {
  1024. VM_WARN_ON_ONCE(!is_vma_hugetlb_flags(&desc->vma_flags));
  1025. VM_WARN_ON_ONCE(vma_desc_test_flags(desc, VMA_MAYSHARE_BIT));
  1026. desc->private_data = (void *)((unsigned long)desc->private_data | flags);
  1027. }
  1028. static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
  1029. {
  1030. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  1031. return (get_vma_private_data(vma) & flag) != 0;
  1032. }
  1033. static bool is_vma_desc_resv_set(struct vm_area_desc *desc, unsigned long flag)
  1034. {
  1035. VM_WARN_ON_ONCE(!is_vma_hugetlb_flags(&desc->vma_flags));
  1036. return ((unsigned long)desc->private_data) & flag;
  1037. }
  1038. bool __vma_private_lock(struct vm_area_struct *vma)
  1039. {
  1040. return !(vma->vm_flags & VM_MAYSHARE) &&
  1041. get_vma_private_data(vma) & ~HPAGE_RESV_MASK &&
  1042. is_vma_resv_set(vma, HPAGE_RESV_OWNER);
  1043. }
  1044. void hugetlb_dup_vma_private(struct vm_area_struct *vma)
  1045. {
  1046. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  1047. /*
  1048. * Clear vm_private_data
  1049. * - For shared mappings this is a per-vma semaphore that may be
  1050. * allocated in a subsequent call to hugetlb_vm_op_open.
  1051. * Before clearing, make sure pointer is not associated with vma
  1052. * as this will leak the structure. This is the case when called
  1053. * via clear_vma_resv_huge_pages() and hugetlb_vm_op_open has already
  1054. * been called to allocate a new structure.
  1055. * - For MAP_PRIVATE mappings, this is the reserve map which does
  1056. * not apply to children. Faults generated by the children are
  1057. * not guaranteed to succeed, even if read-only.
  1058. */
  1059. if (vma->vm_flags & VM_MAYSHARE) {
  1060. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  1061. if (vma_lock && vma_lock->vma != vma)
  1062. vma->vm_private_data = NULL;
  1063. } else {
  1064. vma->vm_private_data = NULL;
  1065. }
  1066. }
  1067. /*
  1068. * Reset and decrement one ref on hugepage private reservation.
  1069. * Called with mm->mmap_lock writer semaphore held.
  1070. * This function should be only used by mremap and operate on
  1071. * same sized vma. It should never come here with last ref on the
  1072. * reservation.
  1073. */
  1074. void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
  1075. {
  1076. /*
  1077. * Clear the old hugetlb private page reservation.
  1078. * It has already been transferred to new_vma.
  1079. *
  1080. * During a mremap() operation of a hugetlb vma we call move_vma()
  1081. * which copies vma into new_vma and unmaps vma. After the copy
  1082. * operation both new_vma and vma share a reference to the resv_map
  1083. * struct, and at that point vma is about to be unmapped. We don't
  1084. * want to return the reservation to the pool at unmap of vma because
  1085. * the reservation still lives on in new_vma, so simply decrement the
  1086. * ref here and remove the resv_map reference from this vma.
  1087. */
  1088. struct resv_map *reservations = vma_resv_map(vma);
  1089. if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
  1090. resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
  1091. kref_put(&reservations->refs, resv_map_release);
  1092. }
  1093. hugetlb_dup_vma_private(vma);
  1094. }
  1095. static void enqueue_hugetlb_folio(struct hstate *h, struct folio *folio)
  1096. {
  1097. int nid = folio_nid(folio);
  1098. lockdep_assert_held(&hugetlb_lock);
  1099. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  1100. list_move(&folio->lru, &h->hugepage_freelists[nid]);
  1101. h->free_huge_pages++;
  1102. h->free_huge_pages_node[nid]++;
  1103. folio_set_hugetlb_freed(folio);
  1104. }
  1105. static struct folio *dequeue_hugetlb_folio_node_exact(struct hstate *h,
  1106. int nid)
  1107. {
  1108. struct folio *folio;
  1109. bool pin = !!(current->flags & PF_MEMALLOC_PIN);
  1110. lockdep_assert_held(&hugetlb_lock);
  1111. list_for_each_entry(folio, &h->hugepage_freelists[nid], lru) {
  1112. if (pin && !folio_is_longterm_pinnable(folio))
  1113. continue;
  1114. if (folio_test_hwpoison(folio))
  1115. continue;
  1116. if (is_migrate_isolate_page(&folio->page))
  1117. continue;
  1118. list_move(&folio->lru, &h->hugepage_activelist);
  1119. folio_ref_unfreeze(folio, 1);
  1120. folio_clear_hugetlb_freed(folio);
  1121. h->free_huge_pages--;
  1122. h->free_huge_pages_node[nid]--;
  1123. return folio;
  1124. }
  1125. return NULL;
  1126. }
  1127. static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_mask,
  1128. int nid, nodemask_t *nmask)
  1129. {
  1130. unsigned int cpuset_mems_cookie;
  1131. struct zonelist *zonelist;
  1132. struct zone *zone;
  1133. struct zoneref *z;
  1134. int node = NUMA_NO_NODE;
  1135. /* 'nid' should not be NUMA_NO_NODE. Try to catch any misuse of it and rectifiy. */
  1136. if (nid == NUMA_NO_NODE)
  1137. nid = numa_node_id();
  1138. zonelist = node_zonelist(nid, gfp_mask);
  1139. retry_cpuset:
  1140. cpuset_mems_cookie = read_mems_allowed_begin();
  1141. for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
  1142. struct folio *folio;
  1143. if (!cpuset_zone_allowed(zone, gfp_mask))
  1144. continue;
  1145. /*
  1146. * no need to ask again on the same node. Pool is node rather than
  1147. * zone aware
  1148. */
  1149. if (zone_to_nid(zone) == node)
  1150. continue;
  1151. node = zone_to_nid(zone);
  1152. folio = dequeue_hugetlb_folio_node_exact(h, node);
  1153. if (folio)
  1154. return folio;
  1155. }
  1156. if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
  1157. goto retry_cpuset;
  1158. return NULL;
  1159. }
  1160. static unsigned long available_huge_pages(struct hstate *h)
  1161. {
  1162. return h->free_huge_pages - h->resv_huge_pages;
  1163. }
  1164. static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
  1165. struct vm_area_struct *vma,
  1166. unsigned long address, long gbl_chg)
  1167. {
  1168. struct folio *folio = NULL;
  1169. struct mempolicy *mpol;
  1170. gfp_t gfp_mask;
  1171. nodemask_t *nodemask;
  1172. int nid;
  1173. /*
  1174. * gbl_chg==1 means the allocation requires a new page that was not
  1175. * reserved before. Making sure there's at least one free page.
  1176. */
  1177. if (gbl_chg && !available_huge_pages(h))
  1178. goto err;
  1179. gfp_mask = htlb_alloc_mask(h);
  1180. nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
  1181. if (mpol_is_preferred_many(mpol)) {
  1182. folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
  1183. nid, nodemask);
  1184. /* Fallback to all nodes if page==NULL */
  1185. nodemask = NULL;
  1186. }
  1187. if (!folio)
  1188. folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
  1189. nid, nodemask);
  1190. mpol_cond_put(mpol);
  1191. return folio;
  1192. err:
  1193. return NULL;
  1194. }
  1195. #if defined(CONFIG_ARCH_HAS_GIGANTIC_PAGE) && defined(CONFIG_CONTIG_ALLOC)
  1196. static struct folio *alloc_gigantic_frozen_folio(int order, gfp_t gfp_mask,
  1197. int nid, nodemask_t *nodemask)
  1198. {
  1199. struct folio *folio;
  1200. folio = hugetlb_cma_alloc_frozen_folio(order, gfp_mask, nid, nodemask);
  1201. if (folio)
  1202. return folio;
  1203. if (hugetlb_cma_exclusive_alloc())
  1204. return NULL;
  1205. folio = (struct folio *)alloc_contig_frozen_pages(1 << order, gfp_mask,
  1206. nid, nodemask);
  1207. return folio;
  1208. }
  1209. #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE || !CONFIG_CONTIG_ALLOC */
  1210. static struct folio *alloc_gigantic_frozen_folio(int order, gfp_t gfp_mask, int nid,
  1211. nodemask_t *nodemask)
  1212. {
  1213. return NULL;
  1214. }
  1215. #endif
  1216. /*
  1217. * Remove hugetlb folio from lists.
  1218. * If vmemmap exists for the folio, clear the hugetlb flag so that the
  1219. * folio appears as just a compound page. Otherwise, wait until after
  1220. * allocating vmemmap to clear the flag.
  1221. *
  1222. * Must be called with hugetlb lock held.
  1223. */
  1224. void remove_hugetlb_folio(struct hstate *h, struct folio *folio,
  1225. bool adjust_surplus)
  1226. {
  1227. int nid = folio_nid(folio);
  1228. VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio(folio), folio);
  1229. VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio_rsvd(folio), folio);
  1230. lockdep_assert_held(&hugetlb_lock);
  1231. if (hstate_is_gigantic_no_runtime(h))
  1232. return;
  1233. list_del(&folio->lru);
  1234. if (folio_test_hugetlb_freed(folio)) {
  1235. folio_clear_hugetlb_freed(folio);
  1236. h->free_huge_pages--;
  1237. h->free_huge_pages_node[nid]--;
  1238. }
  1239. if (adjust_surplus) {
  1240. h->surplus_huge_pages--;
  1241. h->surplus_huge_pages_node[nid]--;
  1242. }
  1243. /*
  1244. * We can only clear the hugetlb flag after allocating vmemmap
  1245. * pages. Otherwise, someone (memory error handling) may try to write
  1246. * to tail struct pages.
  1247. */
  1248. if (!folio_test_hugetlb_vmemmap_optimized(folio))
  1249. __folio_clear_hugetlb(folio);
  1250. h->nr_huge_pages--;
  1251. h->nr_huge_pages_node[nid]--;
  1252. }
  1253. void add_hugetlb_folio(struct hstate *h, struct folio *folio,
  1254. bool adjust_surplus)
  1255. {
  1256. int nid = folio_nid(folio);
  1257. VM_BUG_ON_FOLIO(!folio_test_hugetlb_vmemmap_optimized(folio), folio);
  1258. lockdep_assert_held(&hugetlb_lock);
  1259. INIT_LIST_HEAD(&folio->lru);
  1260. h->nr_huge_pages++;
  1261. h->nr_huge_pages_node[nid]++;
  1262. if (adjust_surplus) {
  1263. h->surplus_huge_pages++;
  1264. h->surplus_huge_pages_node[nid]++;
  1265. }
  1266. __folio_set_hugetlb(folio);
  1267. folio_change_private(folio, NULL);
  1268. /*
  1269. * We have to set hugetlb_vmemmap_optimized again as above
  1270. * folio_change_private(folio, NULL) cleared it.
  1271. */
  1272. folio_set_hugetlb_vmemmap_optimized(folio);
  1273. arch_clear_hugetlb_flags(folio);
  1274. enqueue_hugetlb_folio(h, folio);
  1275. }
  1276. static void __update_and_free_hugetlb_folio(struct hstate *h,
  1277. struct folio *folio)
  1278. {
  1279. bool clear_flag = folio_test_hugetlb_vmemmap_optimized(folio);
  1280. if (hstate_is_gigantic_no_runtime(h))
  1281. return;
  1282. /*
  1283. * If we don't know which subpages are hwpoisoned, we can't free
  1284. * the hugepage, so it's leaked intentionally.
  1285. */
  1286. if (folio_test_hugetlb_raw_hwp_unreliable(folio))
  1287. return;
  1288. /*
  1289. * If folio is not vmemmap optimized (!clear_flag), then the folio
  1290. * is no longer identified as a hugetlb page. hugetlb_vmemmap_restore_folio
  1291. * can only be passed hugetlb pages and will BUG otherwise.
  1292. */
  1293. if (clear_flag && hugetlb_vmemmap_restore_folio(h, folio)) {
  1294. spin_lock_irq(&hugetlb_lock);
  1295. /*
  1296. * If we cannot allocate vmemmap pages, just refuse to free the
  1297. * page and put the page back on the hugetlb free list and treat
  1298. * as a surplus page.
  1299. */
  1300. add_hugetlb_folio(h, folio, true);
  1301. spin_unlock_irq(&hugetlb_lock);
  1302. return;
  1303. }
  1304. /*
  1305. * If vmemmap pages were allocated above, then we need to clear the
  1306. * hugetlb flag under the hugetlb lock.
  1307. */
  1308. if (folio_test_hugetlb(folio)) {
  1309. spin_lock_irq(&hugetlb_lock);
  1310. __folio_clear_hugetlb(folio);
  1311. spin_unlock_irq(&hugetlb_lock);
  1312. }
  1313. /*
  1314. * Move PageHWPoison flag from head page to the raw error pages,
  1315. * which makes any healthy subpages reusable.
  1316. */
  1317. if (unlikely(folio_test_hwpoison(folio)))
  1318. folio_clear_hugetlb_hwpoison(folio);
  1319. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  1320. if (folio_test_hugetlb_cma(folio))
  1321. hugetlb_cma_free_frozen_folio(folio);
  1322. else
  1323. free_frozen_pages(&folio->page, folio_order(folio));
  1324. }
  1325. /*
  1326. * As update_and_free_hugetlb_folio() can be called under any context, so we cannot
  1327. * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
  1328. * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
  1329. * the vmemmap pages.
  1330. *
  1331. * free_hpage_workfn() locklessly retrieves the linked list of pages to be
  1332. * freed and frees them one-by-one. As the page->mapping pointer is going
  1333. * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
  1334. * structure of a lockless linked list of huge pages to be freed.
  1335. */
  1336. static LLIST_HEAD(hpage_freelist);
  1337. static void free_hpage_workfn(struct work_struct *work)
  1338. {
  1339. struct llist_node *node;
  1340. node = llist_del_all(&hpage_freelist);
  1341. while (node) {
  1342. struct folio *folio;
  1343. struct hstate *h;
  1344. folio = container_of((struct address_space **)node,
  1345. struct folio, mapping);
  1346. node = node->next;
  1347. folio->mapping = NULL;
  1348. /*
  1349. * The VM_BUG_ON_FOLIO(!folio_test_hugetlb(folio), folio) in
  1350. * folio_hstate() is going to trigger because a previous call to
  1351. * remove_hugetlb_folio() will clear the hugetlb bit, so do
  1352. * not use folio_hstate() directly.
  1353. */
  1354. h = size_to_hstate(folio_size(folio));
  1355. __update_and_free_hugetlb_folio(h, folio);
  1356. cond_resched();
  1357. }
  1358. }
  1359. static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
  1360. static inline void flush_free_hpage_work(struct hstate *h)
  1361. {
  1362. if (hugetlb_vmemmap_optimizable(h))
  1363. flush_work(&free_hpage_work);
  1364. }
  1365. static void update_and_free_hugetlb_folio(struct hstate *h, struct folio *folio,
  1366. bool atomic)
  1367. {
  1368. if (!folio_test_hugetlb_vmemmap_optimized(folio) || !atomic) {
  1369. __update_and_free_hugetlb_folio(h, folio);
  1370. return;
  1371. }
  1372. /*
  1373. * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
  1374. *
  1375. * Only call schedule_work() if hpage_freelist is previously
  1376. * empty. Otherwise, schedule_work() had been called but the workfn
  1377. * hasn't retrieved the list yet.
  1378. */
  1379. if (llist_add((struct llist_node *)&folio->mapping, &hpage_freelist))
  1380. schedule_work(&free_hpage_work);
  1381. }
  1382. static void bulk_vmemmap_restore_error(struct hstate *h,
  1383. struct list_head *folio_list,
  1384. struct list_head *non_hvo_folios)
  1385. {
  1386. struct folio *folio, *t_folio;
  1387. if (!list_empty(non_hvo_folios)) {
  1388. /*
  1389. * Free any restored hugetlb pages so that restore of the
  1390. * entire list can be retried.
  1391. * The idea is that in the common case of ENOMEM errors freeing
  1392. * hugetlb pages with vmemmap we will free up memory so that we
  1393. * can allocate vmemmap for more hugetlb pages.
  1394. */
  1395. list_for_each_entry_safe(folio, t_folio, non_hvo_folios, lru) {
  1396. list_del(&folio->lru);
  1397. spin_lock_irq(&hugetlb_lock);
  1398. __folio_clear_hugetlb(folio);
  1399. spin_unlock_irq(&hugetlb_lock);
  1400. update_and_free_hugetlb_folio(h, folio, false);
  1401. cond_resched();
  1402. }
  1403. } else {
  1404. /*
  1405. * In the case where there are no folios which can be
  1406. * immediately freed, we loop through the list trying to restore
  1407. * vmemmap individually in the hope that someone elsewhere may
  1408. * have done something to cause success (such as freeing some
  1409. * memory). If unable to restore a hugetlb page, the hugetlb
  1410. * page is made a surplus page and removed from the list.
  1411. * If are able to restore vmemmap and free one hugetlb page, we
  1412. * quit processing the list to retry the bulk operation.
  1413. */
  1414. list_for_each_entry_safe(folio, t_folio, folio_list, lru)
  1415. if (hugetlb_vmemmap_restore_folio(h, folio)) {
  1416. list_del(&folio->lru);
  1417. spin_lock_irq(&hugetlb_lock);
  1418. add_hugetlb_folio(h, folio, true);
  1419. spin_unlock_irq(&hugetlb_lock);
  1420. } else {
  1421. list_del(&folio->lru);
  1422. spin_lock_irq(&hugetlb_lock);
  1423. __folio_clear_hugetlb(folio);
  1424. spin_unlock_irq(&hugetlb_lock);
  1425. update_and_free_hugetlb_folio(h, folio, false);
  1426. cond_resched();
  1427. break;
  1428. }
  1429. }
  1430. }
  1431. static void update_and_free_pages_bulk(struct hstate *h,
  1432. struct list_head *folio_list)
  1433. {
  1434. long ret;
  1435. struct folio *folio, *t_folio;
  1436. LIST_HEAD(non_hvo_folios);
  1437. /*
  1438. * First allocate required vmemmmap (if necessary) for all folios.
  1439. * Carefully handle errors and free up any available hugetlb pages
  1440. * in an effort to make forward progress.
  1441. */
  1442. retry:
  1443. ret = hugetlb_vmemmap_restore_folios(h, folio_list, &non_hvo_folios);
  1444. if (ret < 0) {
  1445. bulk_vmemmap_restore_error(h, folio_list, &non_hvo_folios);
  1446. goto retry;
  1447. }
  1448. /*
  1449. * At this point, list should be empty, ret should be >= 0 and there
  1450. * should only be pages on the non_hvo_folios list.
  1451. * Do note that the non_hvo_folios list could be empty.
  1452. * Without HVO enabled, ret will be 0 and there is no need to call
  1453. * __folio_clear_hugetlb as this was done previously.
  1454. */
  1455. VM_WARN_ON(!list_empty(folio_list));
  1456. VM_WARN_ON(ret < 0);
  1457. if (!list_empty(&non_hvo_folios) && ret) {
  1458. spin_lock_irq(&hugetlb_lock);
  1459. list_for_each_entry(folio, &non_hvo_folios, lru)
  1460. __folio_clear_hugetlb(folio);
  1461. spin_unlock_irq(&hugetlb_lock);
  1462. }
  1463. list_for_each_entry_safe(folio, t_folio, &non_hvo_folios, lru) {
  1464. update_and_free_hugetlb_folio(h, folio, false);
  1465. cond_resched();
  1466. }
  1467. }
  1468. struct hstate *size_to_hstate(unsigned long size)
  1469. {
  1470. struct hstate *h;
  1471. for_each_hstate(h) {
  1472. if (huge_page_size(h) == size)
  1473. return h;
  1474. }
  1475. return NULL;
  1476. }
  1477. void free_huge_folio(struct folio *folio)
  1478. {
  1479. /*
  1480. * Can't pass hstate in here because it is called from the
  1481. * generic mm code.
  1482. */
  1483. struct hstate *h = folio_hstate(folio);
  1484. int nid = folio_nid(folio);
  1485. struct hugepage_subpool *spool = hugetlb_folio_subpool(folio);
  1486. bool restore_reserve;
  1487. unsigned long flags;
  1488. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  1489. VM_BUG_ON_FOLIO(folio_mapcount(folio), folio);
  1490. hugetlb_set_folio_subpool(folio, NULL);
  1491. if (folio_test_anon(folio))
  1492. __ClearPageAnonExclusive(&folio->page);
  1493. folio->mapping = NULL;
  1494. restore_reserve = folio_test_hugetlb_restore_reserve(folio);
  1495. folio_clear_hugetlb_restore_reserve(folio);
  1496. /*
  1497. * If HPageRestoreReserve was set on page, page allocation consumed a
  1498. * reservation. If the page was associated with a subpool, there
  1499. * would have been a page reserved in the subpool before allocation
  1500. * via hugepage_subpool_get_pages(). Since we are 'restoring' the
  1501. * reservation, do not call hugepage_subpool_put_pages() as this will
  1502. * remove the reserved page from the subpool.
  1503. */
  1504. if (!restore_reserve) {
  1505. /*
  1506. * A return code of zero implies that the subpool will be
  1507. * under its minimum size if the reservation is not restored
  1508. * after page is free. Therefore, force restore_reserve
  1509. * operation.
  1510. */
  1511. if (hugepage_subpool_put_pages(spool, 1) == 0)
  1512. restore_reserve = true;
  1513. }
  1514. spin_lock_irqsave(&hugetlb_lock, flags);
  1515. folio_clear_hugetlb_migratable(folio);
  1516. hugetlb_cgroup_uncharge_folio(hstate_index(h),
  1517. pages_per_huge_page(h), folio);
  1518. hugetlb_cgroup_uncharge_folio_rsvd(hstate_index(h),
  1519. pages_per_huge_page(h), folio);
  1520. lruvec_stat_mod_folio(folio, NR_HUGETLB, -pages_per_huge_page(h));
  1521. mem_cgroup_uncharge(folio);
  1522. if (restore_reserve)
  1523. h->resv_huge_pages++;
  1524. if (folio_test_hugetlb_temporary(folio)) {
  1525. remove_hugetlb_folio(h, folio, false);
  1526. spin_unlock_irqrestore(&hugetlb_lock, flags);
  1527. update_and_free_hugetlb_folio(h, folio, true);
  1528. } else if (h->surplus_huge_pages_node[nid]) {
  1529. /* remove the page from active list */
  1530. remove_hugetlb_folio(h, folio, true);
  1531. spin_unlock_irqrestore(&hugetlb_lock, flags);
  1532. update_and_free_hugetlb_folio(h, folio, true);
  1533. } else {
  1534. arch_clear_hugetlb_flags(folio);
  1535. enqueue_hugetlb_folio(h, folio);
  1536. spin_unlock_irqrestore(&hugetlb_lock, flags);
  1537. }
  1538. }
  1539. /*
  1540. * Must be called with the hugetlb lock held
  1541. */
  1542. static void account_new_hugetlb_folio(struct hstate *h, struct folio *folio)
  1543. {
  1544. lockdep_assert_held(&hugetlb_lock);
  1545. h->nr_huge_pages++;
  1546. h->nr_huge_pages_node[folio_nid(folio)]++;
  1547. }
  1548. void init_new_hugetlb_folio(struct folio *folio)
  1549. {
  1550. __folio_set_hugetlb(folio);
  1551. INIT_LIST_HEAD(&folio->lru);
  1552. hugetlb_set_folio_subpool(folio, NULL);
  1553. set_hugetlb_cgroup(folio, NULL);
  1554. set_hugetlb_cgroup_rsvd(folio, NULL);
  1555. }
  1556. /*
  1557. * Find and lock address space (mapping) in write mode.
  1558. *
  1559. * Upon entry, the folio is locked which means that folio_mapping() is
  1560. * stable. Due to locking order, we can only trylock_write. If we can
  1561. * not get the lock, simply return NULL to caller.
  1562. */
  1563. struct address_space *hugetlb_folio_mapping_lock_write(struct folio *folio)
  1564. {
  1565. struct address_space *mapping = folio_mapping(folio);
  1566. if (!mapping)
  1567. return mapping;
  1568. if (i_mmap_trylock_write(mapping))
  1569. return mapping;
  1570. return NULL;
  1571. }
  1572. static struct folio *alloc_buddy_frozen_folio(int order, gfp_t gfp_mask,
  1573. int nid, nodemask_t *nmask, nodemask_t *node_alloc_noretry)
  1574. {
  1575. struct folio *folio;
  1576. bool alloc_try_hard = true;
  1577. /*
  1578. * By default we always try hard to allocate the folio with
  1579. * __GFP_RETRY_MAYFAIL flag. However, if we are allocating folios in
  1580. * a loop (to adjust global huge page counts) and previous allocation
  1581. * failed, do not continue to try hard on the same node. Use the
  1582. * node_alloc_noretry bitmap to manage this state information.
  1583. */
  1584. if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
  1585. alloc_try_hard = false;
  1586. if (alloc_try_hard)
  1587. gfp_mask |= __GFP_RETRY_MAYFAIL;
  1588. folio = (struct folio *)__alloc_frozen_pages(gfp_mask, order, nid, nmask);
  1589. /*
  1590. * If we did not specify __GFP_RETRY_MAYFAIL, but still got a
  1591. * folio this indicates an overall state change. Clear bit so
  1592. * that we resume normal 'try hard' allocations.
  1593. */
  1594. if (node_alloc_noretry && folio && !alloc_try_hard)
  1595. node_clear(nid, *node_alloc_noretry);
  1596. /*
  1597. * If we tried hard to get a folio but failed, set bit so that
  1598. * subsequent attempts will not try as hard until there is an
  1599. * overall state change.
  1600. */
  1601. if (node_alloc_noretry && !folio && alloc_try_hard)
  1602. node_set(nid, *node_alloc_noretry);
  1603. if (!folio) {
  1604. __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
  1605. return NULL;
  1606. }
  1607. __count_vm_event(HTLB_BUDDY_PGALLOC);
  1608. return folio;
  1609. }
  1610. static struct folio *only_alloc_fresh_hugetlb_folio(struct hstate *h,
  1611. gfp_t gfp_mask, int nid, nodemask_t *nmask,
  1612. nodemask_t *node_alloc_noretry)
  1613. {
  1614. struct folio *folio;
  1615. int order = huge_page_order(h);
  1616. if (nid == NUMA_NO_NODE)
  1617. nid = numa_mem_id();
  1618. if (order_is_gigantic(order))
  1619. folio = alloc_gigantic_frozen_folio(order, gfp_mask, nid, nmask);
  1620. else
  1621. folio = alloc_buddy_frozen_folio(order, gfp_mask, nid, nmask,
  1622. node_alloc_noretry);
  1623. if (folio)
  1624. init_new_hugetlb_folio(folio);
  1625. return folio;
  1626. }
  1627. /*
  1628. * Common helper to allocate a fresh hugetlb folio. All specific allocators
  1629. * should use this function to get new hugetlb folio
  1630. *
  1631. * Note that returned folio is 'frozen': ref count of head page and all tail
  1632. * pages is zero, and the accounting must be done in the caller.
  1633. */
  1634. static struct folio *alloc_fresh_hugetlb_folio(struct hstate *h,
  1635. gfp_t gfp_mask, int nid, nodemask_t *nmask)
  1636. {
  1637. struct folio *folio;
  1638. folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask, NULL);
  1639. if (folio)
  1640. hugetlb_vmemmap_optimize_folio(h, folio);
  1641. return folio;
  1642. }
  1643. void prep_and_add_allocated_folios(struct hstate *h,
  1644. struct list_head *folio_list)
  1645. {
  1646. unsigned long flags;
  1647. struct folio *folio, *tmp_f;
  1648. /* Send list for bulk vmemmap optimization processing */
  1649. hugetlb_vmemmap_optimize_folios(h, folio_list);
  1650. /* Add all new pool pages to free lists in one lock cycle */
  1651. spin_lock_irqsave(&hugetlb_lock, flags);
  1652. list_for_each_entry_safe(folio, tmp_f, folio_list, lru) {
  1653. account_new_hugetlb_folio(h, folio);
  1654. enqueue_hugetlb_folio(h, folio);
  1655. }
  1656. spin_unlock_irqrestore(&hugetlb_lock, flags);
  1657. }
  1658. /*
  1659. * Allocates a fresh hugetlb page in a node interleaved manner. The page
  1660. * will later be added to the appropriate hugetlb pool.
  1661. */
  1662. static struct folio *alloc_pool_huge_folio(struct hstate *h,
  1663. nodemask_t *nodes_allowed,
  1664. nodemask_t *node_alloc_noretry,
  1665. int *next_node)
  1666. {
  1667. gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
  1668. int nr_nodes, node;
  1669. for_each_node_mask_to_alloc(next_node, nr_nodes, node, nodes_allowed) {
  1670. struct folio *folio;
  1671. folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, node,
  1672. nodes_allowed, node_alloc_noretry);
  1673. if (folio)
  1674. return folio;
  1675. }
  1676. return NULL;
  1677. }
  1678. /*
  1679. * Remove huge page from pool from next node to free. Attempt to keep
  1680. * persistent huge pages more or less balanced over allowed nodes.
  1681. * This routine only 'removes' the hugetlb page. The caller must make
  1682. * an additional call to free the page to low level allocators.
  1683. * Called with hugetlb_lock locked.
  1684. */
  1685. static struct folio *remove_pool_hugetlb_folio(struct hstate *h,
  1686. nodemask_t *nodes_allowed, bool acct_surplus)
  1687. {
  1688. int nr_nodes, node;
  1689. struct folio *folio = NULL;
  1690. lockdep_assert_held(&hugetlb_lock);
  1691. for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
  1692. /*
  1693. * If we're returning unused surplus pages, only examine
  1694. * nodes with surplus pages.
  1695. */
  1696. if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
  1697. !list_empty(&h->hugepage_freelists[node])) {
  1698. folio = list_entry(h->hugepage_freelists[node].next,
  1699. struct folio, lru);
  1700. remove_hugetlb_folio(h, folio, acct_surplus);
  1701. break;
  1702. }
  1703. }
  1704. return folio;
  1705. }
  1706. /*
  1707. * Dissolve a given free hugetlb folio into free buddy pages. This function
  1708. * does nothing for in-use hugetlb folios and non-hugetlb folios.
  1709. * This function returns values like below:
  1710. *
  1711. * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
  1712. * when the system is under memory pressure and the feature of
  1713. * freeing unused vmemmap pages associated with each hugetlb page
  1714. * is enabled.
  1715. * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
  1716. * (allocated or reserved.)
  1717. * 0: successfully dissolved free hugepages or the page is not a
  1718. * hugepage (considered as already dissolved)
  1719. */
  1720. int dissolve_free_hugetlb_folio(struct folio *folio)
  1721. {
  1722. int rc = -EBUSY;
  1723. retry:
  1724. /* Not to disrupt normal path by vainly holding hugetlb_lock */
  1725. if (!folio_test_hugetlb(folio))
  1726. return 0;
  1727. spin_lock_irq(&hugetlb_lock);
  1728. if (!folio_test_hugetlb(folio)) {
  1729. rc = 0;
  1730. goto out;
  1731. }
  1732. if (!folio_ref_count(folio)) {
  1733. struct hstate *h = folio_hstate(folio);
  1734. bool adjust_surplus = false;
  1735. if (!available_huge_pages(h))
  1736. goto out;
  1737. /*
  1738. * We should make sure that the page is already on the free list
  1739. * when it is dissolved.
  1740. */
  1741. if (unlikely(!folio_test_hugetlb_freed(folio))) {
  1742. spin_unlock_irq(&hugetlb_lock);
  1743. cond_resched();
  1744. /*
  1745. * Theoretically, we should return -EBUSY when we
  1746. * encounter this race. In fact, we have a chance
  1747. * to successfully dissolve the page if we do a
  1748. * retry. Because the race window is quite small.
  1749. * If we seize this opportunity, it is an optimization
  1750. * for increasing the success rate of dissolving page.
  1751. */
  1752. goto retry;
  1753. }
  1754. if (h->surplus_huge_pages_node[folio_nid(folio)])
  1755. adjust_surplus = true;
  1756. remove_hugetlb_folio(h, folio, adjust_surplus);
  1757. h->max_huge_pages--;
  1758. spin_unlock_irq(&hugetlb_lock);
  1759. /*
  1760. * Normally update_and_free_hugtlb_folio will allocate required vmemmmap
  1761. * before freeing the page. update_and_free_hugtlb_folio will fail to
  1762. * free the page if it can not allocate required vmemmap. We
  1763. * need to adjust max_huge_pages if the page is not freed.
  1764. * Attempt to allocate vmemmmap here so that we can take
  1765. * appropriate action on failure.
  1766. *
  1767. * The folio_test_hugetlb check here is because
  1768. * remove_hugetlb_folio will clear hugetlb folio flag for
  1769. * non-vmemmap optimized hugetlb folios.
  1770. */
  1771. if (folio_test_hugetlb(folio)) {
  1772. rc = hugetlb_vmemmap_restore_folio(h, folio);
  1773. if (rc) {
  1774. spin_lock_irq(&hugetlb_lock);
  1775. add_hugetlb_folio(h, folio, adjust_surplus);
  1776. h->max_huge_pages++;
  1777. goto out;
  1778. }
  1779. } else {
  1780. rc = 0;
  1781. }
  1782. update_and_free_hugetlb_folio(h, folio, false);
  1783. return rc;
  1784. }
  1785. out:
  1786. spin_unlock_irq(&hugetlb_lock);
  1787. return rc;
  1788. }
  1789. /*
  1790. * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
  1791. * make specified memory blocks removable from the system.
  1792. * Note that this will dissolve a free gigantic hugepage completely, if any
  1793. * part of it lies within the given range.
  1794. * Also note that if dissolve_free_hugetlb_folio() returns with an error, all
  1795. * free hugetlb folios that were dissolved before that error are lost.
  1796. */
  1797. int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn)
  1798. {
  1799. unsigned long pfn;
  1800. struct folio *folio;
  1801. int rc = 0;
  1802. unsigned int order;
  1803. struct hstate *h;
  1804. if (!hugepages_supported())
  1805. return rc;
  1806. order = huge_page_order(&default_hstate);
  1807. for_each_hstate(h)
  1808. order = min(order, huge_page_order(h));
  1809. for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
  1810. folio = pfn_folio(pfn);
  1811. rc = dissolve_free_hugetlb_folio(folio);
  1812. if (rc)
  1813. break;
  1814. }
  1815. return rc;
  1816. }
  1817. /*
  1818. * Allocates a fresh surplus page from the page allocator.
  1819. */
  1820. static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,
  1821. gfp_t gfp_mask, int nid, nodemask_t *nmask)
  1822. {
  1823. struct folio *folio = NULL;
  1824. if (hstate_is_gigantic_no_runtime(h))
  1825. return NULL;
  1826. spin_lock_irq(&hugetlb_lock);
  1827. if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
  1828. goto out_unlock;
  1829. spin_unlock_irq(&hugetlb_lock);
  1830. folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask);
  1831. if (!folio)
  1832. return NULL;
  1833. spin_lock_irq(&hugetlb_lock);
  1834. /*
  1835. * nr_huge_pages needs to be adjusted within the same lock cycle
  1836. * as surplus_pages, otherwise it might confuse
  1837. * persistent_huge_pages() momentarily.
  1838. */
  1839. account_new_hugetlb_folio(h, folio);
  1840. /*
  1841. * We could have raced with the pool size change.
  1842. * Double check that and simply deallocate the new page
  1843. * if we would end up overcommiting the surpluses. Abuse
  1844. * temporary page to workaround the nasty free_huge_folio
  1845. * codeflow
  1846. */
  1847. if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
  1848. folio_set_hugetlb_temporary(folio);
  1849. spin_unlock_irq(&hugetlb_lock);
  1850. free_huge_folio(folio);
  1851. return NULL;
  1852. }
  1853. h->surplus_huge_pages++;
  1854. h->surplus_huge_pages_node[folio_nid(folio)]++;
  1855. out_unlock:
  1856. spin_unlock_irq(&hugetlb_lock);
  1857. return folio;
  1858. }
  1859. static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mask,
  1860. int nid, nodemask_t *nmask)
  1861. {
  1862. struct folio *folio;
  1863. if (hstate_is_gigantic(h))
  1864. return NULL;
  1865. folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask);
  1866. if (!folio)
  1867. return NULL;
  1868. spin_lock_irq(&hugetlb_lock);
  1869. account_new_hugetlb_folio(h, folio);
  1870. spin_unlock_irq(&hugetlb_lock);
  1871. /* fresh huge pages are frozen */
  1872. folio_ref_unfreeze(folio, 1);
  1873. /*
  1874. * We do not account these pages as surplus because they are only
  1875. * temporary and will be released properly on the last reference
  1876. */
  1877. folio_set_hugetlb_temporary(folio);
  1878. return folio;
  1879. }
  1880. /*
  1881. * Use the VMA's mpolicy to allocate a huge page from the buddy.
  1882. */
  1883. static
  1884. struct folio *alloc_buddy_hugetlb_folio_with_mpol(struct hstate *h,
  1885. struct vm_area_struct *vma, unsigned long addr)
  1886. {
  1887. struct folio *folio = NULL;
  1888. struct mempolicy *mpol;
  1889. gfp_t gfp_mask = htlb_alloc_mask(h);
  1890. int nid;
  1891. nodemask_t *nodemask;
  1892. nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
  1893. if (mpol_is_preferred_many(mpol)) {
  1894. gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
  1895. folio = alloc_surplus_hugetlb_folio(h, gfp, nid, nodemask);
  1896. /* Fallback to all nodes if page==NULL */
  1897. nodemask = NULL;
  1898. }
  1899. if (!folio)
  1900. folio = alloc_surplus_hugetlb_folio(h, gfp_mask, nid, nodemask);
  1901. mpol_cond_put(mpol);
  1902. return folio;
  1903. }
  1904. struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid,
  1905. nodemask_t *nmask, gfp_t gfp_mask)
  1906. {
  1907. struct folio *folio;
  1908. spin_lock_irq(&hugetlb_lock);
  1909. if (!h->resv_huge_pages) {
  1910. spin_unlock_irq(&hugetlb_lock);
  1911. return NULL;
  1912. }
  1913. folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, preferred_nid,
  1914. nmask);
  1915. if (folio)
  1916. h->resv_huge_pages--;
  1917. spin_unlock_irq(&hugetlb_lock);
  1918. return folio;
  1919. }
  1920. /* folio migration callback function */
  1921. struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
  1922. nodemask_t *nmask, gfp_t gfp_mask, bool allow_alloc_fallback)
  1923. {
  1924. spin_lock_irq(&hugetlb_lock);
  1925. if (available_huge_pages(h)) {
  1926. struct folio *folio;
  1927. folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
  1928. preferred_nid, nmask);
  1929. if (folio) {
  1930. spin_unlock_irq(&hugetlb_lock);
  1931. return folio;
  1932. }
  1933. }
  1934. spin_unlock_irq(&hugetlb_lock);
  1935. /* We cannot fallback to other nodes, as we could break the per-node pool. */
  1936. if (!allow_alloc_fallback)
  1937. gfp_mask |= __GFP_THISNODE;
  1938. return alloc_migrate_hugetlb_folio(h, gfp_mask, preferred_nid, nmask);
  1939. }
  1940. static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
  1941. {
  1942. #ifdef CONFIG_NUMA
  1943. struct mempolicy *mpol = get_task_policy(current);
  1944. /*
  1945. * Only enforce MPOL_BIND policy which overlaps with cpuset policy
  1946. * (from policy_nodemask) specifically for hugetlb case
  1947. */
  1948. if (mpol->mode == MPOL_BIND &&
  1949. (apply_policy_zone(mpol, gfp_zone(gfp)) &&
  1950. cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
  1951. return &mpol->nodes;
  1952. #endif
  1953. return NULL;
  1954. }
  1955. /*
  1956. * Increase the hugetlb pool such that it can accommodate a reservation
  1957. * of size 'delta'.
  1958. */
  1959. static int gather_surplus_pages(struct hstate *h, long delta)
  1960. __must_hold(&hugetlb_lock)
  1961. {
  1962. LIST_HEAD(surplus_list);
  1963. struct folio *folio, *tmp;
  1964. int ret;
  1965. long i;
  1966. long needed, allocated;
  1967. bool alloc_ok = true;
  1968. nodemask_t *mbind_nodemask, alloc_nodemask;
  1969. mbind_nodemask = policy_mbind_nodemask(htlb_alloc_mask(h));
  1970. if (mbind_nodemask)
  1971. nodes_and(alloc_nodemask, *mbind_nodemask, cpuset_current_mems_allowed);
  1972. else
  1973. alloc_nodemask = cpuset_current_mems_allowed;
  1974. lockdep_assert_held(&hugetlb_lock);
  1975. needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
  1976. if (needed <= 0) {
  1977. h->resv_huge_pages += delta;
  1978. return 0;
  1979. }
  1980. allocated = 0;
  1981. ret = -ENOMEM;
  1982. retry:
  1983. spin_unlock_irq(&hugetlb_lock);
  1984. for (i = 0; i < needed; i++) {
  1985. folio = NULL;
  1986. /*
  1987. * It is okay to use NUMA_NO_NODE because we use numa_mem_id()
  1988. * down the road to pick the current node if that is the case.
  1989. */
  1990. folio = alloc_surplus_hugetlb_folio(h, htlb_alloc_mask(h),
  1991. NUMA_NO_NODE, &alloc_nodemask);
  1992. if (!folio) {
  1993. alloc_ok = false;
  1994. break;
  1995. }
  1996. list_add(&folio->lru, &surplus_list);
  1997. cond_resched();
  1998. }
  1999. allocated += i;
  2000. /*
  2001. * After retaking hugetlb_lock, we need to recalculate 'needed'
  2002. * because either resv_huge_pages or free_huge_pages may have changed.
  2003. */
  2004. spin_lock_irq(&hugetlb_lock);
  2005. needed = (h->resv_huge_pages + delta) -
  2006. (h->free_huge_pages + allocated);
  2007. if (needed > 0) {
  2008. if (alloc_ok)
  2009. goto retry;
  2010. /*
  2011. * We were not able to allocate enough pages to
  2012. * satisfy the entire reservation so we free what
  2013. * we've allocated so far.
  2014. */
  2015. goto free;
  2016. }
  2017. /*
  2018. * The surplus_list now contains _at_least_ the number of extra pages
  2019. * needed to accommodate the reservation. Add the appropriate number
  2020. * of pages to the hugetlb pool and free the extras back to the buddy
  2021. * allocator. Commit the entire reservation here to prevent another
  2022. * process from stealing the pages as they are added to the pool but
  2023. * before they are reserved.
  2024. */
  2025. needed += allocated;
  2026. h->resv_huge_pages += delta;
  2027. ret = 0;
  2028. /* Free the needed pages to the hugetlb pool */
  2029. list_for_each_entry_safe(folio, tmp, &surplus_list, lru) {
  2030. if ((--needed) < 0)
  2031. break;
  2032. /* Add the page to the hugetlb allocator */
  2033. enqueue_hugetlb_folio(h, folio);
  2034. }
  2035. free:
  2036. spin_unlock_irq(&hugetlb_lock);
  2037. /*
  2038. * Free unnecessary surplus pages to the buddy allocator.
  2039. * Pages have no ref count, call free_huge_folio directly.
  2040. */
  2041. list_for_each_entry_safe(folio, tmp, &surplus_list, lru)
  2042. free_huge_folio(folio);
  2043. spin_lock_irq(&hugetlb_lock);
  2044. return ret;
  2045. }
  2046. /*
  2047. * This routine has two main purposes:
  2048. * 1) Decrement the reservation count (resv_huge_pages) by the value passed
  2049. * in unused_resv_pages. This corresponds to the prior adjustments made
  2050. * to the associated reservation map.
  2051. * 2) Free any unused surplus pages that may have been allocated to satisfy
  2052. * the reservation. As many as unused_resv_pages may be freed.
  2053. */
  2054. static void return_unused_surplus_pages(struct hstate *h,
  2055. unsigned long unused_resv_pages)
  2056. {
  2057. unsigned long nr_pages;
  2058. LIST_HEAD(page_list);
  2059. lockdep_assert_held(&hugetlb_lock);
  2060. /* Uncommit the reservation */
  2061. h->resv_huge_pages -= unused_resv_pages;
  2062. if (hstate_is_gigantic_no_runtime(h))
  2063. goto out;
  2064. /*
  2065. * Part (or even all) of the reservation could have been backed
  2066. * by pre-allocated pages. Only free surplus pages.
  2067. */
  2068. nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
  2069. /*
  2070. * We want to release as many surplus pages as possible, spread
  2071. * evenly across all nodes with memory. Iterate across these nodes
  2072. * until we can no longer free unreserved surplus pages. This occurs
  2073. * when the nodes with surplus pages have no free pages.
  2074. * remove_pool_hugetlb_folio() will balance the freed pages across the
  2075. * on-line nodes with memory and will handle the hstate accounting.
  2076. */
  2077. while (nr_pages--) {
  2078. struct folio *folio;
  2079. folio = remove_pool_hugetlb_folio(h, &node_states[N_MEMORY], 1);
  2080. if (!folio)
  2081. goto out;
  2082. list_add(&folio->lru, &page_list);
  2083. }
  2084. out:
  2085. spin_unlock_irq(&hugetlb_lock);
  2086. update_and_free_pages_bulk(h, &page_list);
  2087. spin_lock_irq(&hugetlb_lock);
  2088. }
  2089. /*
  2090. * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
  2091. * are used by the huge page allocation routines to manage reservations.
  2092. *
  2093. * vma_needs_reservation is called to determine if the huge page at addr
  2094. * within the vma has an associated reservation. If a reservation is
  2095. * needed, the value 1 is returned. The caller is then responsible for
  2096. * managing the global reservation and subpool usage counts. After
  2097. * the huge page has been allocated, vma_commit_reservation is called
  2098. * to add the page to the reservation map. If the page allocation fails,
  2099. * the reservation must be ended instead of committed. vma_end_reservation
  2100. * is called in such cases.
  2101. *
  2102. * In the normal case, vma_commit_reservation returns the same value
  2103. * as the preceding vma_needs_reservation call. The only time this
  2104. * is not the case is if a reserve map was changed between calls. It
  2105. * is the responsibility of the caller to notice the difference and
  2106. * take appropriate action.
  2107. *
  2108. * vma_add_reservation is used in error paths where a reservation must
  2109. * be restored when a newly allocated huge page must be freed. It is
  2110. * to be called after calling vma_needs_reservation to determine if a
  2111. * reservation exists.
  2112. *
  2113. * vma_del_reservation is used in error paths where an entry in the reserve
  2114. * map was created during huge page allocation and must be removed. It is to
  2115. * be called after calling vma_needs_reservation to determine if a reservation
  2116. * exists.
  2117. */
  2118. enum vma_resv_mode {
  2119. VMA_NEEDS_RESV,
  2120. VMA_COMMIT_RESV,
  2121. VMA_END_RESV,
  2122. VMA_ADD_RESV,
  2123. VMA_DEL_RESV,
  2124. };
  2125. static long __vma_reservation_common(struct hstate *h,
  2126. struct vm_area_struct *vma, unsigned long addr,
  2127. enum vma_resv_mode mode)
  2128. {
  2129. struct resv_map *resv;
  2130. pgoff_t idx;
  2131. long ret;
  2132. long dummy_out_regions_needed;
  2133. resv = vma_resv_map(vma);
  2134. if (!resv)
  2135. return 1;
  2136. idx = vma_hugecache_offset(h, vma, addr);
  2137. switch (mode) {
  2138. case VMA_NEEDS_RESV:
  2139. ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
  2140. /* We assume that vma_reservation_* routines always operate on
  2141. * 1 page, and that adding to resv map a 1 page entry can only
  2142. * ever require 1 region.
  2143. */
  2144. VM_BUG_ON(dummy_out_regions_needed != 1);
  2145. break;
  2146. case VMA_COMMIT_RESV:
  2147. ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
  2148. /* region_add calls of range 1 should never fail. */
  2149. VM_BUG_ON(ret < 0);
  2150. break;
  2151. case VMA_END_RESV:
  2152. region_abort(resv, idx, idx + 1, 1);
  2153. ret = 0;
  2154. break;
  2155. case VMA_ADD_RESV:
  2156. if (vma->vm_flags & VM_MAYSHARE) {
  2157. ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
  2158. /* region_add calls of range 1 should never fail. */
  2159. VM_BUG_ON(ret < 0);
  2160. } else {
  2161. region_abort(resv, idx, idx + 1, 1);
  2162. ret = region_del(resv, idx, idx + 1);
  2163. }
  2164. break;
  2165. case VMA_DEL_RESV:
  2166. if (vma->vm_flags & VM_MAYSHARE) {
  2167. region_abort(resv, idx, idx + 1, 1);
  2168. ret = region_del(resv, idx, idx + 1);
  2169. } else {
  2170. ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
  2171. /* region_add calls of range 1 should never fail. */
  2172. VM_BUG_ON(ret < 0);
  2173. }
  2174. break;
  2175. default:
  2176. BUG();
  2177. }
  2178. if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
  2179. return ret;
  2180. /*
  2181. * We know private mapping must have HPAGE_RESV_OWNER set.
  2182. *
  2183. * In most cases, reserves always exist for private mappings.
  2184. * However, a file associated with mapping could have been
  2185. * hole punched or truncated after reserves were consumed.
  2186. * As subsequent fault on such a range will not use reserves.
  2187. * Subtle - The reserve map for private mappings has the
  2188. * opposite meaning than that of shared mappings. If NO
  2189. * entry is in the reserve map, it means a reservation exists.
  2190. * If an entry exists in the reserve map, it means the
  2191. * reservation has already been consumed. As a result, the
  2192. * return value of this routine is the opposite of the
  2193. * value returned from reserve map manipulation routines above.
  2194. */
  2195. if (ret > 0)
  2196. return 0;
  2197. if (ret == 0)
  2198. return 1;
  2199. return ret;
  2200. }
  2201. static long vma_needs_reservation(struct hstate *h,
  2202. struct vm_area_struct *vma, unsigned long addr)
  2203. {
  2204. return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
  2205. }
  2206. static long vma_commit_reservation(struct hstate *h,
  2207. struct vm_area_struct *vma, unsigned long addr)
  2208. {
  2209. return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
  2210. }
  2211. static void vma_end_reservation(struct hstate *h,
  2212. struct vm_area_struct *vma, unsigned long addr)
  2213. {
  2214. (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
  2215. }
  2216. static long vma_add_reservation(struct hstate *h,
  2217. struct vm_area_struct *vma, unsigned long addr)
  2218. {
  2219. return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
  2220. }
  2221. static long vma_del_reservation(struct hstate *h,
  2222. struct vm_area_struct *vma, unsigned long addr)
  2223. {
  2224. return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
  2225. }
  2226. /*
  2227. * This routine is called to restore reservation information on error paths.
  2228. * It should ONLY be called for folios allocated via alloc_hugetlb_folio(),
  2229. * and the hugetlb mutex should remain held when calling this routine.
  2230. *
  2231. * It handles two specific cases:
  2232. * 1) A reservation was in place and the folio consumed the reservation.
  2233. * hugetlb_restore_reserve is set in the folio.
  2234. * 2) No reservation was in place for the page, so hugetlb_restore_reserve is
  2235. * not set. However, alloc_hugetlb_folio always updates the reserve map.
  2236. *
  2237. * In case 1, free_huge_folio later in the error path will increment the
  2238. * global reserve count. But, free_huge_folio does not have enough context
  2239. * to adjust the reservation map. This case deals primarily with private
  2240. * mappings. Adjust the reserve map here to be consistent with global
  2241. * reserve count adjustments to be made by free_huge_folio. Make sure the
  2242. * reserve map indicates there is a reservation present.
  2243. *
  2244. * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio.
  2245. */
  2246. void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
  2247. unsigned long address, struct folio *folio)
  2248. {
  2249. long rc = vma_needs_reservation(h, vma, address);
  2250. if (folio_test_hugetlb_restore_reserve(folio)) {
  2251. if (unlikely(rc < 0))
  2252. /*
  2253. * Rare out of memory condition in reserve map
  2254. * manipulation. Clear hugetlb_restore_reserve so
  2255. * that global reserve count will not be incremented
  2256. * by free_huge_folio. This will make it appear
  2257. * as though the reservation for this folio was
  2258. * consumed. This may prevent the task from
  2259. * faulting in the folio at a later time. This
  2260. * is better than inconsistent global huge page
  2261. * accounting of reserve counts.
  2262. */
  2263. folio_clear_hugetlb_restore_reserve(folio);
  2264. else if (rc)
  2265. (void)vma_add_reservation(h, vma, address);
  2266. else
  2267. vma_end_reservation(h, vma, address);
  2268. } else {
  2269. if (!rc) {
  2270. /*
  2271. * This indicates there is an entry in the reserve map
  2272. * not added by alloc_hugetlb_folio. We know it was added
  2273. * before the alloc_hugetlb_folio call, otherwise
  2274. * hugetlb_restore_reserve would be set on the folio.
  2275. * Remove the entry so that a subsequent allocation
  2276. * does not consume a reservation.
  2277. */
  2278. rc = vma_del_reservation(h, vma, address);
  2279. if (rc < 0)
  2280. /*
  2281. * VERY rare out of memory condition. Since
  2282. * we can not delete the entry, set
  2283. * hugetlb_restore_reserve so that the reserve
  2284. * count will be incremented when the folio
  2285. * is freed. This reserve will be consumed
  2286. * on a subsequent allocation.
  2287. */
  2288. folio_set_hugetlb_restore_reserve(folio);
  2289. } else if (rc < 0) {
  2290. /*
  2291. * Rare out of memory condition from
  2292. * vma_needs_reservation call. Memory allocation is
  2293. * only attempted if a new entry is needed. Therefore,
  2294. * this implies there is not an entry in the
  2295. * reserve map.
  2296. *
  2297. * For shared mappings, no entry in the map indicates
  2298. * no reservation. We are done.
  2299. */
  2300. if (!(vma->vm_flags & VM_MAYSHARE))
  2301. /*
  2302. * For private mappings, no entry indicates
  2303. * a reservation is present. Since we can
  2304. * not add an entry, set hugetlb_restore_reserve
  2305. * on the folio so reserve count will be
  2306. * incremented when freed. This reserve will
  2307. * be consumed on a subsequent allocation.
  2308. */
  2309. folio_set_hugetlb_restore_reserve(folio);
  2310. } else {
  2311. /*
  2312. * No reservation present, do nothing
  2313. */
  2314. vma_end_reservation(h, vma, address);
  2315. }
  2316. }
  2317. }
  2318. /*
  2319. * alloc_and_dissolve_hugetlb_folio - Allocate a new folio and dissolve
  2320. * the old one
  2321. * @old_folio: Old folio to dissolve
  2322. * @list: List to isolate the page in case we need to
  2323. * Returns 0 on success, otherwise negated error.
  2324. */
  2325. static int alloc_and_dissolve_hugetlb_folio(struct folio *old_folio,
  2326. struct list_head *list)
  2327. {
  2328. gfp_t gfp_mask;
  2329. struct hstate *h;
  2330. int nid = folio_nid(old_folio);
  2331. struct folio *new_folio = NULL;
  2332. int ret = 0;
  2333. retry:
  2334. /*
  2335. * The old_folio might have been dissolved from under our feet, so make sure
  2336. * to carefully check the state under the lock.
  2337. */
  2338. spin_lock_irq(&hugetlb_lock);
  2339. if (!folio_test_hugetlb(old_folio)) {
  2340. /*
  2341. * Freed from under us. Drop new_folio too.
  2342. */
  2343. goto free_new;
  2344. } else if (folio_ref_count(old_folio)) {
  2345. bool isolated;
  2346. /*
  2347. * Someone has grabbed the folio, try to isolate it here.
  2348. * Fail with -EBUSY if not possible.
  2349. */
  2350. spin_unlock_irq(&hugetlb_lock);
  2351. isolated = folio_isolate_hugetlb(old_folio, list);
  2352. ret = isolated ? 0 : -EBUSY;
  2353. spin_lock_irq(&hugetlb_lock);
  2354. goto free_new;
  2355. } else if (!folio_test_hugetlb_freed(old_folio)) {
  2356. /*
  2357. * Folio's refcount is 0 but it has not been enqueued in the
  2358. * freelist yet. Race window is small, so we can succeed here if
  2359. * we retry.
  2360. */
  2361. spin_unlock_irq(&hugetlb_lock);
  2362. cond_resched();
  2363. goto retry;
  2364. } else {
  2365. h = folio_hstate(old_folio);
  2366. if (!new_folio) {
  2367. spin_unlock_irq(&hugetlb_lock);
  2368. gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
  2369. new_folio = alloc_fresh_hugetlb_folio(h, gfp_mask,
  2370. nid, NULL);
  2371. if (!new_folio)
  2372. return -ENOMEM;
  2373. goto retry;
  2374. }
  2375. /*
  2376. * Ok, old_folio is still a genuine free hugepage. Remove it from
  2377. * the freelist and decrease the counters. These will be
  2378. * incremented again when calling account_new_hugetlb_folio()
  2379. * and enqueue_hugetlb_folio() for new_folio. The counters will
  2380. * remain stable since this happens under the lock.
  2381. */
  2382. remove_hugetlb_folio(h, old_folio, false);
  2383. /*
  2384. * Ref count on new_folio is already zero as it was dropped
  2385. * earlier. It can be directly added to the pool free list.
  2386. */
  2387. account_new_hugetlb_folio(h, new_folio);
  2388. enqueue_hugetlb_folio(h, new_folio);
  2389. /*
  2390. * Folio has been replaced, we can safely free the old one.
  2391. */
  2392. spin_unlock_irq(&hugetlb_lock);
  2393. update_and_free_hugetlb_folio(h, old_folio, false);
  2394. }
  2395. return ret;
  2396. free_new:
  2397. spin_unlock_irq(&hugetlb_lock);
  2398. if (new_folio)
  2399. update_and_free_hugetlb_folio(h, new_folio, false);
  2400. return ret;
  2401. }
  2402. int isolate_or_dissolve_huge_folio(struct folio *folio, struct list_head *list)
  2403. {
  2404. int ret = -EBUSY;
  2405. /* Not to disrupt normal path by vainly holding hugetlb_lock */
  2406. if (!folio_test_hugetlb(folio))
  2407. return 0;
  2408. /*
  2409. * Fence off gigantic pages as there is a cyclic dependency between
  2410. * alloc_contig_range and them. Return -ENOMEM as this has the effect
  2411. * of bailing out right away without further retrying.
  2412. */
  2413. if (order_is_gigantic(folio_order(folio)))
  2414. return -ENOMEM;
  2415. if (folio_ref_count(folio) && folio_isolate_hugetlb(folio, list))
  2416. ret = 0;
  2417. else if (!folio_ref_count(folio))
  2418. ret = alloc_and_dissolve_hugetlb_folio(folio, list);
  2419. return ret;
  2420. }
  2421. /*
  2422. * replace_free_hugepage_folios - Replace free hugepage folios in a given pfn
  2423. * range with new folios.
  2424. * @start_pfn: start pfn of the given pfn range
  2425. * @end_pfn: end pfn of the given pfn range
  2426. * Returns 0 on success, otherwise negated error.
  2427. */
  2428. int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn)
  2429. {
  2430. unsigned long nr = 0;
  2431. struct page *page;
  2432. struct hstate *h;
  2433. LIST_HEAD(list);
  2434. int ret = 0;
  2435. /* Avoid pfn iterations if no free non-gigantic huge pages */
  2436. for_each_hstate(h) {
  2437. if (hstate_is_gigantic(h))
  2438. continue;
  2439. nr += h->free_huge_pages;
  2440. if (nr)
  2441. break;
  2442. }
  2443. if (!nr)
  2444. return 0;
  2445. while (start_pfn < end_pfn) {
  2446. page = pfn_to_page(start_pfn);
  2447. nr = 1;
  2448. if (PageHuge(page) || PageCompound(page)) {
  2449. struct folio *folio = page_folio(page);
  2450. nr = folio_nr_pages(folio) - folio_page_idx(folio, page);
  2451. /*
  2452. * Don't disrupt normal path by vainly holding
  2453. * hugetlb_lock
  2454. */
  2455. if (folio_test_hugetlb(folio) && !folio_ref_count(folio)) {
  2456. if (order_is_gigantic(folio_order(folio))) {
  2457. ret = -ENOMEM;
  2458. break;
  2459. }
  2460. ret = alloc_and_dissolve_hugetlb_folio(folio, &list);
  2461. if (ret)
  2462. break;
  2463. putback_movable_pages(&list);
  2464. }
  2465. } else if (PageBuddy(page)) {
  2466. /*
  2467. * Buddy order check without zone lock is unsafe and
  2468. * the order is maybe invalid, but race should be
  2469. * small, and the worst thing is skipping free hugetlb.
  2470. */
  2471. const unsigned int order = buddy_order_unsafe(page);
  2472. if (order <= MAX_PAGE_ORDER)
  2473. nr = 1UL << order;
  2474. }
  2475. start_pfn += nr;
  2476. }
  2477. return ret;
  2478. }
  2479. void wait_for_freed_hugetlb_folios(void)
  2480. {
  2481. if (llist_empty(&hpage_freelist))
  2482. return;
  2483. flush_work(&free_hpage_work);
  2484. }
  2485. typedef enum {
  2486. /*
  2487. * For either 0/1: we checked the per-vma resv map, and one resv
  2488. * count either can be reused (0), or an extra needed (1).
  2489. */
  2490. MAP_CHG_REUSE = 0,
  2491. MAP_CHG_NEEDED = 1,
  2492. /*
  2493. * Cannot use per-vma resv count can be used, hence a new resv
  2494. * count is enforced.
  2495. *
  2496. * NOTE: This is mostly identical to MAP_CHG_NEEDED, except
  2497. * that currently vma_needs_reservation() has an unwanted side
  2498. * effect to either use end() or commit() to complete the
  2499. * transaction. Hence it needs to differentiate from NEEDED.
  2500. */
  2501. MAP_CHG_ENFORCED = 2,
  2502. } map_chg_state;
  2503. /*
  2504. * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW
  2505. * faults of hugetlb private mappings on top of a non-page-cache folio (in
  2506. * which case even if there's a private vma resv map it won't cover such
  2507. * allocation). New call sites should (probably) never set it to true!!
  2508. * When it's set, the allocation will bypass all vma level reservations.
  2509. */
  2510. struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
  2511. unsigned long addr, bool cow_from_owner)
  2512. {
  2513. struct hugepage_subpool *spool = subpool_vma(vma);
  2514. struct hstate *h = hstate_vma(vma);
  2515. struct folio *folio;
  2516. long retval, gbl_chg, gbl_reserve;
  2517. map_chg_state map_chg;
  2518. int ret, idx;
  2519. struct hugetlb_cgroup *h_cg = NULL;
  2520. gfp_t gfp = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
  2521. idx = hstate_index(h);
  2522. /* Whether we need a separate per-vma reservation? */
  2523. if (cow_from_owner) {
  2524. /*
  2525. * Special case! Since it's a CoW on top of a reserved
  2526. * page, the private resv map doesn't count. So it cannot
  2527. * consume the per-vma resv map even if it's reserved.
  2528. */
  2529. map_chg = MAP_CHG_ENFORCED;
  2530. } else {
  2531. /*
  2532. * Examine the region/reserve map to determine if the process
  2533. * has a reservation for the page to be allocated. A return
  2534. * code of zero indicates a reservation exists (no change).
  2535. */
  2536. retval = vma_needs_reservation(h, vma, addr);
  2537. if (retval < 0)
  2538. return ERR_PTR(-ENOMEM);
  2539. map_chg = retval ? MAP_CHG_NEEDED : MAP_CHG_REUSE;
  2540. }
  2541. /*
  2542. * Whether we need a separate global reservation?
  2543. *
  2544. * Processes that did not create the mapping will have no
  2545. * reserves as indicated by the region/reserve map. Check
  2546. * that the allocation will not exceed the subpool limit.
  2547. * Or if it can get one from the pool reservation directly.
  2548. */
  2549. if (map_chg) {
  2550. gbl_chg = hugepage_subpool_get_pages(spool, 1);
  2551. if (gbl_chg < 0)
  2552. goto out_end_reservation;
  2553. } else {
  2554. /*
  2555. * If we have the vma reservation ready, no need for extra
  2556. * global reservation.
  2557. */
  2558. gbl_chg = 0;
  2559. }
  2560. /*
  2561. * If this allocation is not consuming a per-vma reservation,
  2562. * charge the hugetlb cgroup now.
  2563. */
  2564. if (map_chg) {
  2565. ret = hugetlb_cgroup_charge_cgroup_rsvd(
  2566. idx, pages_per_huge_page(h), &h_cg);
  2567. if (ret)
  2568. goto out_subpool_put;
  2569. }
  2570. ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
  2571. if (ret)
  2572. goto out_uncharge_cgroup_reservation;
  2573. spin_lock_irq(&hugetlb_lock);
  2574. /*
  2575. * glb_chg is passed to indicate whether or not a page must be taken
  2576. * from the global free pool (global change). gbl_chg == 0 indicates
  2577. * a reservation exists for the allocation.
  2578. */
  2579. folio = dequeue_hugetlb_folio_vma(h, vma, addr, gbl_chg);
  2580. if (!folio) {
  2581. spin_unlock_irq(&hugetlb_lock);
  2582. folio = alloc_buddy_hugetlb_folio_with_mpol(h, vma, addr);
  2583. if (!folio)
  2584. goto out_uncharge_cgroup;
  2585. spin_lock_irq(&hugetlb_lock);
  2586. list_add(&folio->lru, &h->hugepage_activelist);
  2587. folio_ref_unfreeze(folio, 1);
  2588. /* Fall through */
  2589. }
  2590. /*
  2591. * Either dequeued or buddy-allocated folio needs to add special
  2592. * mark to the folio when it consumes a global reservation.
  2593. */
  2594. if (!gbl_chg) {
  2595. folio_set_hugetlb_restore_reserve(folio);
  2596. h->resv_huge_pages--;
  2597. }
  2598. hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, folio);
  2599. /* If allocation is not consuming a reservation, also store the
  2600. * hugetlb_cgroup pointer on the page.
  2601. */
  2602. if (map_chg) {
  2603. hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
  2604. h_cg, folio);
  2605. }
  2606. spin_unlock_irq(&hugetlb_lock);
  2607. hugetlb_set_folio_subpool(folio, spool);
  2608. if (map_chg != MAP_CHG_ENFORCED) {
  2609. /* commit() is only needed if the map_chg is not enforced */
  2610. retval = vma_commit_reservation(h, vma, addr);
  2611. /*
  2612. * Check for possible race conditions. When it happens..
  2613. * The page was added to the reservation map between
  2614. * vma_needs_reservation and vma_commit_reservation.
  2615. * This indicates a race with hugetlb_reserve_pages.
  2616. * Adjust for the subpool count incremented above AND
  2617. * in hugetlb_reserve_pages for the same page. Also,
  2618. * the reservation count added in hugetlb_reserve_pages
  2619. * no longer applies.
  2620. */
  2621. if (unlikely(map_chg == MAP_CHG_NEEDED && retval == 0)) {
  2622. long rsv_adjust;
  2623. rsv_adjust = hugepage_subpool_put_pages(spool, 1);
  2624. hugetlb_acct_memory(h, -rsv_adjust);
  2625. spin_lock_irq(&hugetlb_lock);
  2626. hugetlb_cgroup_uncharge_folio_rsvd(
  2627. hstate_index(h), pages_per_huge_page(h), folio);
  2628. spin_unlock_irq(&hugetlb_lock);
  2629. }
  2630. }
  2631. ret = mem_cgroup_charge_hugetlb(folio, gfp);
  2632. /*
  2633. * Unconditionally increment NR_HUGETLB here. If it turns out that
  2634. * mem_cgroup_charge_hugetlb failed, then immediately free the page and
  2635. * decrement NR_HUGETLB.
  2636. */
  2637. lruvec_stat_mod_folio(folio, NR_HUGETLB, pages_per_huge_page(h));
  2638. if (ret == -ENOMEM) {
  2639. free_huge_folio(folio);
  2640. return ERR_PTR(-ENOMEM);
  2641. }
  2642. return folio;
  2643. out_uncharge_cgroup:
  2644. hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
  2645. out_uncharge_cgroup_reservation:
  2646. if (map_chg)
  2647. hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
  2648. h_cg);
  2649. out_subpool_put:
  2650. /*
  2651. * put page to subpool iff the quota of subpool's rsv_hpages is used
  2652. * during hugepage_subpool_get_pages.
  2653. */
  2654. if (map_chg && !gbl_chg) {
  2655. gbl_reserve = hugepage_subpool_put_pages(spool, 1);
  2656. hugetlb_acct_memory(h, -gbl_reserve);
  2657. }
  2658. out_end_reservation:
  2659. if (map_chg != MAP_CHG_ENFORCED)
  2660. vma_end_reservation(h, vma, addr);
  2661. return ERR_PTR(-ENOSPC);
  2662. }
  2663. static __init void *alloc_bootmem(struct hstate *h, int nid, bool node_exact)
  2664. {
  2665. struct huge_bootmem_page *m;
  2666. int listnode = nid;
  2667. if (hugetlb_early_cma(h))
  2668. m = hugetlb_cma_alloc_bootmem(h, &listnode, node_exact);
  2669. else {
  2670. if (node_exact)
  2671. m = memblock_alloc_exact_nid_raw(huge_page_size(h),
  2672. huge_page_size(h), 0,
  2673. MEMBLOCK_ALLOC_ACCESSIBLE, nid);
  2674. else {
  2675. m = memblock_alloc_try_nid_raw(huge_page_size(h),
  2676. huge_page_size(h), 0,
  2677. MEMBLOCK_ALLOC_ACCESSIBLE, nid);
  2678. /*
  2679. * For pre-HVO to work correctly, pages need to be on
  2680. * the list for the node they were actually allocated
  2681. * from. That node may be different in the case of
  2682. * fallback by memblock_alloc_try_nid_raw. So,
  2683. * extract the actual node first.
  2684. */
  2685. if (m)
  2686. listnode = early_pfn_to_nid(PHYS_PFN(__pa(m)));
  2687. }
  2688. if (m) {
  2689. m->flags = 0;
  2690. m->cma = NULL;
  2691. }
  2692. }
  2693. if (m) {
  2694. /*
  2695. * Use the beginning of the huge page to store the
  2696. * huge_bootmem_page struct (until gather_bootmem
  2697. * puts them into the mem_map).
  2698. *
  2699. * Put them into a private list first because mem_map
  2700. * is not up yet.
  2701. */
  2702. INIT_LIST_HEAD(&m->list);
  2703. list_add(&m->list, &huge_boot_pages[listnode]);
  2704. m->hstate = h;
  2705. }
  2706. return m;
  2707. }
  2708. int alloc_bootmem_huge_page(struct hstate *h, int nid)
  2709. __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
  2710. int __alloc_bootmem_huge_page(struct hstate *h, int nid)
  2711. {
  2712. struct huge_bootmem_page *m = NULL; /* initialize for clang */
  2713. int nr_nodes, node = nid;
  2714. /* do node specific alloc */
  2715. if (nid != NUMA_NO_NODE) {
  2716. m = alloc_bootmem(h, node, true);
  2717. if (!m)
  2718. return 0;
  2719. goto found;
  2720. }
  2721. /* allocate from next node when distributing huge pages */
  2722. for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node,
  2723. &hugetlb_bootmem_nodes) {
  2724. m = alloc_bootmem(h, node, false);
  2725. if (!m)
  2726. return 0;
  2727. goto found;
  2728. }
  2729. found:
  2730. /*
  2731. * Only initialize the head struct page in memmap_init_reserved_pages,
  2732. * rest of the struct pages will be initialized by the HugeTLB
  2733. * subsystem itself.
  2734. * The head struct page is used to get folio information by the HugeTLB
  2735. * subsystem like zone id and node id.
  2736. */
  2737. memblock_reserved_mark_noinit(__pa((void *)m + PAGE_SIZE),
  2738. huge_page_size(h) - PAGE_SIZE);
  2739. return 1;
  2740. }
  2741. /* Initialize [start_page:end_page_number] tail struct pages of a hugepage */
  2742. static void __init hugetlb_folio_init_tail_vmemmap(struct folio *folio,
  2743. unsigned long start_page_number,
  2744. unsigned long end_page_number)
  2745. {
  2746. enum zone_type zone = folio_zonenum(folio);
  2747. int nid = folio_nid(folio);
  2748. struct page *page = folio_page(folio, start_page_number);
  2749. unsigned long head_pfn = folio_pfn(folio);
  2750. unsigned long pfn, end_pfn = head_pfn + end_page_number;
  2751. /*
  2752. * As we marked all tail pages with memblock_reserved_mark_noinit(),
  2753. * we must initialize them ourselves here.
  2754. */
  2755. for (pfn = head_pfn + start_page_number; pfn < end_pfn; page++, pfn++) {
  2756. __init_single_page(page, pfn, zone, nid);
  2757. prep_compound_tail((struct page *)folio, pfn - head_pfn);
  2758. set_page_count(page, 0);
  2759. }
  2760. }
  2761. static void __init hugetlb_folio_init_vmemmap(struct folio *folio,
  2762. struct hstate *h,
  2763. unsigned long nr_pages)
  2764. {
  2765. int ret;
  2766. /*
  2767. * This is an open-coded prep_compound_page() whereby we avoid
  2768. * walking pages twice by initializing/preparing+freezing them in the
  2769. * same go.
  2770. */
  2771. __folio_clear_reserved(folio);
  2772. __folio_set_head(folio);
  2773. ret = folio_ref_freeze(folio, 1);
  2774. VM_BUG_ON(!ret);
  2775. hugetlb_folio_init_tail_vmemmap(folio, 1, nr_pages);
  2776. prep_compound_head(&folio->page, huge_page_order(h));
  2777. }
  2778. static bool __init hugetlb_bootmem_page_prehvo(struct huge_bootmem_page *m)
  2779. {
  2780. return m->flags & HUGE_BOOTMEM_HVO;
  2781. }
  2782. static bool __init hugetlb_bootmem_page_earlycma(struct huge_bootmem_page *m)
  2783. {
  2784. return m->flags & HUGE_BOOTMEM_CMA;
  2785. }
  2786. /*
  2787. * memblock-allocated pageblocks might not have the migrate type set
  2788. * if marked with the 'noinit' flag. Set it to the default (MIGRATE_MOVABLE)
  2789. * here, or MIGRATE_CMA if this was a page allocated through an early CMA
  2790. * reservation.
  2791. *
  2792. * In case of vmemmap optimized folios, the tail vmemmap pages are mapped
  2793. * read-only, but that's ok - for sparse vmemmap this does not write to
  2794. * the page structure.
  2795. */
  2796. static void __init hugetlb_bootmem_init_migratetype(struct folio *folio,
  2797. struct hstate *h)
  2798. {
  2799. unsigned long nr_pages = pages_per_huge_page(h), i;
  2800. WARN_ON_ONCE(!pageblock_aligned(folio_pfn(folio)));
  2801. for (i = 0; i < nr_pages; i += pageblock_nr_pages) {
  2802. if (folio_test_hugetlb_cma(folio))
  2803. init_cma_pageblock(folio_page(folio, i));
  2804. else
  2805. init_pageblock_migratetype(folio_page(folio, i),
  2806. MIGRATE_MOVABLE, false);
  2807. }
  2808. }
  2809. static void __init prep_and_add_bootmem_folios(struct hstate *h,
  2810. struct list_head *folio_list)
  2811. {
  2812. unsigned long flags;
  2813. struct folio *folio, *tmp_f;
  2814. /* Send list for bulk vmemmap optimization processing */
  2815. hugetlb_vmemmap_optimize_bootmem_folios(h, folio_list);
  2816. list_for_each_entry_safe(folio, tmp_f, folio_list, lru) {
  2817. if (!folio_test_hugetlb_vmemmap_optimized(folio)) {
  2818. /*
  2819. * If HVO fails, initialize all tail struct pages
  2820. * We do not worry about potential long lock hold
  2821. * time as this is early in boot and there should
  2822. * be no contention.
  2823. */
  2824. hugetlb_folio_init_tail_vmemmap(folio,
  2825. HUGETLB_VMEMMAP_RESERVE_PAGES,
  2826. pages_per_huge_page(h));
  2827. }
  2828. hugetlb_bootmem_init_migratetype(folio, h);
  2829. /* Subdivide locks to achieve better parallel performance */
  2830. spin_lock_irqsave(&hugetlb_lock, flags);
  2831. account_new_hugetlb_folio(h, folio);
  2832. enqueue_hugetlb_folio(h, folio);
  2833. spin_unlock_irqrestore(&hugetlb_lock, flags);
  2834. }
  2835. }
  2836. bool __init hugetlb_bootmem_page_zones_valid(int nid,
  2837. struct huge_bootmem_page *m)
  2838. {
  2839. unsigned long start_pfn;
  2840. bool valid;
  2841. if (m->flags & HUGE_BOOTMEM_ZONES_VALID) {
  2842. /*
  2843. * Already validated, skip check.
  2844. */
  2845. return true;
  2846. }
  2847. if (hugetlb_bootmem_page_earlycma(m)) {
  2848. valid = cma_validate_zones(m->cma);
  2849. goto out;
  2850. }
  2851. start_pfn = virt_to_phys(m) >> PAGE_SHIFT;
  2852. valid = !pfn_range_intersects_zones(nid, start_pfn,
  2853. pages_per_huge_page(m->hstate));
  2854. out:
  2855. if (!valid)
  2856. hstate_boot_nrinvalid[hstate_index(m->hstate)]++;
  2857. return valid;
  2858. }
  2859. /*
  2860. * Free a bootmem page that was found to be invalid (intersecting with
  2861. * multiple zones).
  2862. *
  2863. * Since it intersects with multiple zones, we can't just do a free
  2864. * operation on all pages at once, but instead have to walk all
  2865. * pages, freeing them one by one.
  2866. */
  2867. static void __init hugetlb_bootmem_free_invalid_page(int nid, struct page *page,
  2868. struct hstate *h)
  2869. {
  2870. unsigned long npages = pages_per_huge_page(h);
  2871. unsigned long pfn;
  2872. while (npages--) {
  2873. pfn = page_to_pfn(page);
  2874. __init_page_from_nid(pfn, nid);
  2875. free_reserved_page(page);
  2876. page++;
  2877. }
  2878. }
  2879. /*
  2880. * Put bootmem huge pages into the standard lists after mem_map is up.
  2881. * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages.
  2882. */
  2883. static void __init gather_bootmem_prealloc_node(unsigned long nid)
  2884. {
  2885. LIST_HEAD(folio_list);
  2886. struct huge_bootmem_page *m, *tm;
  2887. struct hstate *h = NULL, *prev_h = NULL;
  2888. list_for_each_entry_safe(m, tm, &huge_boot_pages[nid], list) {
  2889. struct page *page = virt_to_page(m);
  2890. struct folio *folio = (void *)page;
  2891. h = m->hstate;
  2892. if (!hugetlb_bootmem_page_zones_valid(nid, m)) {
  2893. /*
  2894. * Can't use this page. Initialize the
  2895. * page structures if that hasn't already
  2896. * been done, and give them to the page
  2897. * allocator.
  2898. */
  2899. hugetlb_bootmem_free_invalid_page(nid, page, h);
  2900. continue;
  2901. }
  2902. /*
  2903. * It is possible to have multiple huge page sizes (hstates)
  2904. * in this list. If so, process each size separately.
  2905. */
  2906. if (h != prev_h && prev_h != NULL)
  2907. prep_and_add_bootmem_folios(prev_h, &folio_list);
  2908. prev_h = h;
  2909. VM_BUG_ON(!hstate_is_gigantic(h));
  2910. WARN_ON(folio_ref_count(folio) != 1);
  2911. hugetlb_folio_init_vmemmap(folio, h,
  2912. HUGETLB_VMEMMAP_RESERVE_PAGES);
  2913. init_new_hugetlb_folio(folio);
  2914. if (hugetlb_bootmem_page_prehvo(m))
  2915. /*
  2916. * If pre-HVO was done, just set the
  2917. * flag, the HVO code will then skip
  2918. * this folio.
  2919. */
  2920. folio_set_hugetlb_vmemmap_optimized(folio);
  2921. if (hugetlb_bootmem_page_earlycma(m))
  2922. folio_set_hugetlb_cma(folio);
  2923. list_add(&folio->lru, &folio_list);
  2924. /*
  2925. * We need to restore the 'stolen' pages to totalram_pages
  2926. * in order to fix confusing memory reports from free(1) and
  2927. * other side-effects, like CommitLimit going negative.
  2928. *
  2929. * For CMA pages, this is done in init_cma_pageblock
  2930. * (via hugetlb_bootmem_init_migratetype), so skip it here.
  2931. */
  2932. if (!folio_test_hugetlb_cma(folio))
  2933. adjust_managed_page_count(page, pages_per_huge_page(h));
  2934. cond_resched();
  2935. }
  2936. prep_and_add_bootmem_folios(h, &folio_list);
  2937. }
  2938. static void __init gather_bootmem_prealloc_parallel(unsigned long start,
  2939. unsigned long end, void *arg)
  2940. {
  2941. int nid;
  2942. for (nid = start; nid < end; nid++)
  2943. gather_bootmem_prealloc_node(nid);
  2944. }
  2945. static void __init gather_bootmem_prealloc(void)
  2946. {
  2947. struct padata_mt_job job = {
  2948. .thread_fn = gather_bootmem_prealloc_parallel,
  2949. .fn_arg = NULL,
  2950. .start = 0,
  2951. .size = nr_node_ids,
  2952. .align = 1,
  2953. .min_chunk = 1,
  2954. .max_threads = num_node_state(N_MEMORY),
  2955. .numa_aware = true,
  2956. };
  2957. padata_do_multithreaded(&job);
  2958. }
  2959. static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
  2960. {
  2961. unsigned long i;
  2962. char buf[32];
  2963. LIST_HEAD(folio_list);
  2964. for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
  2965. if (hstate_is_gigantic(h)) {
  2966. if (!alloc_bootmem_huge_page(h, nid))
  2967. break;
  2968. } else {
  2969. struct folio *folio;
  2970. gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
  2971. folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
  2972. &node_states[N_MEMORY], NULL);
  2973. if (!folio && !list_empty(&folio_list) &&
  2974. hugetlb_vmemmap_optimizable_size(h)) {
  2975. prep_and_add_allocated_folios(h, &folio_list);
  2976. INIT_LIST_HEAD(&folio_list);
  2977. folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
  2978. &node_states[N_MEMORY], NULL);
  2979. }
  2980. if (!folio)
  2981. break;
  2982. list_add(&folio->lru, &folio_list);
  2983. }
  2984. cond_resched();
  2985. }
  2986. if (!list_empty(&folio_list))
  2987. prep_and_add_allocated_folios(h, &folio_list);
  2988. if (i == h->max_huge_pages_node[nid])
  2989. return;
  2990. string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
  2991. pr_warn("HugeTLB: allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n",
  2992. h->max_huge_pages_node[nid], buf, nid, i);
  2993. h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
  2994. h->max_huge_pages_node[nid] = i;
  2995. }
  2996. static bool __init hugetlb_hstate_alloc_pages_specific_nodes(struct hstate *h)
  2997. {
  2998. int i;
  2999. bool node_specific_alloc = false;
  3000. for_each_online_node(i) {
  3001. if (h->max_huge_pages_node[i] > 0) {
  3002. hugetlb_hstate_alloc_pages_onenode(h, i);
  3003. node_specific_alloc = true;
  3004. }
  3005. }
  3006. return node_specific_alloc;
  3007. }
  3008. static void __init hugetlb_hstate_alloc_pages_errcheck(unsigned long allocated, struct hstate *h)
  3009. {
  3010. if (allocated < h->max_huge_pages) {
  3011. char buf[32];
  3012. string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
  3013. pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
  3014. h->max_huge_pages, buf, allocated);
  3015. h->max_huge_pages = allocated;
  3016. }
  3017. }
  3018. static void __init hugetlb_pages_alloc_boot_node(unsigned long start, unsigned long end, void *arg)
  3019. {
  3020. struct hstate *h = (struct hstate *)arg;
  3021. int i, num = end - start;
  3022. nodemask_t node_alloc_noretry;
  3023. LIST_HEAD(folio_list);
  3024. int next_node = first_online_node;
  3025. /* Bit mask controlling how hard we retry per-node allocations.*/
  3026. nodes_clear(node_alloc_noretry);
  3027. for (i = 0; i < num; ++i) {
  3028. struct folio *folio;
  3029. if (hugetlb_vmemmap_optimizable_size(h) &&
  3030. (si_mem_available() == 0) && !list_empty(&folio_list)) {
  3031. prep_and_add_allocated_folios(h, &folio_list);
  3032. INIT_LIST_HEAD(&folio_list);
  3033. }
  3034. folio = alloc_pool_huge_folio(h, &node_states[N_MEMORY],
  3035. &node_alloc_noretry, &next_node);
  3036. if (!folio)
  3037. break;
  3038. list_move(&folio->lru, &folio_list);
  3039. cond_resched();
  3040. }
  3041. prep_and_add_allocated_folios(h, &folio_list);
  3042. }
  3043. static unsigned long __init hugetlb_gigantic_pages_alloc_boot(struct hstate *h)
  3044. {
  3045. unsigned long i;
  3046. for (i = 0; i < h->max_huge_pages; ++i) {
  3047. if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
  3048. break;
  3049. cond_resched();
  3050. }
  3051. return i;
  3052. }
  3053. static unsigned long __init hugetlb_pages_alloc_boot(struct hstate *h)
  3054. {
  3055. struct padata_mt_job job = {
  3056. .fn_arg = h,
  3057. .align = 1,
  3058. .numa_aware = true
  3059. };
  3060. unsigned long jiffies_start;
  3061. unsigned long jiffies_end;
  3062. unsigned long remaining;
  3063. job.thread_fn = hugetlb_pages_alloc_boot_node;
  3064. /*
  3065. * job.max_threads is 25% of the available cpu threads by default.
  3066. *
  3067. * On large servers with terabytes of memory, huge page allocation
  3068. * can consume a considerably amount of time.
  3069. *
  3070. * Tests below show how long it takes to allocate 1 TiB of memory with 2MiB huge pages.
  3071. * 2MiB huge pages. Using more threads can significantly improve allocation time.
  3072. *
  3073. * +-----------------------+-------+-------+-------+-------+-------+
  3074. * | threads | 8 | 16 | 32 | 64 | 128 |
  3075. * +-----------------------+-------+-------+-------+-------+-------+
  3076. * | skylake 144 cpus | 44s | 22s | 16s | 19s | 20s |
  3077. * | cascade lake 192 cpus | 39s | 20s | 11s | 10s | 9s |
  3078. * +-----------------------+-------+-------+-------+-------+-------+
  3079. */
  3080. if (hugepage_allocation_threads == 0) {
  3081. hugepage_allocation_threads = num_online_cpus() / 4;
  3082. hugepage_allocation_threads = max(hugepage_allocation_threads, 1);
  3083. }
  3084. job.max_threads = hugepage_allocation_threads;
  3085. jiffies_start = jiffies;
  3086. do {
  3087. remaining = h->max_huge_pages - h->nr_huge_pages;
  3088. job.start = h->nr_huge_pages;
  3089. job.size = remaining;
  3090. job.min_chunk = remaining / hugepage_allocation_threads;
  3091. padata_do_multithreaded(&job);
  3092. if (h->nr_huge_pages == h->max_huge_pages)
  3093. break;
  3094. /*
  3095. * Retry only if the vmemmap optimization might have been able to free
  3096. * some memory back to the system.
  3097. */
  3098. if (!hugetlb_vmemmap_optimizable(h))
  3099. break;
  3100. /* Continue if progress was made in last iteration */
  3101. } while (remaining != (h->max_huge_pages - h->nr_huge_pages));
  3102. jiffies_end = jiffies;
  3103. pr_info("HugeTLB: allocation took %dms with hugepage_allocation_threads=%ld\n",
  3104. jiffies_to_msecs(jiffies_end - jiffies_start),
  3105. hugepage_allocation_threads);
  3106. return h->nr_huge_pages;
  3107. }
  3108. /*
  3109. * NOTE: this routine is called in different contexts for gigantic and
  3110. * non-gigantic pages.
  3111. * - For gigantic pages, this is called early in the boot process and
  3112. * pages are allocated from memblock allocated or something similar.
  3113. * Gigantic pages are actually added to pools later with the routine
  3114. * gather_bootmem_prealloc.
  3115. * - For non-gigantic pages, this is called later in the boot process after
  3116. * all of mm is up and functional. Pages are allocated from buddy and
  3117. * then added to hugetlb pools.
  3118. */
  3119. static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
  3120. {
  3121. unsigned long allocated;
  3122. /*
  3123. * Skip gigantic hugepages allocation if early CMA
  3124. * reservations are not available.
  3125. */
  3126. if (hstate_is_gigantic(h) && hugetlb_cma_total_size() &&
  3127. !hugetlb_early_cma(h)) {
  3128. pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
  3129. return;
  3130. }
  3131. if (!h->max_huge_pages)
  3132. return;
  3133. /* do node specific alloc */
  3134. if (hugetlb_hstate_alloc_pages_specific_nodes(h))
  3135. return;
  3136. /* below will do all node balanced alloc */
  3137. if (hstate_is_gigantic(h))
  3138. allocated = hugetlb_gigantic_pages_alloc_boot(h);
  3139. else
  3140. allocated = hugetlb_pages_alloc_boot(h);
  3141. hugetlb_hstate_alloc_pages_errcheck(allocated, h);
  3142. }
  3143. static void __init hugetlb_init_hstates(void)
  3144. {
  3145. struct hstate *h, *h2;
  3146. for_each_hstate(h) {
  3147. /*
  3148. * Always reset to first_memory_node here, even if
  3149. * next_nid_to_alloc was set before - we can't
  3150. * reference hugetlb_bootmem_nodes after init, and
  3151. * first_memory_node is right for all further allocations.
  3152. */
  3153. h->next_nid_to_alloc = first_memory_node;
  3154. h->next_nid_to_free = first_memory_node;
  3155. /* oversize hugepages were init'ed in early boot */
  3156. if (!hstate_is_gigantic(h))
  3157. hugetlb_hstate_alloc_pages(h);
  3158. /*
  3159. * Set demote order for each hstate. Note that
  3160. * h->demote_order is initially 0.
  3161. * - We can not demote gigantic pages if runtime freeing
  3162. * is not supported, so skip this.
  3163. * - If CMA allocation is possible, we can not demote
  3164. * HUGETLB_PAGE_ORDER or smaller size pages.
  3165. */
  3166. if (hstate_is_gigantic_no_runtime(h))
  3167. continue;
  3168. if (hugetlb_cma_total_size() && h->order <= HUGETLB_PAGE_ORDER)
  3169. continue;
  3170. for_each_hstate(h2) {
  3171. if (h2 == h)
  3172. continue;
  3173. if (h2->order < h->order &&
  3174. h2->order > h->demote_order)
  3175. h->demote_order = h2->order;
  3176. }
  3177. }
  3178. }
  3179. static void __init report_hugepages(void)
  3180. {
  3181. struct hstate *h;
  3182. unsigned long nrinvalid;
  3183. for_each_hstate(h) {
  3184. char buf[32];
  3185. nrinvalid = hstate_boot_nrinvalid[hstate_index(h)];
  3186. h->max_huge_pages -= nrinvalid;
  3187. string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
  3188. pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
  3189. buf, h->nr_huge_pages);
  3190. if (nrinvalid)
  3191. pr_info("HugeTLB: %s page size: %lu invalid page%s discarded\n",
  3192. buf, nrinvalid, str_plural(nrinvalid));
  3193. pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
  3194. hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
  3195. }
  3196. }
  3197. #ifdef CONFIG_HIGHMEM
  3198. static void try_to_free_low(struct hstate *h, unsigned long count,
  3199. nodemask_t *nodes_allowed)
  3200. {
  3201. int i;
  3202. LIST_HEAD(page_list);
  3203. lockdep_assert_held(&hugetlb_lock);
  3204. if (hstate_is_gigantic(h))
  3205. return;
  3206. /*
  3207. * Collect pages to be freed on a list, and free after dropping lock
  3208. */
  3209. for_each_node_mask(i, *nodes_allowed) {
  3210. struct folio *folio, *next;
  3211. struct list_head *freel = &h->hugepage_freelists[i];
  3212. list_for_each_entry_safe(folio, next, freel, lru) {
  3213. if (count >= h->nr_huge_pages)
  3214. goto out;
  3215. if (folio_test_highmem(folio))
  3216. continue;
  3217. remove_hugetlb_folio(h, folio, false);
  3218. list_add(&folio->lru, &page_list);
  3219. }
  3220. }
  3221. out:
  3222. spin_unlock_irq(&hugetlb_lock);
  3223. update_and_free_pages_bulk(h, &page_list);
  3224. spin_lock_irq(&hugetlb_lock);
  3225. }
  3226. #else
  3227. static inline void try_to_free_low(struct hstate *h, unsigned long count,
  3228. nodemask_t *nodes_allowed)
  3229. {
  3230. }
  3231. #endif
  3232. /*
  3233. * Increment or decrement surplus_huge_pages. Keep node-specific counters
  3234. * balanced by operating on them in a round-robin fashion.
  3235. * Returns 1 if an adjustment was made.
  3236. */
  3237. static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
  3238. int delta)
  3239. {
  3240. int nr_nodes, node;
  3241. lockdep_assert_held(&hugetlb_lock);
  3242. VM_BUG_ON(delta != -1 && delta != 1);
  3243. if (delta < 0) {
  3244. for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node, nodes_allowed) {
  3245. if (h->surplus_huge_pages_node[node])
  3246. goto found;
  3247. }
  3248. } else {
  3249. for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
  3250. if (h->surplus_huge_pages_node[node] <
  3251. h->nr_huge_pages_node[node])
  3252. goto found;
  3253. }
  3254. }
  3255. return 0;
  3256. found:
  3257. h->surplus_huge_pages += delta;
  3258. h->surplus_huge_pages_node[node] += delta;
  3259. return 1;
  3260. }
  3261. #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
  3262. static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
  3263. nodemask_t *nodes_allowed)
  3264. {
  3265. unsigned long persistent_free_count;
  3266. unsigned long min_count;
  3267. unsigned long allocated;
  3268. struct folio *folio;
  3269. LIST_HEAD(page_list);
  3270. NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
  3271. /*
  3272. * Bit mask controlling how hard we retry per-node allocations.
  3273. * If we can not allocate the bit mask, do not attempt to allocate
  3274. * the requested huge pages.
  3275. */
  3276. if (node_alloc_noretry)
  3277. nodes_clear(*node_alloc_noretry);
  3278. else
  3279. return -ENOMEM;
  3280. /*
  3281. * resize_lock mutex prevents concurrent adjustments to number of
  3282. * pages in hstate via the proc/sysfs interfaces.
  3283. */
  3284. mutex_lock(&h->resize_lock);
  3285. flush_free_hpage_work(h);
  3286. spin_lock_irq(&hugetlb_lock);
  3287. /*
  3288. * Check for a node specific request.
  3289. * Changing node specific huge page count may require a corresponding
  3290. * change to the global count. In any case, the passed node mask
  3291. * (nodes_allowed) will restrict alloc/free to the specified node.
  3292. */
  3293. if (nid != NUMA_NO_NODE) {
  3294. unsigned long old_count = count;
  3295. count += persistent_huge_pages(h) -
  3296. (h->nr_huge_pages_node[nid] -
  3297. h->surplus_huge_pages_node[nid]);
  3298. /*
  3299. * User may have specified a large count value which caused the
  3300. * above calculation to overflow. In this case, they wanted
  3301. * to allocate as many huge pages as possible. Set count to
  3302. * largest possible value to align with their intention.
  3303. */
  3304. if (count < old_count)
  3305. count = ULONG_MAX;
  3306. }
  3307. /*
  3308. * Gigantic pages runtime allocation depend on the capability for large
  3309. * page range allocation.
  3310. * If the system does not provide this feature, return an error when
  3311. * the user tries to allocate gigantic pages but let the user free the
  3312. * boottime allocated gigantic pages.
  3313. */
  3314. if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
  3315. if (count > persistent_huge_pages(h)) {
  3316. spin_unlock_irq(&hugetlb_lock);
  3317. mutex_unlock(&h->resize_lock);
  3318. NODEMASK_FREE(node_alloc_noretry);
  3319. return -EINVAL;
  3320. }
  3321. /* Fall through to decrease pool */
  3322. }
  3323. /*
  3324. * Increase the pool size
  3325. * First take pages out of surplus state. Then make up the
  3326. * remaining difference by allocating fresh huge pages.
  3327. *
  3328. * We might race with alloc_surplus_hugetlb_folio() here and be unable
  3329. * to convert a surplus huge page to a normal huge page. That is
  3330. * not critical, though, it just means the overall size of the
  3331. * pool might be one hugepage larger than it needs to be, but
  3332. * within all the constraints specified by the sysctls.
  3333. */
  3334. while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
  3335. if (!adjust_pool_surplus(h, nodes_allowed, -1))
  3336. break;
  3337. }
  3338. allocated = 0;
  3339. while (count > (persistent_huge_pages(h) + allocated)) {
  3340. /*
  3341. * If this allocation races such that we no longer need the
  3342. * page, free_huge_folio will handle it by freeing the page
  3343. * and reducing the surplus.
  3344. */
  3345. spin_unlock_irq(&hugetlb_lock);
  3346. /* yield cpu to avoid soft lockup */
  3347. cond_resched();
  3348. folio = alloc_pool_huge_folio(h, nodes_allowed,
  3349. node_alloc_noretry,
  3350. &h->next_nid_to_alloc);
  3351. if (!folio) {
  3352. prep_and_add_allocated_folios(h, &page_list);
  3353. spin_lock_irq(&hugetlb_lock);
  3354. goto out;
  3355. }
  3356. list_add(&folio->lru, &page_list);
  3357. allocated++;
  3358. /* Bail for signals. Probably ctrl-c from user */
  3359. if (signal_pending(current)) {
  3360. prep_and_add_allocated_folios(h, &page_list);
  3361. spin_lock_irq(&hugetlb_lock);
  3362. goto out;
  3363. }
  3364. spin_lock_irq(&hugetlb_lock);
  3365. }
  3366. /* Add allocated pages to the pool */
  3367. if (!list_empty(&page_list)) {
  3368. spin_unlock_irq(&hugetlb_lock);
  3369. prep_and_add_allocated_folios(h, &page_list);
  3370. spin_lock_irq(&hugetlb_lock);
  3371. }
  3372. /*
  3373. * Decrease the pool size
  3374. * First return free pages to the buddy allocator (being careful
  3375. * to keep enough around to satisfy reservations). Then place
  3376. * pages into surplus state as needed so the pool will shrink
  3377. * to the desired size as pages become free.
  3378. *
  3379. * By placing pages into the surplus state independent of the
  3380. * overcommit value, we are allowing the surplus pool size to
  3381. * exceed overcommit. There are few sane options here. Since
  3382. * alloc_surplus_hugetlb_folio() is checking the global counter,
  3383. * though, we'll note that we're not allowed to exceed surplus
  3384. * and won't grow the pool anywhere else. Not until one of the
  3385. * sysctls are changed, or the surplus pages go out of use.
  3386. *
  3387. * min_count is the expected number of persistent pages, we
  3388. * shouldn't calculate min_count by using
  3389. * resv_huge_pages + persistent_huge_pages() - free_huge_pages,
  3390. * because there may exist free surplus huge pages, and this will
  3391. * lead to subtracting twice. Free surplus huge pages come from HVO
  3392. * failing to restore vmemmap, see comments in the callers of
  3393. * hugetlb_vmemmap_restore_folio(). Thus, we should calculate
  3394. * persistent free count first.
  3395. */
  3396. persistent_free_count = h->free_huge_pages;
  3397. if (h->free_huge_pages > persistent_huge_pages(h)) {
  3398. if (h->free_huge_pages > h->surplus_huge_pages)
  3399. persistent_free_count -= h->surplus_huge_pages;
  3400. else
  3401. persistent_free_count = 0;
  3402. }
  3403. min_count = h->resv_huge_pages + persistent_huge_pages(h) - persistent_free_count;
  3404. min_count = max(count, min_count);
  3405. try_to_free_low(h, min_count, nodes_allowed);
  3406. /*
  3407. * Collect pages to be removed on list without dropping lock
  3408. */
  3409. while (min_count < persistent_huge_pages(h)) {
  3410. folio = remove_pool_hugetlb_folio(h, nodes_allowed, 0);
  3411. if (!folio)
  3412. break;
  3413. list_add(&folio->lru, &page_list);
  3414. }
  3415. /* free the pages after dropping lock */
  3416. spin_unlock_irq(&hugetlb_lock);
  3417. update_and_free_pages_bulk(h, &page_list);
  3418. flush_free_hpage_work(h);
  3419. spin_lock_irq(&hugetlb_lock);
  3420. while (count < persistent_huge_pages(h)) {
  3421. if (!adjust_pool_surplus(h, nodes_allowed, 1))
  3422. break;
  3423. }
  3424. out:
  3425. h->max_huge_pages = persistent_huge_pages(h);
  3426. spin_unlock_irq(&hugetlb_lock);
  3427. mutex_unlock(&h->resize_lock);
  3428. NODEMASK_FREE(node_alloc_noretry);
  3429. return 0;
  3430. }
  3431. static long demote_free_hugetlb_folios(struct hstate *src, struct hstate *dst,
  3432. struct list_head *src_list)
  3433. {
  3434. long rc;
  3435. struct folio *folio, *next;
  3436. LIST_HEAD(dst_list);
  3437. LIST_HEAD(ret_list);
  3438. rc = hugetlb_vmemmap_restore_folios(src, src_list, &ret_list);
  3439. list_splice_init(&ret_list, src_list);
  3440. /*
  3441. * Taking target hstate mutex synchronizes with set_max_huge_pages.
  3442. * Without the mutex, pages added to target hstate could be marked
  3443. * as surplus.
  3444. *
  3445. * Note that we already hold src->resize_lock. To prevent deadlock,
  3446. * use the convention of always taking larger size hstate mutex first.
  3447. */
  3448. mutex_lock(&dst->resize_lock);
  3449. list_for_each_entry_safe(folio, next, src_list, lru) {
  3450. int i;
  3451. bool cma;
  3452. if (folio_test_hugetlb_vmemmap_optimized(folio))
  3453. continue;
  3454. cma = folio_test_hugetlb_cma(folio);
  3455. list_del(&folio->lru);
  3456. split_page_owner(&folio->page, huge_page_order(src), huge_page_order(dst));
  3457. pgalloc_tag_split(folio, huge_page_order(src), huge_page_order(dst));
  3458. for (i = 0; i < pages_per_huge_page(src); i += pages_per_huge_page(dst)) {
  3459. struct page *page = folio_page(folio, i);
  3460. /* Careful: see __split_huge_page_tail() */
  3461. struct folio *new_folio = (struct folio *)page;
  3462. clear_compound_head(page);
  3463. prep_compound_page(page, dst->order);
  3464. new_folio->mapping = NULL;
  3465. init_new_hugetlb_folio(new_folio);
  3466. /* Copy the CMA flag so that it is freed correctly */
  3467. if (cma)
  3468. folio_set_hugetlb_cma(new_folio);
  3469. list_add(&new_folio->lru, &dst_list);
  3470. }
  3471. }
  3472. prep_and_add_allocated_folios(dst, &dst_list);
  3473. mutex_unlock(&dst->resize_lock);
  3474. return rc;
  3475. }
  3476. long demote_pool_huge_page(struct hstate *src, nodemask_t *nodes_allowed,
  3477. unsigned long nr_to_demote)
  3478. __must_hold(&hugetlb_lock)
  3479. {
  3480. int nr_nodes, node;
  3481. struct hstate *dst;
  3482. long rc = 0;
  3483. long nr_demoted = 0;
  3484. lockdep_assert_held(&hugetlb_lock);
  3485. /* We should never get here if no demote order */
  3486. if (!src->demote_order) {
  3487. pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
  3488. return -EINVAL; /* internal error */
  3489. }
  3490. dst = size_to_hstate(PAGE_SIZE << src->demote_order);
  3491. for_each_node_mask_to_free(src, nr_nodes, node, nodes_allowed) {
  3492. LIST_HEAD(list);
  3493. struct folio *folio, *next;
  3494. list_for_each_entry_safe(folio, next, &src->hugepage_freelists[node], lru) {
  3495. if (folio_test_hwpoison(folio))
  3496. continue;
  3497. remove_hugetlb_folio(src, folio, false);
  3498. list_add(&folio->lru, &list);
  3499. if (++nr_demoted == nr_to_demote)
  3500. break;
  3501. }
  3502. spin_unlock_irq(&hugetlb_lock);
  3503. rc = demote_free_hugetlb_folios(src, dst, &list);
  3504. spin_lock_irq(&hugetlb_lock);
  3505. list_for_each_entry_safe(folio, next, &list, lru) {
  3506. list_del(&folio->lru);
  3507. add_hugetlb_folio(src, folio, false);
  3508. nr_demoted--;
  3509. }
  3510. if (rc < 0 || nr_demoted == nr_to_demote)
  3511. break;
  3512. }
  3513. /*
  3514. * Not absolutely necessary, but for consistency update max_huge_pages
  3515. * based on pool changes for the demoted page.
  3516. */
  3517. src->max_huge_pages -= nr_demoted;
  3518. dst->max_huge_pages += nr_demoted << (huge_page_order(src) - huge_page_order(dst));
  3519. if (rc < 0)
  3520. return rc;
  3521. if (nr_demoted)
  3522. return nr_demoted;
  3523. /*
  3524. * Only way to get here is if all pages on free lists are poisoned.
  3525. * Return -EBUSY so that caller will not retry.
  3526. */
  3527. return -EBUSY;
  3528. }
  3529. ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
  3530. struct hstate *h, int nid,
  3531. unsigned long count, size_t len)
  3532. {
  3533. int err;
  3534. nodemask_t nodes_allowed, *n_mask;
  3535. if (hstate_is_gigantic_no_runtime(h))
  3536. return -EINVAL;
  3537. if (nid == NUMA_NO_NODE) {
  3538. /*
  3539. * global hstate attribute
  3540. */
  3541. if (!(obey_mempolicy &&
  3542. init_nodemask_of_mempolicy(&nodes_allowed)))
  3543. n_mask = &node_states[N_MEMORY];
  3544. else
  3545. n_mask = &nodes_allowed;
  3546. } else {
  3547. /*
  3548. * Node specific request. count adjustment happens in
  3549. * set_max_huge_pages() after acquiring hugetlb_lock.
  3550. */
  3551. init_nodemask_of_node(&nodes_allowed, nid);
  3552. n_mask = &nodes_allowed;
  3553. }
  3554. err = set_max_huge_pages(h, count, nid, n_mask);
  3555. return err ? err : len;
  3556. }
  3557. static int __init hugetlb_init(void)
  3558. {
  3559. int i;
  3560. BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
  3561. __NR_HPAGEFLAGS);
  3562. BUILD_BUG_ON_INVALID(HUGETLB_PAGE_ORDER > MAX_FOLIO_ORDER);
  3563. if (!hugepages_supported()) {
  3564. if (hugetlb_max_hstate || default_hstate_max_huge_pages)
  3565. pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
  3566. return 0;
  3567. }
  3568. /*
  3569. * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
  3570. * architectures depend on setup being done here.
  3571. */
  3572. hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
  3573. if (!parsed_default_hugepagesz) {
  3574. /*
  3575. * If we did not parse a default huge page size, set
  3576. * default_hstate_idx to HPAGE_SIZE hstate. And, if the
  3577. * number of huge pages for this default size was implicitly
  3578. * specified, set that here as well.
  3579. * Note that the implicit setting will overwrite an explicit
  3580. * setting. A warning will be printed in this case.
  3581. */
  3582. default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
  3583. if (default_hstate_max_huge_pages) {
  3584. if (default_hstate.max_huge_pages) {
  3585. char buf[32];
  3586. string_get_size(huge_page_size(&default_hstate),
  3587. 1, STRING_UNITS_2, buf, 32);
  3588. pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
  3589. default_hstate.max_huge_pages, buf);
  3590. pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
  3591. default_hstate_max_huge_pages);
  3592. }
  3593. default_hstate.max_huge_pages =
  3594. default_hstate_max_huge_pages;
  3595. for_each_online_node(i)
  3596. default_hstate.max_huge_pages_node[i] =
  3597. default_hugepages_in_node[i];
  3598. }
  3599. }
  3600. hugetlb_init_hstates();
  3601. gather_bootmem_prealloc();
  3602. report_hugepages();
  3603. hugetlb_sysfs_init();
  3604. hugetlb_cgroup_file_init();
  3605. hugetlb_sysctl_init();
  3606. #ifdef CONFIG_SMP
  3607. num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
  3608. #else
  3609. num_fault_mutexes = 1;
  3610. #endif
  3611. hugetlb_fault_mutex_table =
  3612. kmalloc_objs(struct mutex, num_fault_mutexes);
  3613. BUG_ON(!hugetlb_fault_mutex_table);
  3614. for (i = 0; i < num_fault_mutexes; i++)
  3615. mutex_init(&hugetlb_fault_mutex_table[i]);
  3616. return 0;
  3617. }
  3618. subsys_initcall(hugetlb_init);
  3619. /* Overwritten by architectures with more huge page sizes */
  3620. bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
  3621. {
  3622. return size == HPAGE_SIZE;
  3623. }
  3624. void __init hugetlb_add_hstate(unsigned int order)
  3625. {
  3626. struct hstate *h;
  3627. unsigned long i;
  3628. if (size_to_hstate(PAGE_SIZE << order)) {
  3629. return;
  3630. }
  3631. BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
  3632. BUG_ON(order < order_base_2(__NR_USED_SUBPAGE));
  3633. WARN_ON(order > MAX_FOLIO_ORDER);
  3634. h = &hstates[hugetlb_max_hstate++];
  3635. __mutex_init(&h->resize_lock, "resize mutex", &h->resize_key);
  3636. h->order = order;
  3637. h->mask = ~(huge_page_size(h) - 1);
  3638. for (i = 0; i < MAX_NUMNODES; ++i)
  3639. INIT_LIST_HEAD(&h->hugepage_freelists[i]);
  3640. INIT_LIST_HEAD(&h->hugepage_activelist);
  3641. snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
  3642. huge_page_size(h)/SZ_1K);
  3643. parsed_hstate = h;
  3644. }
  3645. bool __init __weak hugetlb_node_alloc_supported(void)
  3646. {
  3647. return true;
  3648. }
  3649. static void __init hugepages_clear_pages_in_node(void)
  3650. {
  3651. if (!hugetlb_max_hstate) {
  3652. default_hstate_max_huge_pages = 0;
  3653. memset(default_hugepages_in_node, 0,
  3654. sizeof(default_hugepages_in_node));
  3655. } else {
  3656. parsed_hstate->max_huge_pages = 0;
  3657. memset(parsed_hstate->max_huge_pages_node, 0,
  3658. sizeof(parsed_hstate->max_huge_pages_node));
  3659. }
  3660. }
  3661. static __init int hugetlb_add_param(char *s, int (*setup)(char *))
  3662. {
  3663. size_t len;
  3664. char *p;
  3665. if (hugetlb_param_index >= HUGE_MAX_CMDLINE_ARGS)
  3666. return -EINVAL;
  3667. len = strlen(s) + 1;
  3668. if (len + hstate_cmdline_index > sizeof(hstate_cmdline_buf))
  3669. return -EINVAL;
  3670. p = &hstate_cmdline_buf[hstate_cmdline_index];
  3671. memcpy(p, s, len);
  3672. hstate_cmdline_index += len;
  3673. hugetlb_params[hugetlb_param_index].val = p;
  3674. hugetlb_params[hugetlb_param_index].setup = setup;
  3675. hugetlb_param_index++;
  3676. return 0;
  3677. }
  3678. static __init void hugetlb_parse_params(void)
  3679. {
  3680. int i;
  3681. struct hugetlb_cmdline *hcp;
  3682. for (i = 0; i < hugetlb_param_index; i++) {
  3683. hcp = &hugetlb_params[i];
  3684. hcp->setup(hcp->val);
  3685. }
  3686. hugetlb_cma_validate_params();
  3687. }
  3688. /*
  3689. * hugepages command line processing
  3690. * hugepages normally follows a valid hugepagsz or default_hugepagsz
  3691. * specification. If not, ignore the hugepages value. hugepages can also
  3692. * be the first huge page command line option in which case it implicitly
  3693. * specifies the number of huge pages for the default size.
  3694. */
  3695. static int __init hugepages_setup(char *s)
  3696. {
  3697. unsigned long *mhp;
  3698. static unsigned long *last_mhp;
  3699. int node = NUMA_NO_NODE;
  3700. int count;
  3701. unsigned long tmp;
  3702. char *p = s;
  3703. if (!hugepages_supported()) {
  3704. pr_warn("HugeTLB: hugepages unsupported, ignoring hugepages=%s cmdline\n", s);
  3705. return 0;
  3706. }
  3707. if (!parsed_valid_hugepagesz) {
  3708. pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
  3709. parsed_valid_hugepagesz = true;
  3710. return -EINVAL;
  3711. }
  3712. /*
  3713. * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
  3714. * yet, so this hugepages= parameter goes to the "default hstate".
  3715. * Otherwise, it goes with the previously parsed hugepagesz or
  3716. * default_hugepagesz.
  3717. */
  3718. else if (!hugetlb_max_hstate)
  3719. mhp = &default_hstate_max_huge_pages;
  3720. else
  3721. mhp = &parsed_hstate->max_huge_pages;
  3722. if (mhp == last_mhp) {
  3723. pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
  3724. return 1;
  3725. }
  3726. while (*p) {
  3727. count = 0;
  3728. if (sscanf(p, "%lu%n", &tmp, &count) != 1)
  3729. goto invalid;
  3730. /* Parameter is node format */
  3731. if (p[count] == ':') {
  3732. if (!hugetlb_node_alloc_supported()) {
  3733. pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
  3734. return 1;
  3735. }
  3736. if (tmp >= MAX_NUMNODES || !node_online(tmp))
  3737. goto invalid;
  3738. node = array_index_nospec(tmp, MAX_NUMNODES);
  3739. p += count + 1;
  3740. /* Parse hugepages */
  3741. if (sscanf(p, "%lu%n", &tmp, &count) != 1)
  3742. goto invalid;
  3743. if (!hugetlb_max_hstate)
  3744. default_hugepages_in_node[node] = tmp;
  3745. else
  3746. parsed_hstate->max_huge_pages_node[node] = tmp;
  3747. *mhp += tmp;
  3748. /* Go to parse next node*/
  3749. if (p[count] == ',')
  3750. p += count + 1;
  3751. else
  3752. break;
  3753. } else {
  3754. if (p != s)
  3755. goto invalid;
  3756. *mhp = tmp;
  3757. break;
  3758. }
  3759. }
  3760. last_mhp = mhp;
  3761. return 0;
  3762. invalid:
  3763. pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
  3764. hugepages_clear_pages_in_node();
  3765. return -EINVAL;
  3766. }
  3767. hugetlb_early_param("hugepages", hugepages_setup);
  3768. /*
  3769. * hugepagesz command line processing
  3770. * A specific huge page size can only be specified once with hugepagesz.
  3771. * hugepagesz is followed by hugepages on the command line. The global
  3772. * variable 'parsed_valid_hugepagesz' is used to determine if prior
  3773. * hugepagesz argument was valid.
  3774. */
  3775. static int __init hugepagesz_setup(char *s)
  3776. {
  3777. unsigned long size;
  3778. struct hstate *h;
  3779. if (!hugepages_supported()) {
  3780. pr_warn("HugeTLB: hugepages unsupported, ignoring hugepagesz=%s cmdline\n", s);
  3781. return 0;
  3782. }
  3783. parsed_valid_hugepagesz = false;
  3784. size = (unsigned long)memparse(s, NULL);
  3785. if (!arch_hugetlb_valid_size(size)) {
  3786. pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
  3787. return -EINVAL;
  3788. }
  3789. h = size_to_hstate(size);
  3790. if (h) {
  3791. /*
  3792. * hstate for this size already exists. This is normally
  3793. * an error, but is allowed if the existing hstate is the
  3794. * default hstate. More specifically, it is only allowed if
  3795. * the number of huge pages for the default hstate was not
  3796. * previously specified.
  3797. */
  3798. if (!parsed_default_hugepagesz || h != &default_hstate ||
  3799. default_hstate.max_huge_pages) {
  3800. pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
  3801. return -EINVAL;
  3802. }
  3803. /*
  3804. * No need to call hugetlb_add_hstate() as hstate already
  3805. * exists. But, do set parsed_hstate so that a following
  3806. * hugepages= parameter will be applied to this hstate.
  3807. */
  3808. parsed_hstate = h;
  3809. parsed_valid_hugepagesz = true;
  3810. return 0;
  3811. }
  3812. hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
  3813. parsed_valid_hugepagesz = true;
  3814. return 0;
  3815. }
  3816. hugetlb_early_param("hugepagesz", hugepagesz_setup);
  3817. /*
  3818. * default_hugepagesz command line input
  3819. * Only one instance of default_hugepagesz allowed on command line.
  3820. */
  3821. static int __init default_hugepagesz_setup(char *s)
  3822. {
  3823. unsigned long size;
  3824. int i;
  3825. if (!hugepages_supported()) {
  3826. pr_warn("HugeTLB: hugepages unsupported, ignoring default_hugepagesz=%s cmdline\n",
  3827. s);
  3828. return 0;
  3829. }
  3830. parsed_valid_hugepagesz = false;
  3831. if (parsed_default_hugepagesz) {
  3832. pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
  3833. return -EINVAL;
  3834. }
  3835. size = (unsigned long)memparse(s, NULL);
  3836. if (!arch_hugetlb_valid_size(size)) {
  3837. pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
  3838. return -EINVAL;
  3839. }
  3840. hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
  3841. parsed_valid_hugepagesz = true;
  3842. parsed_default_hugepagesz = true;
  3843. default_hstate_idx = hstate_index(size_to_hstate(size));
  3844. /*
  3845. * The number of default huge pages (for this size) could have been
  3846. * specified as the first hugetlb parameter: hugepages=X. If so,
  3847. * then default_hstate_max_huge_pages is set. If the default huge
  3848. * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be
  3849. * allocated here from bootmem allocator.
  3850. */
  3851. if (default_hstate_max_huge_pages) {
  3852. default_hstate.max_huge_pages = default_hstate_max_huge_pages;
  3853. /*
  3854. * Since this is an early parameter, we can't check
  3855. * NUMA node state yet, so loop through MAX_NUMNODES.
  3856. */
  3857. for (i = 0; i < MAX_NUMNODES; i++) {
  3858. if (default_hugepages_in_node[i] != 0)
  3859. default_hstate.max_huge_pages_node[i] =
  3860. default_hugepages_in_node[i];
  3861. }
  3862. default_hstate_max_huge_pages = 0;
  3863. }
  3864. return 0;
  3865. }
  3866. hugetlb_early_param("default_hugepagesz", default_hugepagesz_setup);
  3867. void __init hugetlb_bootmem_set_nodes(void)
  3868. {
  3869. int i, nid;
  3870. unsigned long start_pfn, end_pfn;
  3871. if (!nodes_empty(hugetlb_bootmem_nodes))
  3872. return;
  3873. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
  3874. if (end_pfn > start_pfn)
  3875. node_set(nid, hugetlb_bootmem_nodes);
  3876. }
  3877. }
  3878. void __init hugetlb_bootmem_alloc(void)
  3879. {
  3880. struct hstate *h;
  3881. int i;
  3882. hugetlb_bootmem_set_nodes();
  3883. for (i = 0; i < MAX_NUMNODES; i++)
  3884. INIT_LIST_HEAD(&huge_boot_pages[i]);
  3885. hugetlb_parse_params();
  3886. for_each_hstate(h) {
  3887. h->next_nid_to_alloc = first_online_node;
  3888. if (hstate_is_gigantic(h))
  3889. hugetlb_hstate_alloc_pages(h);
  3890. }
  3891. }
  3892. /*
  3893. * hugepage_alloc_threads command line parsing.
  3894. *
  3895. * When set, use this specific number of threads for the boot
  3896. * allocation of hugepages.
  3897. */
  3898. static int __init hugepage_alloc_threads_setup(char *s)
  3899. {
  3900. unsigned long allocation_threads;
  3901. if (kstrtoul(s, 0, &allocation_threads) != 0)
  3902. return 1;
  3903. if (allocation_threads == 0)
  3904. return 1;
  3905. hugepage_allocation_threads = allocation_threads;
  3906. return 1;
  3907. }
  3908. __setup("hugepage_alloc_threads=", hugepage_alloc_threads_setup);
  3909. static unsigned int allowed_mems_nr(struct hstate *h)
  3910. {
  3911. int node;
  3912. unsigned int nr = 0;
  3913. nodemask_t *mbind_nodemask;
  3914. unsigned int *array = h->free_huge_pages_node;
  3915. gfp_t gfp_mask = htlb_alloc_mask(h);
  3916. mbind_nodemask = policy_mbind_nodemask(gfp_mask);
  3917. for_each_node_mask(node, cpuset_current_mems_allowed) {
  3918. if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
  3919. nr += array[node];
  3920. }
  3921. return nr;
  3922. }
  3923. void hugetlb_report_meminfo(struct seq_file *m)
  3924. {
  3925. struct hstate *h;
  3926. unsigned long total = 0;
  3927. if (!hugepages_supported())
  3928. return;
  3929. for_each_hstate(h) {
  3930. unsigned long count = h->nr_huge_pages;
  3931. total += huge_page_size(h) * count;
  3932. if (h == &default_hstate)
  3933. seq_printf(m,
  3934. "HugePages_Total: %5lu\n"
  3935. "HugePages_Free: %5lu\n"
  3936. "HugePages_Rsvd: %5lu\n"
  3937. "HugePages_Surp: %5lu\n"
  3938. "Hugepagesize: %8lu kB\n",
  3939. count,
  3940. h->free_huge_pages,
  3941. h->resv_huge_pages,
  3942. h->surplus_huge_pages,
  3943. huge_page_size(h) / SZ_1K);
  3944. }
  3945. seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K);
  3946. }
  3947. int hugetlb_report_node_meminfo(char *buf, int len, int nid)
  3948. {
  3949. struct hstate *h = &default_hstate;
  3950. if (!hugepages_supported())
  3951. return 0;
  3952. return sysfs_emit_at(buf, len,
  3953. "Node %d HugePages_Total: %5u\n"
  3954. "Node %d HugePages_Free: %5u\n"
  3955. "Node %d HugePages_Surp: %5u\n",
  3956. nid, h->nr_huge_pages_node[nid],
  3957. nid, h->free_huge_pages_node[nid],
  3958. nid, h->surplus_huge_pages_node[nid]);
  3959. }
  3960. void hugetlb_show_meminfo_node(int nid)
  3961. {
  3962. struct hstate *h;
  3963. if (!hugepages_supported())
  3964. return;
  3965. for_each_hstate(h)
  3966. printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
  3967. nid,
  3968. h->nr_huge_pages_node[nid],
  3969. h->free_huge_pages_node[nid],
  3970. h->surplus_huge_pages_node[nid],
  3971. huge_page_size(h) / SZ_1K);
  3972. }
  3973. void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
  3974. {
  3975. seq_printf(m, "HugetlbPages:\t%8lu kB\n",
  3976. K(atomic_long_read(&mm->hugetlb_usage)));
  3977. }
  3978. /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
  3979. unsigned long hugetlb_total_pages(void)
  3980. {
  3981. struct hstate *h;
  3982. unsigned long nr_total_pages = 0;
  3983. for_each_hstate(h)
  3984. nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
  3985. return nr_total_pages;
  3986. }
  3987. static int hugetlb_acct_memory(struct hstate *h, long delta)
  3988. {
  3989. int ret = -ENOMEM;
  3990. if (!delta)
  3991. return 0;
  3992. spin_lock_irq(&hugetlb_lock);
  3993. /*
  3994. * When cpuset is configured, it breaks the strict hugetlb page
  3995. * reservation as the accounting is done on a global variable. Such
  3996. * reservation is completely rubbish in the presence of cpuset because
  3997. * the reservation is not checked against page availability for the
  3998. * current cpuset. Application can still potentially OOM'ed by kernel
  3999. * with lack of free htlb page in cpuset that the task is in.
  4000. * Attempt to enforce strict accounting with cpuset is almost
  4001. * impossible (or too ugly) because cpuset is too fluid that
  4002. * task or memory node can be dynamically moved between cpusets.
  4003. *
  4004. * The change of semantics for shared hugetlb mapping with cpuset is
  4005. * undesirable. However, in order to preserve some of the semantics,
  4006. * we fall back to check against current free page availability as
  4007. * a best attempt and hopefully to minimize the impact of changing
  4008. * semantics that cpuset has.
  4009. *
  4010. * Apart from cpuset, we also have memory policy mechanism that
  4011. * also determines from which node the kernel will allocate memory
  4012. * in a NUMA system. So similar to cpuset, we also should consider
  4013. * the memory policy of the current task. Similar to the description
  4014. * above.
  4015. */
  4016. if (delta > 0) {
  4017. if (gather_surplus_pages(h, delta) < 0)
  4018. goto out;
  4019. if (delta > allowed_mems_nr(h)) {
  4020. return_unused_surplus_pages(h, delta);
  4021. goto out;
  4022. }
  4023. }
  4024. ret = 0;
  4025. if (delta < 0)
  4026. return_unused_surplus_pages(h, (unsigned long) -delta);
  4027. out:
  4028. spin_unlock_irq(&hugetlb_lock);
  4029. return ret;
  4030. }
  4031. static void hugetlb_vm_op_open(struct vm_area_struct *vma)
  4032. {
  4033. struct resv_map *resv = vma_resv_map(vma);
  4034. /*
  4035. * HPAGE_RESV_OWNER indicates a private mapping.
  4036. * This new VMA should share its siblings reservation map if present.
  4037. * The VMA will only ever have a valid reservation map pointer where
  4038. * it is being copied for another still existing VMA. As that VMA
  4039. * has a reference to the reservation map it cannot disappear until
  4040. * after this open call completes. It is therefore safe to take a
  4041. * new reference here without additional locking.
  4042. */
  4043. if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
  4044. resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
  4045. kref_get(&resv->refs);
  4046. }
  4047. /*
  4048. * vma_lock structure for sharable mappings is vma specific.
  4049. * Clear old pointer (if copied via vm_area_dup) and allocate
  4050. * new structure. Before clearing, make sure vma_lock is not
  4051. * for this vma.
  4052. */
  4053. if (vma->vm_flags & VM_MAYSHARE) {
  4054. struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
  4055. if (vma_lock) {
  4056. if (vma_lock->vma != vma) {
  4057. vma->vm_private_data = NULL;
  4058. hugetlb_vma_lock_alloc(vma);
  4059. } else {
  4060. pr_warn("HugeTLB: vma_lock already exists in %s.\n", __func__);
  4061. }
  4062. } else {
  4063. hugetlb_vma_lock_alloc(vma);
  4064. }
  4065. }
  4066. }
  4067. static void hugetlb_vm_op_close(struct vm_area_struct *vma)
  4068. {
  4069. struct hstate *h = hstate_vma(vma);
  4070. struct resv_map *resv;
  4071. struct hugepage_subpool *spool = subpool_vma(vma);
  4072. unsigned long reserve, start, end;
  4073. long gbl_reserve;
  4074. hugetlb_vma_lock_free(vma);
  4075. resv = vma_resv_map(vma);
  4076. if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
  4077. return;
  4078. start = vma_hugecache_offset(h, vma, vma->vm_start);
  4079. end = vma_hugecache_offset(h, vma, vma->vm_end);
  4080. reserve = (end - start) - region_count(resv, start, end);
  4081. hugetlb_cgroup_uncharge_counter(resv, start, end);
  4082. if (reserve) {
  4083. /*
  4084. * Decrement reserve counts. The global reserve count may be
  4085. * adjusted if the subpool has a minimum size.
  4086. */
  4087. gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
  4088. hugetlb_acct_memory(h, -gbl_reserve);
  4089. }
  4090. kref_put(&resv->refs, resv_map_release);
  4091. }
  4092. static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
  4093. {
  4094. if (addr & ~(huge_page_mask(hstate_vma(vma))))
  4095. return -EINVAL;
  4096. return 0;
  4097. }
  4098. void hugetlb_split(struct vm_area_struct *vma, unsigned long addr)
  4099. {
  4100. /*
  4101. * PMD sharing is only possible for PUD_SIZE-aligned address ranges
  4102. * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
  4103. * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
  4104. * This function is called in the middle of a VMA split operation, with
  4105. * MM, VMA and rmap all write-locked to prevent concurrent page table
  4106. * walks (except hardware and gup_fast()).
  4107. */
  4108. vma_assert_write_locked(vma);
  4109. i_mmap_assert_write_locked(vma->vm_file->f_mapping);
  4110. if (addr & ~PUD_MASK) {
  4111. unsigned long floor = addr & PUD_MASK;
  4112. unsigned long ceil = floor + PUD_SIZE;
  4113. if (floor >= vma->vm_start && ceil <= vma->vm_end) {
  4114. /*
  4115. * Locking:
  4116. * Use take_locks=false here.
  4117. * The file rmap lock is already held.
  4118. * The hugetlb VMA lock can't be taken when we already
  4119. * hold the file rmap lock, and we don't need it because
  4120. * its purpose is to synchronize against concurrent page
  4121. * table walks, which are not possible thanks to the
  4122. * locks held by our caller.
  4123. */
  4124. hugetlb_unshare_pmds(vma, floor, ceil, /* take_locks = */ false);
  4125. }
  4126. }
  4127. }
  4128. static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
  4129. {
  4130. return huge_page_size(hstate_vma(vma));
  4131. }
  4132. /*
  4133. * We cannot handle pagefaults against hugetlb pages at all. They cause
  4134. * handle_mm_fault() to try to instantiate regular-sized pages in the
  4135. * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get
  4136. * this far.
  4137. */
  4138. static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
  4139. {
  4140. BUG();
  4141. return 0;
  4142. }
  4143. /*
  4144. * When a new function is introduced to vm_operations_struct and added
  4145. * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
  4146. * This is because under System V memory model, mappings created via
  4147. * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
  4148. * their original vm_ops are overwritten with shm_vm_ops.
  4149. */
  4150. const struct vm_operations_struct hugetlb_vm_ops = {
  4151. .fault = hugetlb_vm_op_fault,
  4152. .open = hugetlb_vm_op_open,
  4153. .close = hugetlb_vm_op_close,
  4154. .may_split = hugetlb_vm_op_split,
  4155. .pagesize = hugetlb_vm_op_pagesize,
  4156. };
  4157. static pte_t make_huge_pte(struct vm_area_struct *vma, struct folio *folio,
  4158. bool try_mkwrite)
  4159. {
  4160. pte_t entry = folio_mk_pte(folio, vma->vm_page_prot);
  4161. unsigned int shift = huge_page_shift(hstate_vma(vma));
  4162. if (try_mkwrite && (vma->vm_flags & VM_WRITE)) {
  4163. entry = pte_mkwrite_novma(pte_mkdirty(entry));
  4164. } else {
  4165. entry = pte_wrprotect(entry);
  4166. }
  4167. entry = pte_mkyoung(entry);
  4168. entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
  4169. return entry;
  4170. }
  4171. static void set_huge_ptep_writable(struct vm_area_struct *vma,
  4172. unsigned long address, pte_t *ptep)
  4173. {
  4174. pte_t entry;
  4175. entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(vma->vm_mm, address, ptep)));
  4176. if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
  4177. update_mmu_cache(vma, address, ptep);
  4178. }
  4179. static void set_huge_ptep_maybe_writable(struct vm_area_struct *vma,
  4180. unsigned long address, pte_t *ptep)
  4181. {
  4182. if (vma->vm_flags & VM_WRITE)
  4183. set_huge_ptep_writable(vma, address, ptep);
  4184. }
  4185. static void
  4186. hugetlb_install_folio(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
  4187. struct folio *new_folio, pte_t old, unsigned long sz)
  4188. {
  4189. pte_t newpte = make_huge_pte(vma, new_folio, true);
  4190. __folio_mark_uptodate(new_folio);
  4191. hugetlb_add_new_anon_rmap(new_folio, vma, addr);
  4192. if (userfaultfd_wp(vma) && huge_pte_uffd_wp(old))
  4193. newpte = huge_pte_mkuffd_wp(newpte);
  4194. set_huge_pte_at(vma->vm_mm, addr, ptep, newpte, sz);
  4195. hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
  4196. folio_set_hugetlb_migratable(new_folio);
  4197. }
  4198. int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
  4199. struct vm_area_struct *dst_vma,
  4200. struct vm_area_struct *src_vma)
  4201. {
  4202. pte_t *src_pte, *dst_pte, entry;
  4203. struct folio *pte_folio;
  4204. unsigned long addr;
  4205. bool cow = is_cow_mapping(src_vma->vm_flags);
  4206. struct hstate *h = hstate_vma(src_vma);
  4207. unsigned long sz = huge_page_size(h);
  4208. unsigned long npages = pages_per_huge_page(h);
  4209. struct mmu_notifier_range range;
  4210. unsigned long last_addr_mask;
  4211. softleaf_t softleaf;
  4212. int ret = 0;
  4213. if (cow) {
  4214. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src,
  4215. src_vma->vm_start,
  4216. src_vma->vm_end);
  4217. mmu_notifier_invalidate_range_start(&range);
  4218. vma_assert_write_locked(src_vma);
  4219. raw_write_seqcount_begin(&src->write_protect_seq);
  4220. } else {
  4221. /*
  4222. * For shared mappings the vma lock must be held before
  4223. * calling hugetlb_walk() in the src vma. Otherwise, the
  4224. * returned ptep could go away if part of a shared pmd and
  4225. * another thread calls huge_pmd_unshare.
  4226. */
  4227. hugetlb_vma_lock_read(src_vma);
  4228. }
  4229. last_addr_mask = hugetlb_mask_last_page(h);
  4230. for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
  4231. spinlock_t *src_ptl, *dst_ptl;
  4232. src_pte = hugetlb_walk(src_vma, addr, sz);
  4233. if (!src_pte) {
  4234. addr |= last_addr_mask;
  4235. continue;
  4236. }
  4237. dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
  4238. if (!dst_pte) {
  4239. ret = -ENOMEM;
  4240. break;
  4241. }
  4242. #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
  4243. /* If the pagetables are shared, there is nothing to do */
  4244. if (ptdesc_pmd_is_shared(virt_to_ptdesc(dst_pte))) {
  4245. addr |= last_addr_mask;
  4246. continue;
  4247. }
  4248. #endif
  4249. dst_ptl = huge_pte_lock(h, dst, dst_pte);
  4250. src_ptl = huge_pte_lockptr(h, src, src_pte);
  4251. spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
  4252. entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
  4253. again:
  4254. if (huge_pte_none(entry)) {
  4255. /* Skip if src entry none. */
  4256. goto next;
  4257. }
  4258. softleaf = softleaf_from_pte(entry);
  4259. if (unlikely(softleaf_is_hwpoison(softleaf))) {
  4260. if (!userfaultfd_wp(dst_vma))
  4261. entry = huge_pte_clear_uffd_wp(entry);
  4262. set_huge_pte_at(dst, addr, dst_pte, entry, sz);
  4263. } else if (unlikely(softleaf_is_migration(softleaf))) {
  4264. bool uffd_wp = pte_swp_uffd_wp(entry);
  4265. if (!softleaf_is_migration_read(softleaf) && cow) {
  4266. /*
  4267. * COW mappings require pages in both
  4268. * parent and child to be set to read.
  4269. */
  4270. softleaf = make_readable_migration_entry(
  4271. swp_offset(softleaf));
  4272. entry = swp_entry_to_pte(softleaf);
  4273. if (userfaultfd_wp(src_vma) && uffd_wp)
  4274. entry = pte_swp_mkuffd_wp(entry);
  4275. set_huge_pte_at(src, addr, src_pte, entry, sz);
  4276. }
  4277. if (!userfaultfd_wp(dst_vma))
  4278. entry = huge_pte_clear_uffd_wp(entry);
  4279. set_huge_pte_at(dst, addr, dst_pte, entry, sz);
  4280. } else if (unlikely(pte_is_marker(entry))) {
  4281. const pte_marker marker = copy_pte_marker(softleaf, dst_vma);
  4282. if (marker)
  4283. set_huge_pte_at(dst, addr, dst_pte,
  4284. make_pte_marker(marker), sz);
  4285. } else {
  4286. entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
  4287. pte_folio = page_folio(pte_page(entry));
  4288. folio_get(pte_folio);
  4289. /*
  4290. * Failing to duplicate the anon rmap is a rare case
  4291. * where we see pinned hugetlb pages while they're
  4292. * prone to COW. We need to do the COW earlier during
  4293. * fork.
  4294. *
  4295. * When pre-allocating the page or copying data, we
  4296. * need to be without the pgtable locks since we could
  4297. * sleep during the process.
  4298. */
  4299. if (!folio_test_anon(pte_folio)) {
  4300. hugetlb_add_file_rmap(pte_folio);
  4301. } else if (hugetlb_try_dup_anon_rmap(pte_folio, src_vma)) {
  4302. pte_t src_pte_old = entry;
  4303. struct folio *new_folio;
  4304. spin_unlock(src_ptl);
  4305. spin_unlock(dst_ptl);
  4306. /* Do not use reserve as it's private owned */
  4307. new_folio = alloc_hugetlb_folio(dst_vma, addr, false);
  4308. if (IS_ERR(new_folio)) {
  4309. folio_put(pte_folio);
  4310. ret = PTR_ERR(new_folio);
  4311. break;
  4312. }
  4313. ret = copy_user_large_folio(new_folio, pte_folio,
  4314. addr, dst_vma);
  4315. folio_put(pte_folio);
  4316. if (ret) {
  4317. folio_put(new_folio);
  4318. break;
  4319. }
  4320. /* Install the new hugetlb folio if src pte stable */
  4321. dst_ptl = huge_pte_lock(h, dst, dst_pte);
  4322. src_ptl = huge_pte_lockptr(h, src, src_pte);
  4323. spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
  4324. entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
  4325. if (!pte_same(src_pte_old, entry)) {
  4326. restore_reserve_on_error(h, dst_vma, addr,
  4327. new_folio);
  4328. folio_put(new_folio);
  4329. /* huge_ptep of dst_pte won't change as in child */
  4330. goto again;
  4331. }
  4332. hugetlb_install_folio(dst_vma, dst_pte, addr,
  4333. new_folio, src_pte_old, sz);
  4334. goto next;
  4335. }
  4336. if (cow) {
  4337. /*
  4338. * No need to notify as we are downgrading page
  4339. * table protection not changing it to point
  4340. * to a new page.
  4341. *
  4342. * See Documentation/mm/mmu_notifier.rst
  4343. */
  4344. huge_ptep_set_wrprotect(src, addr, src_pte);
  4345. entry = huge_pte_wrprotect(entry);
  4346. }
  4347. if (!userfaultfd_wp(dst_vma))
  4348. entry = huge_pte_clear_uffd_wp(entry);
  4349. set_huge_pte_at(dst, addr, dst_pte, entry, sz);
  4350. hugetlb_count_add(npages, dst);
  4351. }
  4352. next:
  4353. spin_unlock(src_ptl);
  4354. spin_unlock(dst_ptl);
  4355. }
  4356. if (cow) {
  4357. raw_write_seqcount_end(&src->write_protect_seq);
  4358. mmu_notifier_invalidate_range_end(&range);
  4359. } else {
  4360. hugetlb_vma_unlock_read(src_vma);
  4361. }
  4362. return ret;
  4363. }
  4364. static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
  4365. unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte,
  4366. unsigned long sz)
  4367. {
  4368. bool need_clear_uffd_wp = vma_has_uffd_without_event_remap(vma);
  4369. struct hstate *h = hstate_vma(vma);
  4370. struct mm_struct *mm = vma->vm_mm;
  4371. spinlock_t *src_ptl, *dst_ptl;
  4372. pte_t pte;
  4373. dst_ptl = huge_pte_lock(h, mm, dst_pte);
  4374. src_ptl = huge_pte_lockptr(h, mm, src_pte);
  4375. /*
  4376. * We don't have to worry about the ordering of src and dst ptlocks
  4377. * because exclusive mmap_lock (or the i_mmap_lock) prevents deadlock.
  4378. */
  4379. if (src_ptl != dst_ptl)
  4380. spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
  4381. pte = huge_ptep_get_and_clear(mm, old_addr, src_pte, sz);
  4382. if (need_clear_uffd_wp && pte_is_uffd_wp_marker(pte)) {
  4383. huge_pte_clear(mm, new_addr, dst_pte, sz);
  4384. } else {
  4385. if (need_clear_uffd_wp) {
  4386. if (pte_present(pte))
  4387. pte = huge_pte_clear_uffd_wp(pte);
  4388. else
  4389. pte = pte_swp_clear_uffd_wp(pte);
  4390. }
  4391. set_huge_pte_at(mm, new_addr, dst_pte, pte, sz);
  4392. }
  4393. if (src_ptl != dst_ptl)
  4394. spin_unlock(src_ptl);
  4395. spin_unlock(dst_ptl);
  4396. }
  4397. int move_hugetlb_page_tables(struct vm_area_struct *vma,
  4398. struct vm_area_struct *new_vma,
  4399. unsigned long old_addr, unsigned long new_addr,
  4400. unsigned long len)
  4401. {
  4402. struct hstate *h = hstate_vma(vma);
  4403. struct address_space *mapping = vma->vm_file->f_mapping;
  4404. unsigned long sz = huge_page_size(h);
  4405. struct mm_struct *mm = vma->vm_mm;
  4406. unsigned long old_end = old_addr + len;
  4407. unsigned long last_addr_mask;
  4408. pte_t *src_pte, *dst_pte;
  4409. struct mmu_notifier_range range;
  4410. struct mmu_gather tlb;
  4411. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, old_addr,
  4412. old_end);
  4413. adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
  4414. /*
  4415. * In case of shared PMDs, we should cover the maximum possible
  4416. * range.
  4417. */
  4418. flush_cache_range(vma, range.start, range.end);
  4419. tlb_gather_mmu_vma(&tlb, vma);
  4420. mmu_notifier_invalidate_range_start(&range);
  4421. last_addr_mask = hugetlb_mask_last_page(h);
  4422. /* Prevent race with file truncation */
  4423. hugetlb_vma_lock_write(vma);
  4424. i_mmap_lock_write(mapping);
  4425. for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
  4426. src_pte = hugetlb_walk(vma, old_addr, sz);
  4427. if (!src_pte) {
  4428. old_addr |= last_addr_mask;
  4429. new_addr |= last_addr_mask;
  4430. continue;
  4431. }
  4432. if (huge_pte_none(huge_ptep_get(mm, old_addr, src_pte)))
  4433. continue;
  4434. if (huge_pmd_unshare(&tlb, vma, old_addr, src_pte)) {
  4435. old_addr |= last_addr_mask;
  4436. new_addr |= last_addr_mask;
  4437. continue;
  4438. }
  4439. dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
  4440. if (!dst_pte)
  4441. break;
  4442. move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte, sz);
  4443. tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr);
  4444. }
  4445. tlb_flush_mmu_tlbonly(&tlb);
  4446. huge_pmd_unshare_flush(&tlb, vma);
  4447. mmu_notifier_invalidate_range_end(&range);
  4448. i_mmap_unlock_write(mapping);
  4449. hugetlb_vma_unlock_write(vma);
  4450. tlb_finish_mmu(&tlb);
  4451. return len + old_addr - old_end;
  4452. }
  4453. void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
  4454. unsigned long start, unsigned long end,
  4455. struct folio *folio, zap_flags_t zap_flags)
  4456. {
  4457. struct mm_struct *mm = vma->vm_mm;
  4458. const bool folio_provided = !!folio;
  4459. unsigned long address;
  4460. pte_t *ptep;
  4461. pte_t pte;
  4462. spinlock_t *ptl;
  4463. struct hstate *h = hstate_vma(vma);
  4464. unsigned long sz = huge_page_size(h);
  4465. bool adjust_reservation;
  4466. unsigned long last_addr_mask;
  4467. WARN_ON(!is_vm_hugetlb_page(vma));
  4468. BUG_ON(start & ~huge_page_mask(h));
  4469. BUG_ON(end & ~huge_page_mask(h));
  4470. /*
  4471. * This is a hugetlb vma, all the pte entries should point
  4472. * to huge page.
  4473. */
  4474. tlb_change_page_size(tlb, sz);
  4475. tlb_start_vma(tlb, vma);
  4476. last_addr_mask = hugetlb_mask_last_page(h);
  4477. address = start;
  4478. for (; address < end; address += sz) {
  4479. ptep = hugetlb_walk(vma, address, sz);
  4480. if (!ptep) {
  4481. address |= last_addr_mask;
  4482. continue;
  4483. }
  4484. ptl = huge_pte_lock(h, mm, ptep);
  4485. if (huge_pmd_unshare(tlb, vma, address, ptep)) {
  4486. spin_unlock(ptl);
  4487. address |= last_addr_mask;
  4488. continue;
  4489. }
  4490. pte = huge_ptep_get(mm, address, ptep);
  4491. if (huge_pte_none(pte)) {
  4492. spin_unlock(ptl);
  4493. continue;
  4494. }
  4495. /*
  4496. * Migrating hugepage or HWPoisoned hugepage is already
  4497. * unmapped and its refcount is dropped, so just clear pte here.
  4498. */
  4499. if (unlikely(!pte_present(pte))) {
  4500. /*
  4501. * If the pte was wr-protected by uffd-wp in any of the
  4502. * swap forms, meanwhile the caller does not want to
  4503. * drop the uffd-wp bit in this zap, then replace the
  4504. * pte with a marker.
  4505. */
  4506. if (pte_swp_uffd_wp_any(pte) &&
  4507. !(zap_flags & ZAP_FLAG_DROP_MARKER))
  4508. set_huge_pte_at(mm, address, ptep,
  4509. make_pte_marker(PTE_MARKER_UFFD_WP),
  4510. sz);
  4511. else
  4512. huge_pte_clear(mm, address, ptep, sz);
  4513. spin_unlock(ptl);
  4514. continue;
  4515. }
  4516. /*
  4517. * If a folio is supplied, it is because a specific
  4518. * folio is being unmapped, not a range. Ensure the folio we
  4519. * are about to unmap is the actual folio of interest.
  4520. */
  4521. if (folio_provided) {
  4522. if (folio != page_folio(pte_page(pte))) {
  4523. spin_unlock(ptl);
  4524. continue;
  4525. }
  4526. /*
  4527. * Mark the VMA as having unmapped its page so that
  4528. * future faults in this VMA will fail rather than
  4529. * looking like data was lost
  4530. */
  4531. set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
  4532. } else {
  4533. folio = page_folio(pte_page(pte));
  4534. }
  4535. pte = huge_ptep_get_and_clear(mm, address, ptep, sz);
  4536. tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
  4537. if (huge_pte_dirty(pte))
  4538. folio_mark_dirty(folio);
  4539. /* Leave a uffd-wp pte marker if needed */
  4540. if (huge_pte_uffd_wp(pte) &&
  4541. !(zap_flags & ZAP_FLAG_DROP_MARKER))
  4542. set_huge_pte_at(mm, address, ptep,
  4543. make_pte_marker(PTE_MARKER_UFFD_WP),
  4544. sz);
  4545. hugetlb_count_sub(pages_per_huge_page(h), mm);
  4546. hugetlb_remove_rmap(folio);
  4547. spin_unlock(ptl);
  4548. /*
  4549. * Restore the reservation for anonymous page, otherwise the
  4550. * backing page could be stolen by someone.
  4551. * If there we are freeing a surplus, do not set the restore
  4552. * reservation bit.
  4553. */
  4554. adjust_reservation = false;
  4555. spin_lock_irq(&hugetlb_lock);
  4556. if (!h->surplus_huge_pages && __vma_private_lock(vma) &&
  4557. folio_test_anon(folio)) {
  4558. folio_set_hugetlb_restore_reserve(folio);
  4559. /* Reservation to be adjusted after the spin lock */
  4560. adjust_reservation = true;
  4561. }
  4562. spin_unlock_irq(&hugetlb_lock);
  4563. /*
  4564. * Adjust the reservation for the region that will have the
  4565. * reserve restored. Keep in mind that vma_needs_reservation() changes
  4566. * resv->adds_in_progress if it succeeds. If this is not done,
  4567. * do_exit() will not see it, and will keep the reservation
  4568. * forever.
  4569. */
  4570. if (adjust_reservation) {
  4571. int rc = vma_needs_reservation(h, vma, address);
  4572. if (rc < 0)
  4573. /* Pressumably allocate_file_region_entries failed
  4574. * to allocate a file_region struct. Clear
  4575. * hugetlb_restore_reserve so that global reserve
  4576. * count will not be incremented by free_huge_folio.
  4577. * Act as if we consumed the reservation.
  4578. */
  4579. folio_clear_hugetlb_restore_reserve(folio);
  4580. else if (rc)
  4581. vma_add_reservation(h, vma, address);
  4582. }
  4583. tlb_remove_page_size(tlb, folio_page(folio, 0),
  4584. folio_size(folio));
  4585. /*
  4586. * If we were instructed to unmap a specific folio, we're done.
  4587. */
  4588. if (folio_provided)
  4589. break;
  4590. }
  4591. tlb_end_vma(tlb, vma);
  4592. huge_pmd_unshare_flush(tlb, vma);
  4593. }
  4594. void __hugetlb_zap_begin(struct vm_area_struct *vma,
  4595. unsigned long *start, unsigned long *end)
  4596. {
  4597. if (!vma->vm_file) /* hugetlbfs_file_mmap error */
  4598. return;
  4599. adjust_range_if_pmd_sharing_possible(vma, start, end);
  4600. hugetlb_vma_lock_write(vma);
  4601. if (vma->vm_file)
  4602. i_mmap_lock_write(vma->vm_file->f_mapping);
  4603. }
  4604. void __hugetlb_zap_end(struct vm_area_struct *vma,
  4605. struct zap_details *details)
  4606. {
  4607. zap_flags_t zap_flags = details ? details->zap_flags : 0;
  4608. if (!vma->vm_file) /* hugetlbfs_file_mmap error */
  4609. return;
  4610. if (zap_flags & ZAP_FLAG_UNMAP) { /* final unmap */
  4611. /*
  4612. * Unlock and free the vma lock before releasing i_mmap_rwsem.
  4613. * When the vma_lock is freed, this makes the vma ineligible
  4614. * for pmd sharing. And, i_mmap_rwsem is required to set up
  4615. * pmd sharing. This is important as page tables for this
  4616. * unmapped range will be asynchrously deleted. If the page
  4617. * tables are shared, there will be issues when accessed by
  4618. * someone else.
  4619. */
  4620. __hugetlb_vma_unlock_write_free(vma);
  4621. } else {
  4622. hugetlb_vma_unlock_write(vma);
  4623. }
  4624. if (vma->vm_file)
  4625. i_mmap_unlock_write(vma->vm_file->f_mapping);
  4626. }
  4627. void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
  4628. unsigned long end, struct folio *folio,
  4629. zap_flags_t zap_flags)
  4630. {
  4631. struct mmu_notifier_range range;
  4632. struct mmu_gather tlb;
  4633. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
  4634. start, end);
  4635. adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
  4636. mmu_notifier_invalidate_range_start(&range);
  4637. tlb_gather_mmu(&tlb, vma->vm_mm);
  4638. __unmap_hugepage_range(&tlb, vma, start, end,
  4639. folio, zap_flags);
  4640. mmu_notifier_invalidate_range_end(&range);
  4641. tlb_finish_mmu(&tlb);
  4642. }
  4643. /*
  4644. * This is called when the original mapper is failing to COW a MAP_PRIVATE
  4645. * mapping it owns the reserve page for. The intention is to unmap the page
  4646. * from other VMAs and let the children be SIGKILLed if they are faulting the
  4647. * same region.
  4648. */
  4649. static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
  4650. struct folio *folio, unsigned long address)
  4651. {
  4652. struct hstate *h = hstate_vma(vma);
  4653. struct vm_area_struct *iter_vma;
  4654. struct address_space *mapping;
  4655. pgoff_t pgoff;
  4656. /*
  4657. * vm_pgoff is in PAGE_SIZE units, hence the different calculation
  4658. * from page cache lookup which is in HPAGE_SIZE units.
  4659. */
  4660. address = address & huge_page_mask(h);
  4661. pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
  4662. vma->vm_pgoff;
  4663. mapping = vma->vm_file->f_mapping;
  4664. /*
  4665. * Take the mapping lock for the duration of the table walk. As
  4666. * this mapping should be shared between all the VMAs,
  4667. * __unmap_hugepage_range() is called as the lock is already held
  4668. */
  4669. i_mmap_lock_write(mapping);
  4670. vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
  4671. /* Do not unmap the current VMA */
  4672. if (iter_vma == vma)
  4673. continue;
  4674. /*
  4675. * Shared VMAs have their own reserves and do not affect
  4676. * MAP_PRIVATE accounting but it is possible that a shared
  4677. * VMA is using the same page so check and skip such VMAs.
  4678. */
  4679. if (iter_vma->vm_flags & VM_MAYSHARE)
  4680. continue;
  4681. /*
  4682. * Unmap the page from other VMAs without their own reserves.
  4683. * They get marked to be SIGKILLed if they fault in these
  4684. * areas. This is because a future no-page fault on this VMA
  4685. * could insert a zeroed page instead of the data existing
  4686. * from the time of fork. This would look like data corruption
  4687. */
  4688. if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
  4689. unmap_hugepage_range(iter_vma, address,
  4690. address + huge_page_size(h),
  4691. folio, 0);
  4692. }
  4693. i_mmap_unlock_write(mapping);
  4694. }
  4695. /*
  4696. * hugetlb_wp() should be called with page lock of the original hugepage held.
  4697. * Called with hugetlb_fault_mutex_table held and pte_page locked so we
  4698. * cannot race with other handlers or page migration.
  4699. * Keep the pte_same checks anyway to make transition from the mutex easier.
  4700. */
  4701. static vm_fault_t hugetlb_wp(struct vm_fault *vmf)
  4702. {
  4703. struct vm_area_struct *vma = vmf->vma;
  4704. struct mm_struct *mm = vma->vm_mm;
  4705. const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
  4706. pte_t pte = huge_ptep_get(mm, vmf->address, vmf->pte);
  4707. struct hstate *h = hstate_vma(vma);
  4708. struct folio *old_folio;
  4709. struct folio *new_folio;
  4710. bool cow_from_owner = 0;
  4711. vm_fault_t ret = 0;
  4712. struct mmu_notifier_range range;
  4713. /*
  4714. * Never handle CoW for uffd-wp protected pages. It should be only
  4715. * handled when the uffd-wp protection is removed.
  4716. *
  4717. * Note that only the CoW optimization path (in hugetlb_no_page())
  4718. * can trigger this, because hugetlb_fault() will always resolve
  4719. * uffd-wp bit first.
  4720. */
  4721. if (!unshare && huge_pte_uffd_wp(pte))
  4722. return 0;
  4723. /* Let's take out MAP_SHARED mappings first. */
  4724. if (vma->vm_flags & VM_MAYSHARE) {
  4725. set_huge_ptep_writable(vma, vmf->address, vmf->pte);
  4726. return 0;
  4727. }
  4728. old_folio = page_folio(pte_page(pte));
  4729. delayacct_wpcopy_start();
  4730. retry_avoidcopy:
  4731. /*
  4732. * If no-one else is actually using this page, we're the exclusive
  4733. * owner and can reuse this page.
  4734. *
  4735. * Note that we don't rely on the (safer) folio refcount here, because
  4736. * copying the hugetlb folio when there are unexpected (temporary)
  4737. * folio references could harm simple fork()+exit() users when
  4738. * we run out of free hugetlb folios: we would have to kill processes
  4739. * in scenarios that used to work. As a side effect, there can still
  4740. * be leaks between processes, for example, with FOLL_GET users.
  4741. */
  4742. if (folio_mapcount(old_folio) == 1 && folio_test_anon(old_folio)) {
  4743. if (!PageAnonExclusive(&old_folio->page)) {
  4744. folio_move_anon_rmap(old_folio, vma);
  4745. SetPageAnonExclusive(&old_folio->page);
  4746. }
  4747. if (likely(!unshare))
  4748. set_huge_ptep_maybe_writable(vma, vmf->address,
  4749. vmf->pte);
  4750. delayacct_wpcopy_end();
  4751. return 0;
  4752. }
  4753. VM_BUG_ON_PAGE(folio_test_anon(old_folio) &&
  4754. PageAnonExclusive(&old_folio->page), &old_folio->page);
  4755. /*
  4756. * If the process that created a MAP_PRIVATE mapping is about to perform
  4757. * a COW due to a shared page count, attempt to satisfy the allocation
  4758. * without using the existing reserves.
  4759. * In order to determine where this is a COW on a MAP_PRIVATE mapping it
  4760. * is enough to check whether the old_folio is anonymous. This means that
  4761. * the reserve for this address was consumed. If reserves were used, a
  4762. * partial faulted mapping at the fime of fork() could consume its reserves
  4763. * on COW instead of the full address range.
  4764. */
  4765. if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
  4766. folio_test_anon(old_folio))
  4767. cow_from_owner = true;
  4768. folio_get(old_folio);
  4769. /*
  4770. * Drop page table lock as buddy allocator may be called. It will
  4771. * be acquired again before returning to the caller, as expected.
  4772. */
  4773. spin_unlock(vmf->ptl);
  4774. new_folio = alloc_hugetlb_folio(vma, vmf->address, cow_from_owner);
  4775. if (IS_ERR(new_folio)) {
  4776. /*
  4777. * If a process owning a MAP_PRIVATE mapping fails to COW,
  4778. * it is due to references held by a child and an insufficient
  4779. * huge page pool. To guarantee the original mappers
  4780. * reliability, unmap the page from child processes. The child
  4781. * may get SIGKILLed if it later faults.
  4782. */
  4783. if (cow_from_owner) {
  4784. struct address_space *mapping = vma->vm_file->f_mapping;
  4785. pgoff_t idx;
  4786. u32 hash;
  4787. folio_put(old_folio);
  4788. /*
  4789. * Drop hugetlb_fault_mutex and vma_lock before
  4790. * unmapping. unmapping needs to hold vma_lock
  4791. * in write mode. Dropping vma_lock in read mode
  4792. * here is OK as COW mappings do not interact with
  4793. * PMD sharing.
  4794. *
  4795. * Reacquire both after unmap operation.
  4796. */
  4797. idx = vma_hugecache_offset(h, vma, vmf->address);
  4798. hash = hugetlb_fault_mutex_hash(mapping, idx);
  4799. hugetlb_vma_unlock_read(vma);
  4800. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  4801. unmap_ref_private(mm, vma, old_folio, vmf->address);
  4802. mutex_lock(&hugetlb_fault_mutex_table[hash]);
  4803. hugetlb_vma_lock_read(vma);
  4804. spin_lock(vmf->ptl);
  4805. vmf->pte = hugetlb_walk(vma, vmf->address,
  4806. huge_page_size(h));
  4807. if (likely(vmf->pte &&
  4808. pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte)))
  4809. goto retry_avoidcopy;
  4810. /*
  4811. * race occurs while re-acquiring page table
  4812. * lock, and our job is done.
  4813. */
  4814. delayacct_wpcopy_end();
  4815. return 0;
  4816. }
  4817. ret = vmf_error(PTR_ERR(new_folio));
  4818. goto out_release_old;
  4819. }
  4820. /*
  4821. * When the original hugepage is shared one, it does not have
  4822. * anon_vma prepared.
  4823. */
  4824. ret = __vmf_anon_prepare(vmf);
  4825. if (unlikely(ret))
  4826. goto out_release_all;
  4827. if (copy_user_large_folio(new_folio, old_folio, vmf->real_address, vma)) {
  4828. ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h));
  4829. goto out_release_all;
  4830. }
  4831. __folio_mark_uptodate(new_folio);
  4832. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, vmf->address,
  4833. vmf->address + huge_page_size(h));
  4834. mmu_notifier_invalidate_range_start(&range);
  4835. /*
  4836. * Retake the page table lock to check for racing updates
  4837. * before the page tables are altered
  4838. */
  4839. spin_lock(vmf->ptl);
  4840. vmf->pte = hugetlb_walk(vma, vmf->address, huge_page_size(h));
  4841. if (likely(vmf->pte && pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte))) {
  4842. pte_t newpte = make_huge_pte(vma, new_folio, !unshare);
  4843. /* Break COW or unshare */
  4844. huge_ptep_clear_flush(vma, vmf->address, vmf->pte);
  4845. hugetlb_remove_rmap(old_folio);
  4846. hugetlb_add_new_anon_rmap(new_folio, vma, vmf->address);
  4847. if (huge_pte_uffd_wp(pte))
  4848. newpte = huge_pte_mkuffd_wp(newpte);
  4849. set_huge_pte_at(mm, vmf->address, vmf->pte, newpte,
  4850. huge_page_size(h));
  4851. folio_set_hugetlb_migratable(new_folio);
  4852. /* Make the old page be freed below */
  4853. new_folio = old_folio;
  4854. }
  4855. spin_unlock(vmf->ptl);
  4856. mmu_notifier_invalidate_range_end(&range);
  4857. out_release_all:
  4858. /*
  4859. * No restore in case of successful pagetable update (Break COW or
  4860. * unshare)
  4861. */
  4862. if (new_folio != old_folio)
  4863. restore_reserve_on_error(h, vma, vmf->address, new_folio);
  4864. folio_put(new_folio);
  4865. out_release_old:
  4866. folio_put(old_folio);
  4867. spin_lock(vmf->ptl); /* Caller expects lock to be held */
  4868. delayacct_wpcopy_end();
  4869. return ret;
  4870. }
  4871. /*
  4872. * Return whether there is a pagecache page to back given address within VMA.
  4873. */
  4874. bool hugetlbfs_pagecache_present(struct hstate *h,
  4875. struct vm_area_struct *vma, unsigned long address)
  4876. {
  4877. struct address_space *mapping = vma->vm_file->f_mapping;
  4878. pgoff_t idx = linear_page_index(vma, address);
  4879. struct folio *folio;
  4880. folio = filemap_get_folio(mapping, idx);
  4881. if (IS_ERR(folio))
  4882. return false;
  4883. folio_put(folio);
  4884. return true;
  4885. }
  4886. int hugetlb_add_to_page_cache(struct folio *folio, struct address_space *mapping,
  4887. pgoff_t idx)
  4888. {
  4889. struct inode *inode = mapping->host;
  4890. struct hstate *h = hstate_inode(inode);
  4891. int err;
  4892. idx <<= huge_page_order(h);
  4893. __folio_set_locked(folio);
  4894. err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
  4895. if (unlikely(err)) {
  4896. __folio_clear_locked(folio);
  4897. return err;
  4898. }
  4899. folio_clear_hugetlb_restore_reserve(folio);
  4900. /*
  4901. * mark folio dirty so that it will not be removed from cache/file
  4902. * by non-hugetlbfs specific code paths.
  4903. */
  4904. folio_mark_dirty(folio);
  4905. spin_lock(&inode->i_lock);
  4906. inode->i_blocks += blocks_per_huge_page(h);
  4907. spin_unlock(&inode->i_lock);
  4908. return 0;
  4909. }
  4910. static inline vm_fault_t hugetlb_handle_userfault(struct vm_fault *vmf,
  4911. struct address_space *mapping,
  4912. unsigned long reason)
  4913. {
  4914. u32 hash;
  4915. /*
  4916. * vma_lock and hugetlb_fault_mutex must be dropped before handling
  4917. * userfault. Also mmap_lock could be dropped due to handling
  4918. * userfault, any vma operation should be careful from here.
  4919. */
  4920. hugetlb_vma_unlock_read(vmf->vma);
  4921. hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
  4922. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  4923. return handle_userfault(vmf, reason);
  4924. }
  4925. /*
  4926. * Recheck pte with pgtable lock. Returns true if pte didn't change, or
  4927. * false if pte changed or is changing.
  4928. */
  4929. static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm, unsigned long addr,
  4930. pte_t *ptep, pte_t old_pte)
  4931. {
  4932. spinlock_t *ptl;
  4933. bool same;
  4934. ptl = huge_pte_lock(h, mm, ptep);
  4935. same = pte_same(huge_ptep_get(mm, addr, ptep), old_pte);
  4936. spin_unlock(ptl);
  4937. return same;
  4938. }
  4939. static vm_fault_t hugetlb_no_page(struct address_space *mapping,
  4940. struct vm_fault *vmf)
  4941. {
  4942. u32 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
  4943. bool new_folio, new_anon_folio = false;
  4944. struct vm_area_struct *vma = vmf->vma;
  4945. struct mm_struct *mm = vma->vm_mm;
  4946. struct hstate *h = hstate_vma(vma);
  4947. vm_fault_t ret = VM_FAULT_SIGBUS;
  4948. bool folio_locked = true;
  4949. struct folio *folio;
  4950. unsigned long size;
  4951. pte_t new_pte;
  4952. /*
  4953. * Currently, we are forced to kill the process in the event the
  4954. * original mapper has unmapped pages from the child due to a failed
  4955. * COW/unsharing. Warn that such a situation has occurred as it may not
  4956. * be obvious.
  4957. */
  4958. if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
  4959. pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
  4960. current->pid);
  4961. goto out;
  4962. }
  4963. /*
  4964. * Use page lock to guard against racing truncation
  4965. * before we get page_table_lock.
  4966. */
  4967. new_folio = false;
  4968. folio = filemap_lock_hugetlb_folio(h, mapping, vmf->pgoff);
  4969. if (IS_ERR(folio)) {
  4970. size = i_size_read(mapping->host) >> huge_page_shift(h);
  4971. if (vmf->pgoff >= size)
  4972. goto out;
  4973. /* Check for page in userfault range */
  4974. if (userfaultfd_missing(vma)) {
  4975. /*
  4976. * Since hugetlb_no_page() was examining pte
  4977. * without pgtable lock, we need to re-test under
  4978. * lock because the pte may not be stable and could
  4979. * have changed from under us. Try to detect
  4980. * either changed or during-changing ptes and retry
  4981. * properly when needed.
  4982. *
  4983. * Note that userfaultfd is actually fine with
  4984. * false positives (e.g. caused by pte changed),
  4985. * but not wrong logical events (e.g. caused by
  4986. * reading a pte during changing). The latter can
  4987. * confuse the userspace, so the strictness is very
  4988. * much preferred. E.g., MISSING event should
  4989. * never happen on the page after UFFDIO_COPY has
  4990. * correctly installed the page and returned.
  4991. */
  4992. if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
  4993. ret = 0;
  4994. goto out;
  4995. }
  4996. return hugetlb_handle_userfault(vmf, mapping,
  4997. VM_UFFD_MISSING);
  4998. }
  4999. if (!(vma->vm_flags & VM_MAYSHARE)) {
  5000. ret = __vmf_anon_prepare(vmf);
  5001. if (unlikely(ret))
  5002. goto out;
  5003. }
  5004. folio = alloc_hugetlb_folio(vma, vmf->address, false);
  5005. if (IS_ERR(folio)) {
  5006. /*
  5007. * Returning error will result in faulting task being
  5008. * sent SIGBUS. The hugetlb fault mutex prevents two
  5009. * tasks from racing to fault in the same page which
  5010. * could result in false unable to allocate errors.
  5011. * Page migration does not take the fault mutex, but
  5012. * does a clear then write of pte's under page table
  5013. * lock. Page fault code could race with migration,
  5014. * notice the clear pte and try to allocate a page
  5015. * here. Before returning error, get ptl and make
  5016. * sure there really is no pte entry.
  5017. */
  5018. if (hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte))
  5019. ret = vmf_error(PTR_ERR(folio));
  5020. else
  5021. ret = 0;
  5022. goto out;
  5023. }
  5024. folio_zero_user(folio, vmf->real_address);
  5025. __folio_mark_uptodate(folio);
  5026. new_folio = true;
  5027. if (vma->vm_flags & VM_MAYSHARE) {
  5028. int err = hugetlb_add_to_page_cache(folio, mapping,
  5029. vmf->pgoff);
  5030. if (err) {
  5031. /*
  5032. * err can't be -EEXIST which implies someone
  5033. * else consumed the reservation since hugetlb
  5034. * fault mutex is held when add a hugetlb page
  5035. * to the page cache. So it's safe to call
  5036. * restore_reserve_on_error() here.
  5037. */
  5038. restore_reserve_on_error(h, vma, vmf->address,
  5039. folio);
  5040. folio_put(folio);
  5041. ret = VM_FAULT_SIGBUS;
  5042. goto out;
  5043. }
  5044. } else {
  5045. new_anon_folio = true;
  5046. folio_lock(folio);
  5047. }
  5048. } else {
  5049. /*
  5050. * If memory error occurs between mmap() and fault, some process
  5051. * don't have hwpoisoned swap entry for errored virtual address.
  5052. * So we need to block hugepage fault by PG_hwpoison bit check.
  5053. */
  5054. if (unlikely(folio_test_hwpoison(folio))) {
  5055. ret = VM_FAULT_HWPOISON_LARGE |
  5056. VM_FAULT_SET_HINDEX(hstate_index(h));
  5057. goto backout_unlocked;
  5058. }
  5059. /* Check for page in userfault range. */
  5060. if (userfaultfd_minor(vma)) {
  5061. folio_unlock(folio);
  5062. folio_put(folio);
  5063. /* See comment in userfaultfd_missing() block above */
  5064. if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
  5065. ret = 0;
  5066. goto out;
  5067. }
  5068. return hugetlb_handle_userfault(vmf, mapping,
  5069. VM_UFFD_MINOR);
  5070. }
  5071. }
  5072. /*
  5073. * If we are going to COW a private mapping later, we examine the
  5074. * pending reservations for this page now. This will ensure that
  5075. * any allocations necessary to record that reservation occur outside
  5076. * the spinlock.
  5077. */
  5078. if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
  5079. if (vma_needs_reservation(h, vma, vmf->address) < 0) {
  5080. ret = VM_FAULT_OOM;
  5081. goto backout_unlocked;
  5082. }
  5083. /* Just decrements count, does not deallocate */
  5084. vma_end_reservation(h, vma, vmf->address);
  5085. }
  5086. vmf->ptl = huge_pte_lock(h, mm, vmf->pte);
  5087. ret = 0;
  5088. /* If pte changed from under us, retry */
  5089. if (!pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), vmf->orig_pte))
  5090. goto backout;
  5091. if (new_anon_folio)
  5092. hugetlb_add_new_anon_rmap(folio, vma, vmf->address);
  5093. else
  5094. hugetlb_add_file_rmap(folio);
  5095. new_pte = make_huge_pte(vma, folio, vma->vm_flags & VM_SHARED);
  5096. /*
  5097. * If this pte was previously wr-protected, keep it wr-protected even
  5098. * if populated.
  5099. */
  5100. if (unlikely(pte_is_uffd_wp_marker(vmf->orig_pte)))
  5101. new_pte = huge_pte_mkuffd_wp(new_pte);
  5102. set_huge_pte_at(mm, vmf->address, vmf->pte, new_pte, huge_page_size(h));
  5103. hugetlb_count_add(pages_per_huge_page(h), mm);
  5104. if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
  5105. /*
  5106. * No need to keep file folios locked. See comment in
  5107. * hugetlb_fault().
  5108. */
  5109. if (!new_anon_folio) {
  5110. folio_locked = false;
  5111. folio_unlock(folio);
  5112. }
  5113. /* Optimization, do the COW without a second fault */
  5114. ret = hugetlb_wp(vmf);
  5115. }
  5116. spin_unlock(vmf->ptl);
  5117. /*
  5118. * Only set hugetlb_migratable in newly allocated pages. Existing pages
  5119. * found in the pagecache may not have hugetlb_migratable if they have
  5120. * been isolated for migration.
  5121. */
  5122. if (new_folio)
  5123. folio_set_hugetlb_migratable(folio);
  5124. if (folio_locked)
  5125. folio_unlock(folio);
  5126. out:
  5127. hugetlb_vma_unlock_read(vma);
  5128. /*
  5129. * We must check to release the per-VMA lock. __vmf_anon_prepare() is
  5130. * the only way ret can be set to VM_FAULT_RETRY.
  5131. */
  5132. if (unlikely(ret & VM_FAULT_RETRY))
  5133. vma_end_read(vma);
  5134. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  5135. return ret;
  5136. backout:
  5137. spin_unlock(vmf->ptl);
  5138. backout_unlocked:
  5139. /* We only need to restore reservations for private mappings */
  5140. if (new_anon_folio)
  5141. restore_reserve_on_error(h, vma, vmf->address, folio);
  5142. folio_unlock(folio);
  5143. folio_put(folio);
  5144. goto out;
  5145. }
  5146. #ifdef CONFIG_SMP
  5147. u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
  5148. {
  5149. unsigned long key[2];
  5150. u32 hash;
  5151. key[0] = (unsigned long) mapping;
  5152. key[1] = idx;
  5153. hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
  5154. return hash & (num_fault_mutexes - 1);
  5155. }
  5156. #else
  5157. /*
  5158. * For uniprocessor systems we always use a single mutex, so just
  5159. * return 0 and avoid the hashing overhead.
  5160. */
  5161. u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
  5162. {
  5163. return 0;
  5164. }
  5165. #endif
  5166. vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
  5167. unsigned long address, unsigned int flags)
  5168. {
  5169. vm_fault_t ret;
  5170. u32 hash;
  5171. struct folio *folio = NULL;
  5172. struct hstate *h = hstate_vma(vma);
  5173. struct address_space *mapping;
  5174. bool need_wait_lock = false;
  5175. struct vm_fault vmf = {
  5176. .vma = vma,
  5177. .address = address & huge_page_mask(h),
  5178. .real_address = address,
  5179. .flags = flags,
  5180. .pgoff = vma_hugecache_offset(h, vma,
  5181. address & huge_page_mask(h)),
  5182. /* TODO: Track hugetlb faults using vm_fault */
  5183. /*
  5184. * Some fields may not be initialized, be careful as it may
  5185. * be hard to debug if called functions make assumptions
  5186. */
  5187. };
  5188. /*
  5189. * Serialize hugepage allocation and instantiation, so that we don't
  5190. * get spurious allocation failures if two CPUs race to instantiate
  5191. * the same page in the page cache.
  5192. */
  5193. mapping = vma->vm_file->f_mapping;
  5194. hash = hugetlb_fault_mutex_hash(mapping, vmf.pgoff);
  5195. mutex_lock(&hugetlb_fault_mutex_table[hash]);
  5196. /*
  5197. * Acquire vma lock before calling huge_pte_alloc and hold
  5198. * until finished with vmf.pte. This prevents huge_pmd_unshare from
  5199. * being called elsewhere and making the vmf.pte no longer valid.
  5200. */
  5201. hugetlb_vma_lock_read(vma);
  5202. vmf.pte = huge_pte_alloc(mm, vma, vmf.address, huge_page_size(h));
  5203. if (!vmf.pte) {
  5204. hugetlb_vma_unlock_read(vma);
  5205. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  5206. return VM_FAULT_OOM;
  5207. }
  5208. vmf.orig_pte = huge_ptep_get(mm, vmf.address, vmf.pte);
  5209. if (huge_pte_none(vmf.orig_pte))
  5210. /*
  5211. * hugetlb_no_page will drop vma lock and hugetlb fault
  5212. * mutex internally, which make us return immediately.
  5213. */
  5214. return hugetlb_no_page(mapping, &vmf);
  5215. if (pte_is_marker(vmf.orig_pte)) {
  5216. const pte_marker marker =
  5217. softleaf_to_marker(softleaf_from_pte(vmf.orig_pte));
  5218. if (marker & PTE_MARKER_POISONED) {
  5219. ret = VM_FAULT_HWPOISON_LARGE |
  5220. VM_FAULT_SET_HINDEX(hstate_index(h));
  5221. goto out_mutex;
  5222. } else if (WARN_ON_ONCE(marker & PTE_MARKER_GUARD)) {
  5223. /* This isn't supported in hugetlb. */
  5224. ret = VM_FAULT_SIGSEGV;
  5225. goto out_mutex;
  5226. }
  5227. return hugetlb_no_page(mapping, &vmf);
  5228. }
  5229. ret = 0;
  5230. /* Not present, either a migration or a hwpoisoned entry */
  5231. if (!pte_present(vmf.orig_pte) && !huge_pte_none(vmf.orig_pte)) {
  5232. const softleaf_t softleaf = softleaf_from_pte(vmf.orig_pte);
  5233. if (softleaf_is_migration(softleaf)) {
  5234. /*
  5235. * Release the hugetlb fault lock now, but retain
  5236. * the vma lock, because it is needed to guard the
  5237. * huge_pte_lockptr() later in
  5238. * migration_entry_wait_huge(). The vma lock will
  5239. * be released there.
  5240. */
  5241. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  5242. migration_entry_wait_huge(vma, vmf.address, vmf.pte);
  5243. return 0;
  5244. }
  5245. if (softleaf_is_hwpoison(softleaf)) {
  5246. ret = VM_FAULT_HWPOISON_LARGE |
  5247. VM_FAULT_SET_HINDEX(hstate_index(h));
  5248. }
  5249. goto out_mutex;
  5250. }
  5251. /*
  5252. * If we are going to COW/unshare the mapping later, we examine the
  5253. * pending reservations for this page now. This will ensure that any
  5254. * allocations necessary to record that reservation occur outside the
  5255. * spinlock.
  5256. */
  5257. if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
  5258. !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(vmf.orig_pte)) {
  5259. if (vma_needs_reservation(h, vma, vmf.address) < 0) {
  5260. ret = VM_FAULT_OOM;
  5261. goto out_mutex;
  5262. }
  5263. /* Just decrements count, does not deallocate */
  5264. vma_end_reservation(h, vma, vmf.address);
  5265. }
  5266. vmf.ptl = huge_pte_lock(h, mm, vmf.pte);
  5267. /* Check for a racing update before calling hugetlb_wp() */
  5268. if (unlikely(!pte_same(vmf.orig_pte, huge_ptep_get(mm, vmf.address, vmf.pte))))
  5269. goto out_ptl;
  5270. /* Handle userfault-wp first, before trying to lock more pages */
  5271. if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(mm, vmf.address, vmf.pte)) &&
  5272. (flags & FAULT_FLAG_WRITE) && !huge_pte_write(vmf.orig_pte)) {
  5273. if (!userfaultfd_wp_async(vma)) {
  5274. spin_unlock(vmf.ptl);
  5275. hugetlb_vma_unlock_read(vma);
  5276. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  5277. return handle_userfault(&vmf, VM_UFFD_WP);
  5278. }
  5279. vmf.orig_pte = huge_pte_clear_uffd_wp(vmf.orig_pte);
  5280. set_huge_pte_at(mm, vmf.address, vmf.pte, vmf.orig_pte,
  5281. huge_page_size(hstate_vma(vma)));
  5282. /* Fallthrough to CoW */
  5283. }
  5284. if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
  5285. if (!huge_pte_write(vmf.orig_pte)) {
  5286. /*
  5287. * Anonymous folios need to be lock since hugetlb_wp()
  5288. * checks whether we can re-use the folio exclusively
  5289. * for us in case we are the only user of it.
  5290. */
  5291. folio = page_folio(pte_page(vmf.orig_pte));
  5292. if (folio_test_anon(folio) && !folio_trylock(folio)) {
  5293. need_wait_lock = true;
  5294. goto out_ptl;
  5295. }
  5296. folio_get(folio);
  5297. ret = hugetlb_wp(&vmf);
  5298. if (folio_test_anon(folio))
  5299. folio_unlock(folio);
  5300. folio_put(folio);
  5301. goto out_ptl;
  5302. } else if (likely(flags & FAULT_FLAG_WRITE)) {
  5303. vmf.orig_pte = huge_pte_mkdirty(vmf.orig_pte);
  5304. }
  5305. }
  5306. vmf.orig_pte = pte_mkyoung(vmf.orig_pte);
  5307. if (huge_ptep_set_access_flags(vma, vmf.address, vmf.pte, vmf.orig_pte,
  5308. flags & FAULT_FLAG_WRITE))
  5309. update_mmu_cache(vma, vmf.address, vmf.pte);
  5310. out_ptl:
  5311. spin_unlock(vmf.ptl);
  5312. out_mutex:
  5313. hugetlb_vma_unlock_read(vma);
  5314. /*
  5315. * We must check to release the per-VMA lock. __vmf_anon_prepare() in
  5316. * hugetlb_wp() is the only way ret can be set to VM_FAULT_RETRY.
  5317. */
  5318. if (unlikely(ret & VM_FAULT_RETRY))
  5319. vma_end_read(vma);
  5320. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  5321. /*
  5322. * hugetlb_wp drops all the locks, but the folio lock, before trying to
  5323. * unmap the folio from other processes. During that window, if another
  5324. * process mapping that folio faults in, it will take the mutex and then
  5325. * it will wait on folio_lock, causing an ABBA deadlock.
  5326. * Use trylock instead and bail out if we fail.
  5327. *
  5328. * Ideally, we should hold a refcount on the folio we wait for, but we do
  5329. * not want to use the folio after it becomes unlocked, but rather just
  5330. * wait for it to become unlocked, so hopefully next fault successes on
  5331. * the trylock.
  5332. */
  5333. if (need_wait_lock)
  5334. folio_wait_locked(folio);
  5335. return ret;
  5336. }
  5337. #ifdef CONFIG_USERFAULTFD
  5338. /*
  5339. * Can probably be eliminated, but still used by hugetlb_mfill_atomic_pte().
  5340. */
  5341. static struct folio *alloc_hugetlb_folio_vma(struct hstate *h,
  5342. struct vm_area_struct *vma, unsigned long address)
  5343. {
  5344. struct mempolicy *mpol;
  5345. nodemask_t *nodemask;
  5346. struct folio *folio;
  5347. gfp_t gfp_mask;
  5348. int node;
  5349. gfp_mask = htlb_alloc_mask(h);
  5350. node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
  5351. /*
  5352. * This is used to allocate a temporary hugetlb to hold the copied
  5353. * content, which will then be copied again to the final hugetlb
  5354. * consuming a reservation. Set the alloc_fallback to false to indicate
  5355. * that breaking the per-node hugetlb pool is not allowed in this case.
  5356. */
  5357. folio = alloc_hugetlb_folio_nodemask(h, node, nodemask, gfp_mask, false);
  5358. mpol_cond_put(mpol);
  5359. return folio;
  5360. }
  5361. /*
  5362. * Used by userfaultfd UFFDIO_* ioctls. Based on userfaultfd's mfill_atomic_pte
  5363. * with modifications for hugetlb pages.
  5364. */
  5365. int hugetlb_mfill_atomic_pte(pte_t *dst_pte,
  5366. struct vm_area_struct *dst_vma,
  5367. unsigned long dst_addr,
  5368. unsigned long src_addr,
  5369. uffd_flags_t flags,
  5370. struct folio **foliop)
  5371. {
  5372. struct mm_struct *dst_mm = dst_vma->vm_mm;
  5373. bool is_continue = uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE);
  5374. bool wp_enabled = (flags & MFILL_ATOMIC_WP);
  5375. struct hstate *h = hstate_vma(dst_vma);
  5376. struct address_space *mapping = dst_vma->vm_file->f_mapping;
  5377. pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
  5378. unsigned long size = huge_page_size(h);
  5379. int vm_shared = dst_vma->vm_flags & VM_SHARED;
  5380. pte_t _dst_pte;
  5381. spinlock_t *ptl;
  5382. int ret = -ENOMEM;
  5383. struct folio *folio;
  5384. bool folio_in_pagecache = false;
  5385. pte_t dst_ptep;
  5386. if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
  5387. ptl = huge_pte_lock(h, dst_mm, dst_pte);
  5388. /* Don't overwrite any existing PTEs (even markers) */
  5389. if (!huge_pte_none(huge_ptep_get(dst_mm, dst_addr, dst_pte))) {
  5390. spin_unlock(ptl);
  5391. return -EEXIST;
  5392. }
  5393. _dst_pte = make_pte_marker(PTE_MARKER_POISONED);
  5394. set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
  5395. /* No need to invalidate - it was non-present before */
  5396. update_mmu_cache(dst_vma, dst_addr, dst_pte);
  5397. spin_unlock(ptl);
  5398. return 0;
  5399. }
  5400. if (is_continue) {
  5401. ret = -EFAULT;
  5402. folio = filemap_lock_hugetlb_folio(h, mapping, idx);
  5403. if (IS_ERR(folio))
  5404. goto out;
  5405. folio_in_pagecache = true;
  5406. } else if (!*foliop) {
  5407. /* If a folio already exists, then it's UFFDIO_COPY for
  5408. * a non-missing case. Return -EEXIST.
  5409. */
  5410. if (vm_shared &&
  5411. hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
  5412. ret = -EEXIST;
  5413. goto out;
  5414. }
  5415. folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
  5416. if (IS_ERR(folio)) {
  5417. pte_t *actual_pte = hugetlb_walk(dst_vma, dst_addr, PMD_SIZE);
  5418. if (actual_pte) {
  5419. ret = -EEXIST;
  5420. goto out;
  5421. }
  5422. ret = -ENOMEM;
  5423. goto out;
  5424. }
  5425. ret = copy_folio_from_user(folio, (const void __user *) src_addr,
  5426. false);
  5427. /* fallback to copy_from_user outside mmap_lock */
  5428. if (unlikely(ret)) {
  5429. ret = -ENOENT;
  5430. /* Free the allocated folio which may have
  5431. * consumed a reservation.
  5432. */
  5433. restore_reserve_on_error(h, dst_vma, dst_addr, folio);
  5434. folio_put(folio);
  5435. /* Allocate a temporary folio to hold the copied
  5436. * contents.
  5437. */
  5438. folio = alloc_hugetlb_folio_vma(h, dst_vma, dst_addr);
  5439. if (!folio) {
  5440. ret = -ENOMEM;
  5441. goto out;
  5442. }
  5443. *foliop = folio;
  5444. /* Set the outparam foliop and return to the caller to
  5445. * copy the contents outside the lock. Don't free the
  5446. * folio.
  5447. */
  5448. goto out;
  5449. }
  5450. } else {
  5451. if (vm_shared &&
  5452. hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
  5453. folio_put(*foliop);
  5454. ret = -EEXIST;
  5455. *foliop = NULL;
  5456. goto out;
  5457. }
  5458. folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
  5459. if (IS_ERR(folio)) {
  5460. folio_put(*foliop);
  5461. ret = -ENOMEM;
  5462. *foliop = NULL;
  5463. goto out;
  5464. }
  5465. ret = copy_user_large_folio(folio, *foliop, dst_addr, dst_vma);
  5466. folio_put(*foliop);
  5467. *foliop = NULL;
  5468. if (ret) {
  5469. folio_put(folio);
  5470. goto out;
  5471. }
  5472. }
  5473. /*
  5474. * If we just allocated a new page, we need a memory barrier to ensure
  5475. * that preceding stores to the page become visible before the
  5476. * set_pte_at() write. The memory barrier inside __folio_mark_uptodate
  5477. * is what we need.
  5478. *
  5479. * In the case where we have not allocated a new page (is_continue),
  5480. * the page must already be uptodate. UFFDIO_CONTINUE already includes
  5481. * an earlier smp_wmb() to ensure that prior stores will be visible
  5482. * before the set_pte_at() write.
  5483. */
  5484. if (!is_continue)
  5485. __folio_mark_uptodate(folio);
  5486. else
  5487. WARN_ON_ONCE(!folio_test_uptodate(folio));
  5488. /* Add shared, newly allocated pages to the page cache. */
  5489. if (vm_shared && !is_continue) {
  5490. ret = -EFAULT;
  5491. if (idx >= (i_size_read(mapping->host) >> huge_page_shift(h)))
  5492. goto out_release_nounlock;
  5493. /*
  5494. * Serialization between remove_inode_hugepages() and
  5495. * hugetlb_add_to_page_cache() below happens through the
  5496. * hugetlb_fault_mutex_table that here must be hold by
  5497. * the caller.
  5498. */
  5499. ret = hugetlb_add_to_page_cache(folio, mapping, idx);
  5500. if (ret)
  5501. goto out_release_nounlock;
  5502. folio_in_pagecache = true;
  5503. }
  5504. ptl = huge_pte_lock(h, dst_mm, dst_pte);
  5505. ret = -EIO;
  5506. if (folio_test_hwpoison(folio))
  5507. goto out_release_unlock;
  5508. ret = -EEXIST;
  5509. dst_ptep = huge_ptep_get(dst_mm, dst_addr, dst_pte);
  5510. /*
  5511. * See comment about UFFD marker overwriting in
  5512. * mfill_atomic_install_pte().
  5513. */
  5514. if (!huge_pte_none(dst_ptep) && !pte_is_uffd_marker(dst_ptep))
  5515. goto out_release_unlock;
  5516. if (folio_in_pagecache)
  5517. hugetlb_add_file_rmap(folio);
  5518. else
  5519. hugetlb_add_new_anon_rmap(folio, dst_vma, dst_addr);
  5520. /*
  5521. * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
  5522. * with wp flag set, don't set pte write bit.
  5523. */
  5524. _dst_pte = make_huge_pte(dst_vma, folio,
  5525. !wp_enabled && !(is_continue && !vm_shared));
  5526. /*
  5527. * Always mark UFFDIO_COPY page dirty; note that this may not be
  5528. * extremely important for hugetlbfs for now since swapping is not
  5529. * supported, but we should still be clear in that this page cannot be
  5530. * thrown away at will, even if write bit not set.
  5531. */
  5532. _dst_pte = huge_pte_mkdirty(_dst_pte);
  5533. _dst_pte = pte_mkyoung(_dst_pte);
  5534. if (wp_enabled)
  5535. _dst_pte = huge_pte_mkuffd_wp(_dst_pte);
  5536. set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
  5537. hugetlb_count_add(pages_per_huge_page(h), dst_mm);
  5538. /* No need to invalidate - it was non-present before */
  5539. update_mmu_cache(dst_vma, dst_addr, dst_pte);
  5540. spin_unlock(ptl);
  5541. if (!is_continue)
  5542. folio_set_hugetlb_migratable(folio);
  5543. if (vm_shared || is_continue)
  5544. folio_unlock(folio);
  5545. ret = 0;
  5546. out:
  5547. return ret;
  5548. out_release_unlock:
  5549. spin_unlock(ptl);
  5550. if (vm_shared || is_continue)
  5551. folio_unlock(folio);
  5552. out_release_nounlock:
  5553. if (!folio_in_pagecache)
  5554. restore_reserve_on_error(h, dst_vma, dst_addr, folio);
  5555. folio_put(folio);
  5556. goto out;
  5557. }
  5558. #endif /* CONFIG_USERFAULTFD */
  5559. long hugetlb_change_protection(struct vm_area_struct *vma,
  5560. unsigned long address, unsigned long end,
  5561. pgprot_t newprot, unsigned long cp_flags)
  5562. {
  5563. struct mm_struct *mm = vma->vm_mm;
  5564. unsigned long start = address;
  5565. pte_t *ptep;
  5566. pte_t pte;
  5567. struct hstate *h = hstate_vma(vma);
  5568. long pages = 0, psize = huge_page_size(h);
  5569. struct mmu_notifier_range range;
  5570. unsigned long last_addr_mask;
  5571. bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
  5572. bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
  5573. struct mmu_gather tlb;
  5574. /*
  5575. * In the case of shared PMDs, the area to flush could be beyond
  5576. * start/end. Set range.start/range.end to cover the maximum possible
  5577. * range if PMD sharing is possible.
  5578. */
  5579. mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
  5580. 0, mm, start, end);
  5581. adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
  5582. BUG_ON(address >= end);
  5583. flush_cache_range(vma, range.start, range.end);
  5584. tlb_gather_mmu_vma(&tlb, vma);
  5585. mmu_notifier_invalidate_range_start(&range);
  5586. hugetlb_vma_lock_write(vma);
  5587. i_mmap_lock_write(vma->vm_file->f_mapping);
  5588. last_addr_mask = hugetlb_mask_last_page(h);
  5589. for (; address < end; address += psize) {
  5590. softleaf_t entry;
  5591. spinlock_t *ptl;
  5592. ptep = hugetlb_walk(vma, address, psize);
  5593. if (!ptep) {
  5594. if (!uffd_wp) {
  5595. address |= last_addr_mask;
  5596. continue;
  5597. }
  5598. /*
  5599. * Userfaultfd wr-protect requires pgtable
  5600. * pre-allocations to install pte markers.
  5601. */
  5602. ptep = huge_pte_alloc(mm, vma, address, psize);
  5603. if (!ptep) {
  5604. pages = -ENOMEM;
  5605. break;
  5606. }
  5607. }
  5608. ptl = huge_pte_lock(h, mm, ptep);
  5609. if (huge_pmd_unshare(&tlb, vma, address, ptep)) {
  5610. /*
  5611. * When uffd-wp is enabled on the vma, unshare
  5612. * shouldn't happen at all. Warn about it if it
  5613. * happened due to some reason.
  5614. */
  5615. WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
  5616. pages++;
  5617. spin_unlock(ptl);
  5618. address |= last_addr_mask;
  5619. continue;
  5620. }
  5621. pte = huge_ptep_get(mm, address, ptep);
  5622. if (huge_pte_none(pte)) {
  5623. if (unlikely(uffd_wp))
  5624. /* Safe to modify directly (none->non-present). */
  5625. set_huge_pte_at(mm, address, ptep,
  5626. make_pte_marker(PTE_MARKER_UFFD_WP),
  5627. psize);
  5628. goto next;
  5629. }
  5630. entry = softleaf_from_pte(pte);
  5631. if (unlikely(softleaf_is_hwpoison(entry))) {
  5632. /* Nothing to do. */
  5633. } else if (unlikely(softleaf_is_migration(entry))) {
  5634. struct folio *folio = softleaf_to_folio(entry);
  5635. pte_t newpte = pte;
  5636. if (softleaf_is_migration_write(entry)) {
  5637. if (folio_test_anon(folio))
  5638. entry = make_readable_exclusive_migration_entry(
  5639. swp_offset(entry));
  5640. else
  5641. entry = make_readable_migration_entry(
  5642. swp_offset(entry));
  5643. newpte = swp_entry_to_pte(entry);
  5644. pages++;
  5645. }
  5646. if (uffd_wp)
  5647. newpte = pte_swp_mkuffd_wp(newpte);
  5648. else if (uffd_wp_resolve)
  5649. newpte = pte_swp_clear_uffd_wp(newpte);
  5650. if (!pte_same(pte, newpte))
  5651. set_huge_pte_at(mm, address, ptep, newpte, psize);
  5652. } else if (unlikely(pte_is_marker(pte))) {
  5653. /*
  5654. * Do nothing on a poison marker; page is
  5655. * corrupted, permissions do not apply. Here
  5656. * pte_marker_uffd_wp()==true implies !poison
  5657. * because they're mutual exclusive.
  5658. */
  5659. if (pte_is_uffd_wp_marker(pte) && uffd_wp_resolve)
  5660. /* Safe to modify directly (non-present->none). */
  5661. huge_pte_clear(mm, address, ptep, psize);
  5662. } else {
  5663. pte_t old_pte;
  5664. unsigned int shift = huge_page_shift(hstate_vma(vma));
  5665. old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
  5666. pte = huge_pte_modify(old_pte, newprot);
  5667. pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
  5668. if (uffd_wp)
  5669. pte = huge_pte_mkuffd_wp(pte);
  5670. else if (uffd_wp_resolve)
  5671. pte = huge_pte_clear_uffd_wp(pte);
  5672. huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
  5673. pages++;
  5674. tlb_remove_huge_tlb_entry(h, &tlb, ptep, address);
  5675. }
  5676. next:
  5677. spin_unlock(ptl);
  5678. cond_resched();
  5679. }
  5680. tlb_flush_mmu_tlbonly(&tlb);
  5681. huge_pmd_unshare_flush(&tlb, vma);
  5682. /*
  5683. * No need to call mmu_notifier_arch_invalidate_secondary_tlbs() we are
  5684. * downgrading page table protection not changing it to point to a new
  5685. * page.
  5686. *
  5687. * See Documentation/mm/mmu_notifier.rst
  5688. */
  5689. i_mmap_unlock_write(vma->vm_file->f_mapping);
  5690. hugetlb_vma_unlock_write(vma);
  5691. mmu_notifier_invalidate_range_end(&range);
  5692. tlb_finish_mmu(&tlb);
  5693. return pages > 0 ? (pages << h->order) : pages;
  5694. }
  5695. /*
  5696. * Update the reservation map for the range [from, to].
  5697. *
  5698. * Returns the number of entries that would be added to the reservation map
  5699. * associated with the range [from, to]. This number is greater or equal to
  5700. * zero. -EINVAL or -ENOMEM is returned in case of any errors.
  5701. */
  5702. long hugetlb_reserve_pages(struct inode *inode,
  5703. long from, long to,
  5704. struct vm_area_desc *desc,
  5705. vma_flags_t vma_flags)
  5706. {
  5707. long chg = -1, add = -1, spool_resv, gbl_resv;
  5708. struct hstate *h = hstate_inode(inode);
  5709. struct hugepage_subpool *spool = subpool_inode(inode);
  5710. struct resv_map *resv_map;
  5711. struct hugetlb_cgroup *h_cg = NULL;
  5712. long gbl_reserve, regions_needed = 0;
  5713. int err;
  5714. /* This should never happen */
  5715. if (from > to) {
  5716. VM_WARN(1, "%s called with a negative range\n", __func__);
  5717. return -EINVAL;
  5718. }
  5719. /*
  5720. * Only apply hugepage reservation if asked. At fault time, an
  5721. * attempt will be made for VM_NORESERVE to allocate a page
  5722. * without using reserves
  5723. */
  5724. if (vma_flags_test(&vma_flags, VMA_NORESERVE_BIT))
  5725. return 0;
  5726. /*
  5727. * Shared mappings base their reservation on the number of pages that
  5728. * are already allocated on behalf of the file. Private mappings need
  5729. * to reserve the full area even if read-only as mprotect() may be
  5730. * called to make the mapping read-write. Assume !desc is a shm mapping
  5731. */
  5732. if (!desc || vma_desc_test_flags(desc, VMA_MAYSHARE_BIT)) {
  5733. /*
  5734. * resv_map can not be NULL as hugetlb_reserve_pages is only
  5735. * called for inodes for which resv_maps were created (see
  5736. * hugetlbfs_get_inode).
  5737. */
  5738. resv_map = inode_resv_map(inode);
  5739. chg = region_chg(resv_map, from, to, &regions_needed);
  5740. } else {
  5741. /* Private mapping. */
  5742. resv_map = resv_map_alloc();
  5743. if (!resv_map) {
  5744. err = -ENOMEM;
  5745. goto out_err;
  5746. }
  5747. chg = to - from;
  5748. set_vma_desc_resv_map(desc, resv_map);
  5749. set_vma_desc_resv_flags(desc, HPAGE_RESV_OWNER);
  5750. }
  5751. if (chg < 0) {
  5752. /* region_chg() above can return -ENOMEM */
  5753. err = (chg == -ENOMEM) ? -ENOMEM : -EINVAL;
  5754. goto out_err;
  5755. }
  5756. err = hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
  5757. chg * pages_per_huge_page(h), &h_cg);
  5758. if (err < 0)
  5759. goto out_err;
  5760. if (desc && !vma_desc_test_flags(desc, VMA_MAYSHARE_BIT) && h_cg) {
  5761. /* For private mappings, the hugetlb_cgroup uncharge info hangs
  5762. * of the resv_map.
  5763. */
  5764. resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
  5765. }
  5766. /*
  5767. * There must be enough pages in the subpool for the mapping. If
  5768. * the subpool has a minimum size, there may be some global
  5769. * reservations already in place (gbl_reserve).
  5770. */
  5771. gbl_reserve = hugepage_subpool_get_pages(spool, chg);
  5772. if (gbl_reserve < 0) {
  5773. err = gbl_reserve;
  5774. goto out_uncharge_cgroup;
  5775. }
  5776. /*
  5777. * Check enough hugepages are available for the reservation.
  5778. * Hand the pages back to the subpool if there are not
  5779. */
  5780. err = hugetlb_acct_memory(h, gbl_reserve);
  5781. if (err < 0)
  5782. goto out_put_pages;
  5783. /*
  5784. * Account for the reservations made. Shared mappings record regions
  5785. * that have reservations as they are shared by multiple VMAs.
  5786. * When the last VMA disappears, the region map says how much
  5787. * the reservation was and the page cache tells how much of
  5788. * the reservation was consumed. Private mappings are per-VMA and
  5789. * only the consumed reservations are tracked. When the VMA
  5790. * disappears, the original reservation is the VMA size and the
  5791. * consumed reservations are stored in the map. Hence, nothing
  5792. * else has to be done for private mappings here
  5793. */
  5794. if (!desc || vma_desc_test_flags(desc, VMA_MAYSHARE_BIT)) {
  5795. add = region_add(resv_map, from, to, regions_needed, h, h_cg);
  5796. if (unlikely(add < 0)) {
  5797. hugetlb_acct_memory(h, -gbl_reserve);
  5798. err = add;
  5799. goto out_put_pages;
  5800. } else if (unlikely(chg > add)) {
  5801. /*
  5802. * pages in this range were added to the reserve
  5803. * map between region_chg and region_add. This
  5804. * indicates a race with alloc_hugetlb_folio. Adjust
  5805. * the subpool and reserve counts modified above
  5806. * based on the difference.
  5807. */
  5808. long rsv_adjust;
  5809. /*
  5810. * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
  5811. * reference to h_cg->css. See comment below for detail.
  5812. */
  5813. hugetlb_cgroup_uncharge_cgroup_rsvd(
  5814. hstate_index(h),
  5815. (chg - add) * pages_per_huge_page(h), h_cg);
  5816. rsv_adjust = hugepage_subpool_put_pages(spool,
  5817. chg - add);
  5818. hugetlb_acct_memory(h, -rsv_adjust);
  5819. } else if (h_cg) {
  5820. /*
  5821. * The file_regions will hold their own reference to
  5822. * h_cg->css. So we should release the reference held
  5823. * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
  5824. * done.
  5825. */
  5826. hugetlb_cgroup_put_rsvd_cgroup(h_cg);
  5827. }
  5828. }
  5829. return chg;
  5830. out_put_pages:
  5831. spool_resv = chg - gbl_reserve;
  5832. if (spool_resv) {
  5833. /* put sub pool's reservation back, chg - gbl_reserve */
  5834. gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
  5835. /*
  5836. * subpool's reserved pages can not be put back due to race,
  5837. * return to hstate.
  5838. */
  5839. hugetlb_acct_memory(h, -gbl_resv);
  5840. }
  5841. /* Restore used_hpages for pages that failed global reservation */
  5842. if (gbl_reserve && spool) {
  5843. unsigned long flags;
  5844. spin_lock_irqsave(&spool->lock, flags);
  5845. if (spool->max_hpages != -1)
  5846. spool->used_hpages -= gbl_reserve;
  5847. unlock_or_release_subpool(spool, flags);
  5848. }
  5849. out_uncharge_cgroup:
  5850. hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
  5851. chg * pages_per_huge_page(h), h_cg);
  5852. out_err:
  5853. if (!desc || vma_desc_test_flags(desc, VMA_MAYSHARE_BIT))
  5854. /* Only call region_abort if the region_chg succeeded but the
  5855. * region_add failed or didn't run.
  5856. */
  5857. if (chg >= 0 && add < 0)
  5858. region_abort(resv_map, from, to, regions_needed);
  5859. if (desc && is_vma_desc_resv_set(desc, HPAGE_RESV_OWNER)) {
  5860. kref_put(&resv_map->refs, resv_map_release);
  5861. set_vma_desc_resv_map(desc, NULL);
  5862. }
  5863. return err;
  5864. }
  5865. long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
  5866. long freed)
  5867. {
  5868. struct hstate *h = hstate_inode(inode);
  5869. struct resv_map *resv_map = inode_resv_map(inode);
  5870. long chg = 0;
  5871. struct hugepage_subpool *spool = subpool_inode(inode);
  5872. long gbl_reserve;
  5873. /*
  5874. * Since this routine can be called in the evict inode path for all
  5875. * hugetlbfs inodes, resv_map could be NULL.
  5876. */
  5877. if (resv_map) {
  5878. chg = region_del(resv_map, start, end);
  5879. /*
  5880. * region_del() can fail in the rare case where a region
  5881. * must be split and another region descriptor can not be
  5882. * allocated. If end == LONG_MAX, it will not fail.
  5883. */
  5884. if (chg < 0)
  5885. return chg;
  5886. }
  5887. spin_lock(&inode->i_lock);
  5888. inode->i_blocks -= (blocks_per_huge_page(h) * freed);
  5889. spin_unlock(&inode->i_lock);
  5890. /*
  5891. * If the subpool has a minimum size, the number of global
  5892. * reservations to be released may be adjusted.
  5893. *
  5894. * Note that !resv_map implies freed == 0. So (chg - freed)
  5895. * won't go negative.
  5896. */
  5897. gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
  5898. hugetlb_acct_memory(h, -gbl_reserve);
  5899. return 0;
  5900. }
  5901. #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
  5902. static unsigned long page_table_shareable(struct vm_area_struct *svma,
  5903. struct vm_area_struct *vma,
  5904. unsigned long addr, pgoff_t idx)
  5905. {
  5906. unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
  5907. svma->vm_start;
  5908. unsigned long sbase = saddr & PUD_MASK;
  5909. unsigned long s_end = sbase + PUD_SIZE;
  5910. /* Allow segments to share if only one is marked locked */
  5911. vm_flags_t vm_flags = vma->vm_flags & ~VM_LOCKED_MASK;
  5912. vm_flags_t svm_flags = svma->vm_flags & ~VM_LOCKED_MASK;
  5913. /*
  5914. * match the virtual addresses, permission and the alignment of the
  5915. * page table page.
  5916. *
  5917. * Also, vma_lock (vm_private_data) is required for sharing.
  5918. */
  5919. if (pmd_index(addr) != pmd_index(saddr) ||
  5920. vm_flags != svm_flags ||
  5921. !range_in_vma(svma, sbase, s_end) ||
  5922. !svma->vm_private_data)
  5923. return 0;
  5924. return saddr;
  5925. }
  5926. bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
  5927. {
  5928. unsigned long start = addr & PUD_MASK;
  5929. unsigned long end = start + PUD_SIZE;
  5930. #ifdef CONFIG_USERFAULTFD
  5931. if (uffd_disable_huge_pmd_share(vma))
  5932. return false;
  5933. #endif
  5934. /*
  5935. * check on proper vm_flags and page table alignment
  5936. */
  5937. if (!(vma->vm_flags & VM_MAYSHARE))
  5938. return false;
  5939. if (!vma->vm_private_data) /* vma lock required for sharing */
  5940. return false;
  5941. if (!range_in_vma(vma, start, end))
  5942. return false;
  5943. return true;
  5944. }
  5945. /*
  5946. * Determine if start,end range within vma could be mapped by shared pmd.
  5947. * If yes, adjust start and end to cover range associated with possible
  5948. * shared pmd mappings.
  5949. */
  5950. void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
  5951. unsigned long *start, unsigned long *end)
  5952. {
  5953. unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
  5954. v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
  5955. /*
  5956. * vma needs to span at least one aligned PUD size, and the range
  5957. * must be at least partially within in.
  5958. */
  5959. if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
  5960. (*end <= v_start) || (*start >= v_end))
  5961. return;
  5962. /* Extend the range to be PUD aligned for a worst case scenario */
  5963. if (*start > v_start)
  5964. *start = ALIGN_DOWN(*start, PUD_SIZE);
  5965. if (*end < v_end)
  5966. *end = ALIGN(*end, PUD_SIZE);
  5967. }
  5968. /*
  5969. * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
  5970. * and returns the corresponding pte. While this is not necessary for the
  5971. * !shared pmd case because we can allocate the pmd later as well, it makes the
  5972. * code much cleaner. pmd allocation is essential for the shared case because
  5973. * pud has to be populated inside the same i_mmap_rwsem section - otherwise
  5974. * racing tasks could either miss the sharing (see huge_pte_offset) or select a
  5975. * bad pmd for sharing.
  5976. */
  5977. pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
  5978. unsigned long addr, pud_t *pud)
  5979. {
  5980. struct address_space *mapping = vma->vm_file->f_mapping;
  5981. pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
  5982. vma->vm_pgoff;
  5983. struct vm_area_struct *svma;
  5984. unsigned long saddr;
  5985. pte_t *spte = NULL;
  5986. pte_t *pte;
  5987. i_mmap_lock_read(mapping);
  5988. vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
  5989. if (svma == vma)
  5990. continue;
  5991. saddr = page_table_shareable(svma, vma, addr, idx);
  5992. if (saddr) {
  5993. spte = hugetlb_walk(svma, saddr,
  5994. vma_mmu_pagesize(svma));
  5995. if (spte) {
  5996. ptdesc_pmd_pts_inc(virt_to_ptdesc(spte));
  5997. break;
  5998. }
  5999. }
  6000. }
  6001. if (!spte)
  6002. goto out;
  6003. spin_lock(&mm->page_table_lock);
  6004. if (pud_none(*pud)) {
  6005. pud_populate(mm, pud,
  6006. (pmd_t *)((unsigned long)spte & PAGE_MASK));
  6007. mm_inc_nr_pmds(mm);
  6008. } else {
  6009. ptdesc_pmd_pts_dec(virt_to_ptdesc(spte));
  6010. }
  6011. spin_unlock(&mm->page_table_lock);
  6012. out:
  6013. pte = (pte_t *)pmd_alloc(mm, pud, addr);
  6014. i_mmap_unlock_read(mapping);
  6015. return pte;
  6016. }
  6017. /**
  6018. * huge_pmd_unshare - Unmap a pmd table if it is shared by multiple users
  6019. * @tlb: the current mmu_gather.
  6020. * @vma: the vma covering the pmd table.
  6021. * @addr: the address we are trying to unshare.
  6022. * @ptep: pointer into the (pmd) page table.
  6023. *
  6024. * Called with the page table lock held, the i_mmap_rwsem held in write mode
  6025. * and the hugetlb vma lock held in write mode.
  6026. *
  6027. * Note: The caller must call huge_pmd_unshare_flush() before dropping the
  6028. * i_mmap_rwsem.
  6029. *
  6030. * Returns: 1 if it was a shared PMD table and it got unmapped, or 0 if it
  6031. * was not a shared PMD table.
  6032. */
  6033. int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma,
  6034. unsigned long addr, pte_t *ptep)
  6035. {
  6036. unsigned long sz = huge_page_size(hstate_vma(vma));
  6037. struct mm_struct *mm = vma->vm_mm;
  6038. pgd_t *pgd = pgd_offset(mm, addr);
  6039. p4d_t *p4d = p4d_offset(pgd, addr);
  6040. pud_t *pud = pud_offset(p4d, addr);
  6041. if (sz != PMD_SIZE)
  6042. return 0;
  6043. if (!ptdesc_pmd_is_shared(virt_to_ptdesc(ptep)))
  6044. return 0;
  6045. i_mmap_assert_write_locked(vma->vm_file->f_mapping);
  6046. hugetlb_vma_assert_locked(vma);
  6047. pud_clear(pud);
  6048. tlb_unshare_pmd_ptdesc(tlb, virt_to_ptdesc(ptep), addr);
  6049. mm_dec_nr_pmds(mm);
  6050. return 1;
  6051. }
  6052. /*
  6053. * huge_pmd_unshare_flush - Complete a sequence of huge_pmd_unshare() calls
  6054. * @tlb: the current mmu_gather.
  6055. * @vma: the vma covering the pmd table.
  6056. *
  6057. * Perform necessary TLB flushes or IPI broadcasts to synchronize PMD table
  6058. * unsharing with concurrent page table walkers.
  6059. *
  6060. * This function must be called after a sequence of huge_pmd_unshare()
  6061. * calls while still holding the i_mmap_rwsem.
  6062. */
  6063. void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma)
  6064. {
  6065. /*
  6066. * We must synchronize page table unsharing such that nobody will
  6067. * try reusing a previously-shared page table while it might still
  6068. * be in use by previous sharers (TLB, GUP_fast).
  6069. */
  6070. i_mmap_assert_write_locked(vma->vm_file->f_mapping);
  6071. tlb_flush_unshared_tables(tlb);
  6072. }
  6073. #else /* !CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
  6074. pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
  6075. unsigned long addr, pud_t *pud)
  6076. {
  6077. return NULL;
  6078. }
  6079. int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma,
  6080. unsigned long addr, pte_t *ptep)
  6081. {
  6082. return 0;
  6083. }
  6084. void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma)
  6085. {
  6086. }
  6087. void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
  6088. unsigned long *start, unsigned long *end)
  6089. {
  6090. }
  6091. bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
  6092. {
  6093. return false;
  6094. }
  6095. #endif /* CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
  6096. #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
  6097. pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
  6098. unsigned long addr, unsigned long sz)
  6099. {
  6100. pgd_t *pgd;
  6101. p4d_t *p4d;
  6102. pud_t *pud;
  6103. pte_t *pte = NULL;
  6104. pgd = pgd_offset(mm, addr);
  6105. p4d = p4d_alloc(mm, pgd, addr);
  6106. if (!p4d)
  6107. return NULL;
  6108. pud = pud_alloc(mm, p4d, addr);
  6109. if (pud) {
  6110. if (sz == PUD_SIZE) {
  6111. pte = (pte_t *)pud;
  6112. } else {
  6113. BUG_ON(sz != PMD_SIZE);
  6114. if (want_pmd_share(vma, addr) && pud_none(*pud))
  6115. pte = huge_pmd_share(mm, vma, addr, pud);
  6116. else
  6117. pte = (pte_t *)pmd_alloc(mm, pud, addr);
  6118. }
  6119. }
  6120. if (pte) {
  6121. pte_t pteval = ptep_get_lockless(pte);
  6122. BUG_ON(pte_present(pteval) && !pte_huge(pteval));
  6123. }
  6124. return pte;
  6125. }
  6126. /*
  6127. * huge_pte_offset() - Walk the page table to resolve the hugepage
  6128. * entry at address @addr
  6129. *
  6130. * Return: Pointer to page table entry (PUD or PMD) for
  6131. * address @addr, or NULL if a !p*d_present() entry is encountered and the
  6132. * size @sz doesn't match the hugepage size at this level of the page
  6133. * table.
  6134. */
  6135. pte_t *huge_pte_offset(struct mm_struct *mm,
  6136. unsigned long addr, unsigned long sz)
  6137. {
  6138. pgd_t *pgd;
  6139. p4d_t *p4d;
  6140. pud_t *pud;
  6141. pmd_t *pmd;
  6142. pgd = pgd_offset(mm, addr);
  6143. if (!pgd_present(*pgd))
  6144. return NULL;
  6145. p4d = p4d_offset(pgd, addr);
  6146. if (!p4d_present(*p4d))
  6147. return NULL;
  6148. pud = pud_offset(p4d, addr);
  6149. if (sz == PUD_SIZE)
  6150. /* must be pud huge, non-present or none */
  6151. return (pte_t *)pud;
  6152. if (!pud_present(*pud))
  6153. return NULL;
  6154. /* must have a valid entry and size to go further */
  6155. pmd = pmd_offset(pud, addr);
  6156. /* must be pmd huge, non-present or none */
  6157. return (pte_t *)pmd;
  6158. }
  6159. /*
  6160. * Return a mask that can be used to update an address to the last huge
  6161. * page in a page table page mapping size. Used to skip non-present
  6162. * page table entries when linearly scanning address ranges. Architectures
  6163. * with unique huge page to page table relationships can define their own
  6164. * version of this routine.
  6165. */
  6166. unsigned long hugetlb_mask_last_page(struct hstate *h)
  6167. {
  6168. unsigned long hp_size = huge_page_size(h);
  6169. if (hp_size == PUD_SIZE)
  6170. return P4D_SIZE - PUD_SIZE;
  6171. else if (hp_size == PMD_SIZE)
  6172. return PUD_SIZE - PMD_SIZE;
  6173. else
  6174. return 0UL;
  6175. }
  6176. #else
  6177. /* See description above. Architectures can provide their own version. */
  6178. __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
  6179. {
  6180. #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
  6181. if (huge_page_size(h) == PMD_SIZE)
  6182. return PUD_SIZE - PMD_SIZE;
  6183. #endif
  6184. return 0UL;
  6185. }
  6186. #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
  6187. /**
  6188. * folio_isolate_hugetlb - try to isolate an allocated hugetlb folio
  6189. * @folio: the folio to isolate
  6190. * @list: the list to add the folio to on success
  6191. *
  6192. * Isolate an allocated (refcount > 0) hugetlb folio, marking it as
  6193. * isolated/non-migratable, and moving it from the active list to the
  6194. * given list.
  6195. *
  6196. * Isolation will fail if @folio is not an allocated hugetlb folio, or if
  6197. * it is already isolated/non-migratable.
  6198. *
  6199. * On success, an additional folio reference is taken that must be dropped
  6200. * using folio_putback_hugetlb() to undo the isolation.
  6201. *
  6202. * Return: True if isolation worked, otherwise False.
  6203. */
  6204. bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list)
  6205. {
  6206. bool ret = true;
  6207. spin_lock_irq(&hugetlb_lock);
  6208. if (!folio_test_hugetlb(folio) ||
  6209. !folio_test_hugetlb_migratable(folio) ||
  6210. !folio_try_get(folio)) {
  6211. ret = false;
  6212. goto unlock;
  6213. }
  6214. folio_clear_hugetlb_migratable(folio);
  6215. list_move_tail(&folio->lru, list);
  6216. unlock:
  6217. spin_unlock_irq(&hugetlb_lock);
  6218. return ret;
  6219. }
  6220. int get_hwpoison_hugetlb_folio(struct folio *folio, bool *hugetlb, bool unpoison)
  6221. {
  6222. int ret = 0;
  6223. *hugetlb = false;
  6224. spin_lock_irq(&hugetlb_lock);
  6225. if (folio_test_hugetlb(folio)) {
  6226. *hugetlb = true;
  6227. if (folio_test_hugetlb_freed(folio))
  6228. ret = 0;
  6229. else if (folio_test_hugetlb_migratable(folio) || unpoison)
  6230. ret = folio_try_get(folio);
  6231. else
  6232. ret = -EBUSY;
  6233. }
  6234. spin_unlock_irq(&hugetlb_lock);
  6235. return ret;
  6236. }
  6237. int get_huge_page_for_hwpoison(unsigned long pfn, int flags,
  6238. bool *migratable_cleared)
  6239. {
  6240. int ret;
  6241. spin_lock_irq(&hugetlb_lock);
  6242. ret = __get_huge_page_for_hwpoison(pfn, flags, migratable_cleared);
  6243. spin_unlock_irq(&hugetlb_lock);
  6244. return ret;
  6245. }
  6246. /**
  6247. * folio_putback_hugetlb - unisolate a hugetlb folio
  6248. * @folio: the isolated hugetlb folio
  6249. *
  6250. * Putback/un-isolate the hugetlb folio that was previous isolated using
  6251. * folio_isolate_hugetlb(): marking it non-isolated/migratable and putting it
  6252. * back onto the active list.
  6253. *
  6254. * Will drop the additional folio reference obtained through
  6255. * folio_isolate_hugetlb().
  6256. */
  6257. void folio_putback_hugetlb(struct folio *folio)
  6258. {
  6259. spin_lock_irq(&hugetlb_lock);
  6260. folio_set_hugetlb_migratable(folio);
  6261. list_move_tail(&folio->lru, &(folio_hstate(folio))->hugepage_activelist);
  6262. spin_unlock_irq(&hugetlb_lock);
  6263. folio_put(folio);
  6264. }
  6265. void move_hugetlb_state(struct folio *old_folio, struct folio *new_folio, int reason)
  6266. {
  6267. struct hstate *h = folio_hstate(old_folio);
  6268. hugetlb_cgroup_migrate(old_folio, new_folio);
  6269. folio_set_owner_migrate_reason(new_folio, reason);
  6270. /*
  6271. * transfer temporary state of the new hugetlb folio. This is
  6272. * reverse to other transitions because the newpage is going to
  6273. * be final while the old one will be freed so it takes over
  6274. * the temporary status.
  6275. *
  6276. * Also note that we have to transfer the per-node surplus state
  6277. * here as well otherwise the global surplus count will not match
  6278. * the per-node's.
  6279. */
  6280. if (folio_test_hugetlb_temporary(new_folio)) {
  6281. int old_nid = folio_nid(old_folio);
  6282. int new_nid = folio_nid(new_folio);
  6283. folio_set_hugetlb_temporary(old_folio);
  6284. folio_clear_hugetlb_temporary(new_folio);
  6285. /*
  6286. * There is no need to transfer the per-node surplus state
  6287. * when we do not cross the node.
  6288. */
  6289. if (new_nid == old_nid)
  6290. return;
  6291. spin_lock_irq(&hugetlb_lock);
  6292. if (h->surplus_huge_pages_node[old_nid]) {
  6293. h->surplus_huge_pages_node[old_nid]--;
  6294. h->surplus_huge_pages_node[new_nid]++;
  6295. }
  6296. spin_unlock_irq(&hugetlb_lock);
  6297. }
  6298. /*
  6299. * Our old folio is isolated and has "migratable" cleared until it
  6300. * is putback. As migration succeeded, set the new folio "migratable"
  6301. * and add it to the active list.
  6302. */
  6303. spin_lock_irq(&hugetlb_lock);
  6304. folio_set_hugetlb_migratable(new_folio);
  6305. list_move_tail(&new_folio->lru, &(folio_hstate(new_folio))->hugepage_activelist);
  6306. spin_unlock_irq(&hugetlb_lock);
  6307. }
  6308. /*
  6309. * If @take_locks is false, the caller must ensure that no concurrent page table
  6310. * access can happen (except for gup_fast() and hardware page walks).
  6311. * If @take_locks is true, we take the hugetlb VMA lock (to lock out things like
  6312. * concurrent page fault handling) and the file rmap lock.
  6313. */
  6314. static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
  6315. unsigned long start,
  6316. unsigned long end,
  6317. bool take_locks)
  6318. {
  6319. struct hstate *h = hstate_vma(vma);
  6320. unsigned long sz = huge_page_size(h);
  6321. struct mm_struct *mm = vma->vm_mm;
  6322. struct mmu_notifier_range range;
  6323. struct mmu_gather tlb;
  6324. unsigned long address;
  6325. spinlock_t *ptl;
  6326. pte_t *ptep;
  6327. if (!(vma->vm_flags & VM_MAYSHARE))
  6328. return;
  6329. if (start >= end)
  6330. return;
  6331. flush_cache_range(vma, start, end);
  6332. tlb_gather_mmu_vma(&tlb, vma);
  6333. /*
  6334. * No need to call adjust_range_if_pmd_sharing_possible(), because
  6335. * we have already done the PUD_SIZE alignment.
  6336. */
  6337. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
  6338. start, end);
  6339. mmu_notifier_invalidate_range_start(&range);
  6340. if (take_locks) {
  6341. hugetlb_vma_lock_write(vma);
  6342. i_mmap_lock_write(vma->vm_file->f_mapping);
  6343. } else {
  6344. i_mmap_assert_write_locked(vma->vm_file->f_mapping);
  6345. }
  6346. for (address = start; address < end; address += PUD_SIZE) {
  6347. ptep = hugetlb_walk(vma, address, sz);
  6348. if (!ptep)
  6349. continue;
  6350. ptl = huge_pte_lock(h, mm, ptep);
  6351. huge_pmd_unshare(&tlb, vma, address, ptep);
  6352. spin_unlock(ptl);
  6353. }
  6354. huge_pmd_unshare_flush(&tlb, vma);
  6355. if (take_locks) {
  6356. i_mmap_unlock_write(vma->vm_file->f_mapping);
  6357. hugetlb_vma_unlock_write(vma);
  6358. }
  6359. /*
  6360. * No need to call mmu_notifier_arch_invalidate_secondary_tlbs(), see
  6361. * Documentation/mm/mmu_notifier.rst.
  6362. */
  6363. mmu_notifier_invalidate_range_end(&range);
  6364. tlb_finish_mmu(&tlb);
  6365. }
  6366. /*
  6367. * This function will unconditionally remove all the shared pmd pgtable entries
  6368. * within the specific vma for a hugetlbfs memory range.
  6369. */
  6370. void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
  6371. {
  6372. hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
  6373. ALIGN_DOWN(vma->vm_end, PUD_SIZE),
  6374. /* take_locks = */ true);
  6375. }
  6376. /*
  6377. * For hugetlb, mremap() is an odd edge case - while the VMA copying is
  6378. * performed, we permit both the old and new VMAs to reference the same
  6379. * reservation.
  6380. *
  6381. * We fix this up after the operation succeeds, or if a newly allocated VMA
  6382. * is closed as a result of a failure to allocate memory.
  6383. */
  6384. void fixup_hugetlb_reservations(struct vm_area_struct *vma)
  6385. {
  6386. if (is_vm_hugetlb_page(vma))
  6387. clear_vma_resv_huge_pages(vma);
  6388. }