hugetlb.c 210 KB

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