hugetlb.c 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877
  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 <asm/page.h>
  34. #include <asm/pgalloc.h>
  35. #include <asm/tlb.h>
  36. #include <linux/io.h>
  37. #include <linux/hugetlb.h>
  38. #include <linux/hugetlb_cgroup.h>
  39. #include <linux/node.h>
  40. #include <linux/page_owner.h>
  41. #include "internal.h"
  42. int hugetlb_max_hstate __read_mostly;
  43. unsigned int default_hstate_idx;
  44. struct hstate hstates[HUGE_MAX_HSTATE];
  45. #ifdef CONFIG_CMA
  46. static struct cma *hugetlb_cma[MAX_NUMNODES];
  47. #endif
  48. static unsigned long hugetlb_cma_size __initdata;
  49. /*
  50. * Minimum page order among possible hugepage sizes, set to a proper value
  51. * at boot time.
  52. */
  53. static unsigned int minimum_order __read_mostly = UINT_MAX;
  54. __initdata LIST_HEAD(huge_boot_pages);
  55. /* for command line parsing */
  56. static struct hstate * __initdata parsed_hstate;
  57. static unsigned long __initdata default_hstate_max_huge_pages;
  58. static bool __initdata parsed_valid_hugepagesz = true;
  59. static bool __initdata parsed_default_hugepagesz;
  60. /*
  61. * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
  62. * free_huge_pages, and surplus_huge_pages.
  63. */
  64. DEFINE_SPINLOCK(hugetlb_lock);
  65. /*
  66. * Serializes faults on the same logical page. This is used to
  67. * prevent spurious OOMs when the hugepage pool is fully utilized.
  68. */
  69. static int num_fault_mutexes;
  70. struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
  71. static inline bool PageHugeFreed(struct page *head)
  72. {
  73. return page_private(head + 4) == -1UL;
  74. }
  75. static inline void SetPageHugeFreed(struct page *head)
  76. {
  77. set_page_private(head + 4, -1UL);
  78. }
  79. static inline void ClearPageHugeFreed(struct page *head)
  80. {
  81. set_page_private(head + 4, 0);
  82. }
  83. /* Forward declaration */
  84. static int hugetlb_acct_memory(struct hstate *h, long delta);
  85. static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
  86. {
  87. bool free = (spool->count == 0) && (spool->used_hpages == 0);
  88. spin_unlock(&spool->lock);
  89. /* If no pages are used, and no other handles to the subpool
  90. * remain, give up any reservations based on minimum size and
  91. * free the subpool */
  92. if (free) {
  93. if (spool->min_hpages != -1)
  94. hugetlb_acct_memory(spool->hstate,
  95. -spool->min_hpages);
  96. kfree(spool);
  97. }
  98. }
  99. struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
  100. long min_hpages)
  101. {
  102. struct hugepage_subpool *spool;
  103. spool = kzalloc(sizeof(*spool), GFP_KERNEL);
  104. if (!spool)
  105. return NULL;
  106. spin_lock_init(&spool->lock);
  107. spool->count = 1;
  108. spool->max_hpages = max_hpages;
  109. spool->hstate = h;
  110. spool->min_hpages = min_hpages;
  111. if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
  112. kfree(spool);
  113. return NULL;
  114. }
  115. spool->rsv_hpages = min_hpages;
  116. return spool;
  117. }
  118. void hugepage_put_subpool(struct hugepage_subpool *spool)
  119. {
  120. spin_lock(&spool->lock);
  121. BUG_ON(!spool->count);
  122. spool->count--;
  123. unlock_or_release_subpool(spool);
  124. }
  125. /*
  126. * Subpool accounting for allocating and reserving pages.
  127. * Return -ENOMEM if there are not enough resources to satisfy the
  128. * request. Otherwise, return the number of pages by which the
  129. * global pools must be adjusted (upward). The returned value may
  130. * only be different than the passed value (delta) in the case where
  131. * a subpool minimum size must be maintained.
  132. */
  133. static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
  134. long delta)
  135. {
  136. long ret = delta;
  137. if (!spool)
  138. return ret;
  139. spin_lock(&spool->lock);
  140. if (spool->max_hpages != -1) { /* maximum size accounting */
  141. if ((spool->used_hpages + delta) <= spool->max_hpages)
  142. spool->used_hpages += delta;
  143. else {
  144. ret = -ENOMEM;
  145. goto unlock_ret;
  146. }
  147. }
  148. /* minimum size accounting */
  149. if (spool->min_hpages != -1 && spool->rsv_hpages) {
  150. if (delta > spool->rsv_hpages) {
  151. /*
  152. * Asking for more reserves than those already taken on
  153. * behalf of subpool. Return difference.
  154. */
  155. ret = delta - spool->rsv_hpages;
  156. spool->rsv_hpages = 0;
  157. } else {
  158. ret = 0; /* reserves already accounted for */
  159. spool->rsv_hpages -= delta;
  160. }
  161. }
  162. unlock_ret:
  163. spin_unlock(&spool->lock);
  164. return ret;
  165. }
  166. /*
  167. * Subpool accounting for freeing and unreserving pages.
  168. * Return the number of global page reservations that must be dropped.
  169. * The return value may only be different than the passed value (delta)
  170. * in the case where a subpool minimum size must be maintained.
  171. */
  172. static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
  173. long delta)
  174. {
  175. long ret = delta;
  176. if (!spool)
  177. return delta;
  178. spin_lock(&spool->lock);
  179. if (spool->max_hpages != -1) /* maximum size accounting */
  180. spool->used_hpages -= delta;
  181. /* minimum size accounting */
  182. if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
  183. if (spool->rsv_hpages + delta <= spool->min_hpages)
  184. ret = 0;
  185. else
  186. ret = spool->rsv_hpages + delta - spool->min_hpages;
  187. spool->rsv_hpages += delta;
  188. if (spool->rsv_hpages > spool->min_hpages)
  189. spool->rsv_hpages = spool->min_hpages;
  190. }
  191. /*
  192. * If hugetlbfs_put_super couldn't free spool due to an outstanding
  193. * quota reference, free it now.
  194. */
  195. unlock_or_release_subpool(spool);
  196. return ret;
  197. }
  198. static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
  199. {
  200. return HUGETLBFS_SB(inode->i_sb)->spool;
  201. }
  202. static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
  203. {
  204. return subpool_inode(file_inode(vma->vm_file));
  205. }
  206. /* Helper that removes a struct file_region from the resv_map cache and returns
  207. * it for use.
  208. */
  209. static struct file_region *
  210. get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
  211. {
  212. struct file_region *nrg = NULL;
  213. VM_BUG_ON(resv->region_cache_count <= 0);
  214. resv->region_cache_count--;
  215. nrg = list_first_entry(&resv->region_cache, struct file_region, link);
  216. list_del(&nrg->link);
  217. nrg->from = from;
  218. nrg->to = to;
  219. return nrg;
  220. }
  221. static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
  222. struct file_region *rg)
  223. {
  224. #ifdef CONFIG_CGROUP_HUGETLB
  225. nrg->reservation_counter = rg->reservation_counter;
  226. nrg->css = rg->css;
  227. if (rg->css)
  228. css_get(rg->css);
  229. #endif
  230. }
  231. /* Helper that records hugetlb_cgroup uncharge info. */
  232. static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
  233. struct hstate *h,
  234. struct resv_map *resv,
  235. struct file_region *nrg)
  236. {
  237. #ifdef CONFIG_CGROUP_HUGETLB
  238. if (h_cg) {
  239. nrg->reservation_counter =
  240. &h_cg->rsvd_hugepage[hstate_index(h)];
  241. nrg->css = &h_cg->css;
  242. /*
  243. * The caller will hold exactly one h_cg->css reference for the
  244. * whole contiguous reservation region. But this area might be
  245. * scattered when there are already some file_regions reside in
  246. * it. As a result, many file_regions may share only one css
  247. * reference. In order to ensure that one file_region must hold
  248. * exactly one h_cg->css reference, we should do css_get for
  249. * each file_region and leave the reference held by caller
  250. * untouched.
  251. */
  252. css_get(&h_cg->css);
  253. if (!resv->pages_per_hpage)
  254. resv->pages_per_hpage = pages_per_huge_page(h);
  255. /* pages_per_hpage should be the same for all entries in
  256. * a resv_map.
  257. */
  258. VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
  259. } else {
  260. nrg->reservation_counter = NULL;
  261. nrg->css = NULL;
  262. }
  263. #endif
  264. }
  265. static void put_uncharge_info(struct file_region *rg)
  266. {
  267. #ifdef CONFIG_CGROUP_HUGETLB
  268. if (rg->css)
  269. css_put(rg->css);
  270. #endif
  271. }
  272. static bool has_same_uncharge_info(struct file_region *rg,
  273. struct file_region *org)
  274. {
  275. #ifdef CONFIG_CGROUP_HUGETLB
  276. return rg && org &&
  277. rg->reservation_counter == org->reservation_counter &&
  278. rg->css == org->css;
  279. #else
  280. return true;
  281. #endif
  282. }
  283. static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
  284. {
  285. struct file_region *nrg = NULL, *prg = NULL;
  286. prg = list_prev_entry(rg, link);
  287. if (&prg->link != &resv->regions && prg->to == rg->from &&
  288. has_same_uncharge_info(prg, rg)) {
  289. prg->to = rg->to;
  290. list_del(&rg->link);
  291. put_uncharge_info(rg);
  292. kfree(rg);
  293. rg = prg;
  294. }
  295. nrg = list_next_entry(rg, link);
  296. if (&nrg->link != &resv->regions && nrg->from == rg->to &&
  297. has_same_uncharge_info(nrg, rg)) {
  298. nrg->from = rg->from;
  299. list_del(&rg->link);
  300. put_uncharge_info(rg);
  301. kfree(rg);
  302. }
  303. }
  304. /*
  305. * Must be called with resv->lock held.
  306. *
  307. * Calling this with regions_needed != NULL will count the number of pages
  308. * to be added but will not modify the linked list. And regions_needed will
  309. * indicate the number of file_regions needed in the cache to carry out to add
  310. * the regions for this range.
  311. */
  312. static long add_reservation_in_range(struct resv_map *resv, long f, long t,
  313. struct hugetlb_cgroup *h_cg,
  314. struct hstate *h, long *regions_needed)
  315. {
  316. long add = 0;
  317. struct list_head *head = &resv->regions;
  318. long last_accounted_offset = f;
  319. struct file_region *rg = NULL, *trg = NULL, *nrg = NULL;
  320. if (regions_needed)
  321. *regions_needed = 0;
  322. /* In this loop, we essentially handle an entry for the range
  323. * [last_accounted_offset, rg->from), at every iteration, with some
  324. * bounds checking.
  325. */
  326. list_for_each_entry_safe(rg, trg, head, link) {
  327. /* Skip irrelevant regions that start before our range. */
  328. if (rg->from < f) {
  329. /* If this region ends after the last accounted offset,
  330. * then we need to update last_accounted_offset.
  331. */
  332. if (rg->to > last_accounted_offset)
  333. last_accounted_offset = rg->to;
  334. continue;
  335. }
  336. /* When we find a region that starts beyond our range, we've
  337. * finished.
  338. */
  339. if (rg->from > t)
  340. break;
  341. /* Add an entry for last_accounted_offset -> rg->from, and
  342. * update last_accounted_offset.
  343. */
  344. if (rg->from > last_accounted_offset) {
  345. add += rg->from - last_accounted_offset;
  346. if (!regions_needed) {
  347. nrg = get_file_region_entry_from_cache(
  348. resv, last_accounted_offset, rg->from);
  349. record_hugetlb_cgroup_uncharge_info(h_cg, h,
  350. resv, nrg);
  351. list_add(&nrg->link, rg->link.prev);
  352. coalesce_file_region(resv, nrg);
  353. } else
  354. *regions_needed += 1;
  355. }
  356. last_accounted_offset = rg->to;
  357. }
  358. /* Handle the case where our range extends beyond
  359. * last_accounted_offset.
  360. */
  361. if (last_accounted_offset < t) {
  362. add += t - last_accounted_offset;
  363. if (!regions_needed) {
  364. nrg = get_file_region_entry_from_cache(
  365. resv, last_accounted_offset, t);
  366. record_hugetlb_cgroup_uncharge_info(h_cg, h, resv, nrg);
  367. list_add(&nrg->link, rg->link.prev);
  368. coalesce_file_region(resv, nrg);
  369. } else
  370. *regions_needed += 1;
  371. }
  372. VM_BUG_ON(add < 0);
  373. return add;
  374. }
  375. /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
  376. */
  377. static int allocate_file_region_entries(struct resv_map *resv,
  378. int regions_needed)
  379. __must_hold(&resv->lock)
  380. {
  381. struct list_head allocated_regions;
  382. int to_allocate = 0, i = 0;
  383. struct file_region *trg = NULL, *rg = NULL;
  384. VM_BUG_ON(regions_needed < 0);
  385. INIT_LIST_HEAD(&allocated_regions);
  386. /*
  387. * Check for sufficient descriptors in the cache to accommodate
  388. * the number of in progress add operations plus regions_needed.
  389. *
  390. * This is a while loop because when we drop the lock, some other call
  391. * to region_add or region_del may have consumed some region_entries,
  392. * so we keep looping here until we finally have enough entries for
  393. * (adds_in_progress + regions_needed).
  394. */
  395. while (resv->region_cache_count <
  396. (resv->adds_in_progress + regions_needed)) {
  397. to_allocate = resv->adds_in_progress + regions_needed -
  398. resv->region_cache_count;
  399. /* At this point, we should have enough entries in the cache
  400. * for all the existings adds_in_progress. We should only be
  401. * needing to allocate for regions_needed.
  402. */
  403. VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
  404. spin_unlock(&resv->lock);
  405. for (i = 0; i < to_allocate; i++) {
  406. trg = kmalloc(sizeof(*trg), GFP_KERNEL);
  407. if (!trg)
  408. goto out_of_memory;
  409. list_add(&trg->link, &allocated_regions);
  410. }
  411. spin_lock(&resv->lock);
  412. list_splice(&allocated_regions, &resv->region_cache);
  413. resv->region_cache_count += to_allocate;
  414. }
  415. return 0;
  416. out_of_memory:
  417. list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
  418. list_del(&rg->link);
  419. kfree(rg);
  420. }
  421. return -ENOMEM;
  422. }
  423. /*
  424. * Add the huge page range represented by [f, t) to the reserve
  425. * map. Regions will be taken from the cache to fill in this range.
  426. * Sufficient regions should exist in the cache due to the previous
  427. * call to region_chg with the same range, but in some cases the cache will not
  428. * have sufficient entries due to races with other code doing region_add or
  429. * region_del. The extra needed entries will be allocated.
  430. *
  431. * regions_needed is the out value provided by a previous call to region_chg.
  432. *
  433. * Return the number of new huge pages added to the map. This number is greater
  434. * than or equal to zero. If file_region entries needed to be allocated for
  435. * this operation and we were not able to allocate, it returns -ENOMEM.
  436. * region_add of regions of length 1 never allocate file_regions and cannot
  437. * fail; region_chg will always allocate at least 1 entry and a region_add for
  438. * 1 page will only require at most 1 entry.
  439. */
  440. static long region_add(struct resv_map *resv, long f, long t,
  441. long in_regions_needed, struct hstate *h,
  442. struct hugetlb_cgroup *h_cg)
  443. {
  444. long add = 0, actual_regions_needed = 0;
  445. spin_lock(&resv->lock);
  446. retry:
  447. /* Count how many regions are actually needed to execute this add. */
  448. add_reservation_in_range(resv, f, t, NULL, NULL,
  449. &actual_regions_needed);
  450. /*
  451. * Check for sufficient descriptors in the cache to accommodate
  452. * this add operation. Note that actual_regions_needed may be greater
  453. * than in_regions_needed, as the resv_map may have been modified since
  454. * the region_chg call. In this case, we need to make sure that we
  455. * allocate extra entries, such that we have enough for all the
  456. * existing adds_in_progress, plus the excess needed for this
  457. * operation.
  458. */
  459. if (actual_regions_needed > in_regions_needed &&
  460. resv->region_cache_count <
  461. resv->adds_in_progress +
  462. (actual_regions_needed - in_regions_needed)) {
  463. /* region_add operation of range 1 should never need to
  464. * allocate file_region entries.
  465. */
  466. VM_BUG_ON(t - f <= 1);
  467. if (allocate_file_region_entries(
  468. resv, actual_regions_needed - in_regions_needed)) {
  469. return -ENOMEM;
  470. }
  471. goto retry;
  472. }
  473. add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
  474. resv->adds_in_progress -= in_regions_needed;
  475. spin_unlock(&resv->lock);
  476. VM_BUG_ON(add < 0);
  477. return add;
  478. }
  479. /*
  480. * Examine the existing reserve map and determine how many
  481. * huge pages in the specified range [f, t) are NOT currently
  482. * represented. This routine is called before a subsequent
  483. * call to region_add that will actually modify the reserve
  484. * map to add the specified range [f, t). region_chg does
  485. * not change the number of huge pages represented by the
  486. * map. A number of new file_region structures is added to the cache as a
  487. * placeholder, for the subsequent region_add call to use. At least 1
  488. * file_region structure is added.
  489. *
  490. * out_regions_needed is the number of regions added to the
  491. * resv->adds_in_progress. This value needs to be provided to a follow up call
  492. * to region_add or region_abort for proper accounting.
  493. *
  494. * Returns the number of huge pages that need to be added to the existing
  495. * reservation map for the range [f, t). This number is greater or equal to
  496. * zero. -ENOMEM is returned if a new file_region structure or cache entry
  497. * is needed and can not be allocated.
  498. */
  499. static long region_chg(struct resv_map *resv, long f, long t,
  500. long *out_regions_needed)
  501. {
  502. long chg = 0;
  503. spin_lock(&resv->lock);
  504. /* Count how many hugepages in this range are NOT represented. */
  505. chg = add_reservation_in_range(resv, f, t, NULL, NULL,
  506. out_regions_needed);
  507. if (*out_regions_needed == 0)
  508. *out_regions_needed = 1;
  509. if (allocate_file_region_entries(resv, *out_regions_needed))
  510. return -ENOMEM;
  511. resv->adds_in_progress += *out_regions_needed;
  512. spin_unlock(&resv->lock);
  513. return chg;
  514. }
  515. /*
  516. * Abort the in progress add operation. The adds_in_progress field
  517. * of the resv_map keeps track of the operations in progress between
  518. * calls to region_chg and region_add. Operations are sometimes
  519. * aborted after the call to region_chg. In such cases, region_abort
  520. * is called to decrement the adds_in_progress counter. regions_needed
  521. * is the value returned by the region_chg call, it is used to decrement
  522. * the adds_in_progress counter.
  523. *
  524. * NOTE: The range arguments [f, t) are not needed or used in this
  525. * routine. They are kept to make reading the calling code easier as
  526. * arguments will match the associated region_chg call.
  527. */
  528. static void region_abort(struct resv_map *resv, long f, long t,
  529. long regions_needed)
  530. {
  531. spin_lock(&resv->lock);
  532. VM_BUG_ON(!resv->region_cache_count);
  533. resv->adds_in_progress -= regions_needed;
  534. spin_unlock(&resv->lock);
  535. }
  536. /*
  537. * Delete the specified range [f, t) from the reserve map. If the
  538. * t parameter is LONG_MAX, this indicates that ALL regions after f
  539. * should be deleted. Locate the regions which intersect [f, t)
  540. * and either trim, delete or split the existing regions.
  541. *
  542. * Returns the number of huge pages deleted from the reserve map.
  543. * In the normal case, the return value is zero or more. In the
  544. * case where a region must be split, a new region descriptor must
  545. * be allocated. If the allocation fails, -ENOMEM will be returned.
  546. * NOTE: If the parameter t == LONG_MAX, then we will never split
  547. * a region and possibly return -ENOMEM. Callers specifying
  548. * t == LONG_MAX do not need to check for -ENOMEM error.
  549. */
  550. static long region_del(struct resv_map *resv, long f, long t)
  551. {
  552. struct list_head *head = &resv->regions;
  553. struct file_region *rg, *trg;
  554. struct file_region *nrg = NULL;
  555. long del = 0;
  556. retry:
  557. spin_lock(&resv->lock);
  558. list_for_each_entry_safe(rg, trg, head, link) {
  559. /*
  560. * Skip regions before the range to be deleted. file_region
  561. * ranges are normally of the form [from, to). However, there
  562. * may be a "placeholder" entry in the map which is of the form
  563. * (from, to) with from == to. Check for placeholder entries
  564. * at the beginning of the range to be deleted.
  565. */
  566. if (rg->to <= f && (rg->to != rg->from || rg->to != f))
  567. continue;
  568. if (rg->from >= t)
  569. break;
  570. if (f > rg->from && t < rg->to) { /* Must split region */
  571. /*
  572. * Check for an entry in the cache before dropping
  573. * lock and attempting allocation.
  574. */
  575. if (!nrg &&
  576. resv->region_cache_count > resv->adds_in_progress) {
  577. nrg = list_first_entry(&resv->region_cache,
  578. struct file_region,
  579. link);
  580. list_del(&nrg->link);
  581. resv->region_cache_count--;
  582. }
  583. if (!nrg) {
  584. spin_unlock(&resv->lock);
  585. nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
  586. if (!nrg)
  587. return -ENOMEM;
  588. goto retry;
  589. }
  590. del += t - f;
  591. hugetlb_cgroup_uncharge_file_region(
  592. resv, rg, t - f, false);
  593. /* New entry for end of split region */
  594. nrg->from = t;
  595. nrg->to = rg->to;
  596. copy_hugetlb_cgroup_uncharge_info(nrg, rg);
  597. INIT_LIST_HEAD(&nrg->link);
  598. /* Original entry is trimmed */
  599. rg->to = f;
  600. list_add(&nrg->link, &rg->link);
  601. nrg = NULL;
  602. break;
  603. }
  604. if (f <= rg->from && t >= rg->to) { /* Remove entire region */
  605. del += rg->to - rg->from;
  606. hugetlb_cgroup_uncharge_file_region(resv, rg,
  607. rg->to - rg->from, true);
  608. list_del(&rg->link);
  609. kfree(rg);
  610. continue;
  611. }
  612. if (f <= rg->from) { /* Trim beginning of region */
  613. hugetlb_cgroup_uncharge_file_region(resv, rg,
  614. t - rg->from, false);
  615. del += t - rg->from;
  616. rg->from = t;
  617. } else { /* Trim end of region */
  618. hugetlb_cgroup_uncharge_file_region(resv, rg,
  619. rg->to - f, false);
  620. del += rg->to - f;
  621. rg->to = f;
  622. }
  623. }
  624. spin_unlock(&resv->lock);
  625. kfree(nrg);
  626. return del;
  627. }
  628. /*
  629. * A rare out of memory error was encountered which prevented removal of
  630. * the reserve map region for a page. The huge page itself was free'ed
  631. * and removed from the page cache. This routine will adjust the subpool
  632. * usage count, and the global reserve count if needed. By incrementing
  633. * these counts, the reserve map entry which could not be deleted will
  634. * appear as a "reserved" entry instead of simply dangling with incorrect
  635. * counts.
  636. */
  637. void hugetlb_fix_reserve_counts(struct inode *inode)
  638. {
  639. struct hugepage_subpool *spool = subpool_inode(inode);
  640. long rsv_adjust;
  641. bool reserved = false;
  642. rsv_adjust = hugepage_subpool_get_pages(spool, 1);
  643. if (rsv_adjust > 0) {
  644. struct hstate *h = hstate_inode(inode);
  645. if (!hugetlb_acct_memory(h, 1))
  646. reserved = true;
  647. } else if (!rsv_adjust) {
  648. reserved = true;
  649. }
  650. if (!reserved)
  651. pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
  652. }
  653. /*
  654. * Count and return the number of huge pages in the reserve map
  655. * that intersect with the range [f, t).
  656. */
  657. static long region_count(struct resv_map *resv, long f, long t)
  658. {
  659. struct list_head *head = &resv->regions;
  660. struct file_region *rg;
  661. long chg = 0;
  662. spin_lock(&resv->lock);
  663. /* Locate each segment we overlap with, and count that overlap. */
  664. list_for_each_entry(rg, head, link) {
  665. long seg_from;
  666. long seg_to;
  667. if (rg->to <= f)
  668. continue;
  669. if (rg->from >= t)
  670. break;
  671. seg_from = max(rg->from, f);
  672. seg_to = min(rg->to, t);
  673. chg += seg_to - seg_from;
  674. }
  675. spin_unlock(&resv->lock);
  676. return chg;
  677. }
  678. /*
  679. * Convert the address within this vma to the page offset within
  680. * the mapping, in pagecache page units; huge pages here.
  681. */
  682. static pgoff_t vma_hugecache_offset(struct hstate *h,
  683. struct vm_area_struct *vma, unsigned long address)
  684. {
  685. return ((address - vma->vm_start) >> huge_page_shift(h)) +
  686. (vma->vm_pgoff >> huge_page_order(h));
  687. }
  688. pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
  689. unsigned long address)
  690. {
  691. return vma_hugecache_offset(hstate_vma(vma), vma, address);
  692. }
  693. EXPORT_SYMBOL_GPL(linear_hugepage_index);
  694. /*
  695. * Return the size of the pages allocated when backing a VMA. In the majority
  696. * cases this will be same size as used by the page table entries.
  697. */
  698. unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
  699. {
  700. if (vma->vm_ops && vma->vm_ops->pagesize)
  701. return vma->vm_ops->pagesize(vma);
  702. return PAGE_SIZE;
  703. }
  704. EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
  705. /*
  706. * Return the page size being used by the MMU to back a VMA. In the majority
  707. * of cases, the page size used by the kernel matches the MMU size. On
  708. * architectures where it differs, an architecture-specific 'strong'
  709. * version of this symbol is required.
  710. */
  711. __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
  712. {
  713. return vma_kernel_pagesize(vma);
  714. }
  715. /*
  716. * Flags for MAP_PRIVATE reservations. These are stored in the bottom
  717. * bits of the reservation map pointer, which are always clear due to
  718. * alignment.
  719. */
  720. #define HPAGE_RESV_OWNER (1UL << 0)
  721. #define HPAGE_RESV_UNMAPPED (1UL << 1)
  722. #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
  723. /*
  724. * These helpers are used to track how many pages are reserved for
  725. * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
  726. * is guaranteed to have their future faults succeed.
  727. *
  728. * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
  729. * the reserve counters are updated with the hugetlb_lock held. It is safe
  730. * to reset the VMA at fork() time as it is not in use yet and there is no
  731. * chance of the global counters getting corrupted as a result of the values.
  732. *
  733. * The private mapping reservation is represented in a subtly different
  734. * manner to a shared mapping. A shared mapping has a region map associated
  735. * with the underlying file, this region map represents the backing file
  736. * pages which have ever had a reservation assigned which this persists even
  737. * after the page is instantiated. A private mapping has a region map
  738. * associated with the original mmap which is attached to all VMAs which
  739. * reference it, this region map represents those offsets which have consumed
  740. * reservation ie. where pages have been instantiated.
  741. */
  742. static unsigned long get_vma_private_data(struct vm_area_struct *vma)
  743. {
  744. return (unsigned long)vma->vm_private_data;
  745. }
  746. static void set_vma_private_data(struct vm_area_struct *vma,
  747. unsigned long value)
  748. {
  749. vma->vm_private_data = (void *)value;
  750. }
  751. static void
  752. resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
  753. struct hugetlb_cgroup *h_cg,
  754. struct hstate *h)
  755. {
  756. #ifdef CONFIG_CGROUP_HUGETLB
  757. if (!h_cg || !h) {
  758. resv_map->reservation_counter = NULL;
  759. resv_map->pages_per_hpage = 0;
  760. resv_map->css = NULL;
  761. } else {
  762. resv_map->reservation_counter =
  763. &h_cg->rsvd_hugepage[hstate_index(h)];
  764. resv_map->pages_per_hpage = pages_per_huge_page(h);
  765. resv_map->css = &h_cg->css;
  766. }
  767. #endif
  768. }
  769. struct resv_map *resv_map_alloc(void)
  770. {
  771. struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
  772. struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
  773. if (!resv_map || !rg) {
  774. kfree(resv_map);
  775. kfree(rg);
  776. return NULL;
  777. }
  778. kref_init(&resv_map->refs);
  779. spin_lock_init(&resv_map->lock);
  780. INIT_LIST_HEAD(&resv_map->regions);
  781. resv_map->adds_in_progress = 0;
  782. /*
  783. * Initialize these to 0. On shared mappings, 0's here indicate these
  784. * fields don't do cgroup accounting. On private mappings, these will be
  785. * re-initialized to the proper values, to indicate that hugetlb cgroup
  786. * reservations are to be un-charged from here.
  787. */
  788. resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
  789. INIT_LIST_HEAD(&resv_map->region_cache);
  790. list_add(&rg->link, &resv_map->region_cache);
  791. resv_map->region_cache_count = 1;
  792. return resv_map;
  793. }
  794. void resv_map_release(struct kref *ref)
  795. {
  796. struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
  797. struct list_head *head = &resv_map->region_cache;
  798. struct file_region *rg, *trg;
  799. /* Clear out any active regions before we release the map. */
  800. region_del(resv_map, 0, LONG_MAX);
  801. /* ... and any entries left in the cache */
  802. list_for_each_entry_safe(rg, trg, head, link) {
  803. list_del(&rg->link);
  804. kfree(rg);
  805. }
  806. VM_BUG_ON(resv_map->adds_in_progress);
  807. kfree(resv_map);
  808. }
  809. static inline struct resv_map *inode_resv_map(struct inode *inode)
  810. {
  811. /*
  812. * At inode evict time, i_mapping may not point to the original
  813. * address space within the inode. This original address space
  814. * contains the pointer to the resv_map. So, always use the
  815. * address space embedded within the inode.
  816. * The VERY common case is inode->mapping == &inode->i_data but,
  817. * this may not be true for device special inodes.
  818. */
  819. return (struct resv_map *)(&inode->i_data)->private_data;
  820. }
  821. static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
  822. {
  823. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  824. if (vma->vm_flags & VM_MAYSHARE) {
  825. struct address_space *mapping = vma->vm_file->f_mapping;
  826. struct inode *inode = mapping->host;
  827. return inode_resv_map(inode);
  828. } else {
  829. return (struct resv_map *)(get_vma_private_data(vma) &
  830. ~HPAGE_RESV_MASK);
  831. }
  832. }
  833. static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
  834. {
  835. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  836. VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
  837. set_vma_private_data(vma, (get_vma_private_data(vma) &
  838. HPAGE_RESV_MASK) | (unsigned long)map);
  839. }
  840. static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
  841. {
  842. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  843. VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
  844. set_vma_private_data(vma, get_vma_private_data(vma) | flags);
  845. }
  846. static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
  847. {
  848. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  849. return (get_vma_private_data(vma) & flag) != 0;
  850. }
  851. /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
  852. void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
  853. {
  854. VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
  855. if (!(vma->vm_flags & VM_MAYSHARE))
  856. vma->vm_private_data = (void *)0;
  857. }
  858. /* Returns true if the VMA has associated reserve pages */
  859. static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
  860. {
  861. if (vma->vm_flags & VM_NORESERVE) {
  862. /*
  863. * This address is already reserved by other process(chg == 0),
  864. * so, we should decrement reserved count. Without decrementing,
  865. * reserve count remains after releasing inode, because this
  866. * allocated page will go into page cache and is regarded as
  867. * coming from reserved pool in releasing step. Currently, we
  868. * don't have any other solution to deal with this situation
  869. * properly, so add work-around here.
  870. */
  871. if (vma->vm_flags & VM_MAYSHARE && chg == 0)
  872. return true;
  873. else
  874. return false;
  875. }
  876. /* Shared mappings always use reserves */
  877. if (vma->vm_flags & VM_MAYSHARE) {
  878. /*
  879. * We know VM_NORESERVE is not set. Therefore, there SHOULD
  880. * be a region map for all pages. The only situation where
  881. * there is no region map is if a hole was punched via
  882. * fallocate. In this case, there really are no reserves to
  883. * use. This situation is indicated if chg != 0.
  884. */
  885. if (chg)
  886. return false;
  887. else
  888. return true;
  889. }
  890. /*
  891. * Only the process that called mmap() has reserves for
  892. * private mappings.
  893. */
  894. if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
  895. /*
  896. * Like the shared case above, a hole punch or truncate
  897. * could have been performed on the private mapping.
  898. * Examine the value of chg to determine if reserves
  899. * actually exist or were previously consumed.
  900. * Very Subtle - The value of chg comes from a previous
  901. * call to vma_needs_reserves(). The reserve map for
  902. * private mappings has different (opposite) semantics
  903. * than that of shared mappings. vma_needs_reserves()
  904. * has already taken this difference in semantics into
  905. * account. Therefore, the meaning of chg is the same
  906. * as in the shared case above. Code could easily be
  907. * combined, but keeping it separate draws attention to
  908. * subtle differences.
  909. */
  910. if (chg)
  911. return false;
  912. else
  913. return true;
  914. }
  915. return false;
  916. }
  917. static void enqueue_huge_page(struct hstate *h, struct page *page)
  918. {
  919. int nid = page_to_nid(page);
  920. list_move(&page->lru, &h->hugepage_freelists[nid]);
  921. h->free_huge_pages++;
  922. h->free_huge_pages_node[nid]++;
  923. SetPageHugeFreed(page);
  924. }
  925. static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
  926. {
  927. struct page *page;
  928. bool nocma = !!(current->flags & PF_MEMALLOC_NOCMA);
  929. list_for_each_entry(page, &h->hugepage_freelists[nid], lru) {
  930. if (nocma && is_migrate_cma_page(page))
  931. continue;
  932. if (PageHWPoison(page))
  933. continue;
  934. list_move(&page->lru, &h->hugepage_activelist);
  935. set_page_refcounted(page);
  936. ClearPageHugeFreed(page);
  937. h->free_huge_pages--;
  938. h->free_huge_pages_node[nid]--;
  939. return page;
  940. }
  941. return NULL;
  942. }
  943. static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
  944. nodemask_t *nmask)
  945. {
  946. unsigned int cpuset_mems_cookie;
  947. struct zonelist *zonelist;
  948. struct zone *zone;
  949. struct zoneref *z;
  950. int node = NUMA_NO_NODE;
  951. zonelist = node_zonelist(nid, gfp_mask);
  952. retry_cpuset:
  953. cpuset_mems_cookie = read_mems_allowed_begin();
  954. for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
  955. struct page *page;
  956. if (!cpuset_zone_allowed(zone, gfp_mask))
  957. continue;
  958. /*
  959. * no need to ask again on the same node. Pool is node rather than
  960. * zone aware
  961. */
  962. if (zone_to_nid(zone) == node)
  963. continue;
  964. node = zone_to_nid(zone);
  965. page = dequeue_huge_page_node_exact(h, node);
  966. if (page)
  967. return page;
  968. }
  969. if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
  970. goto retry_cpuset;
  971. return NULL;
  972. }
  973. static struct page *dequeue_huge_page_vma(struct hstate *h,
  974. struct vm_area_struct *vma,
  975. unsigned long address, int avoid_reserve,
  976. long chg)
  977. {
  978. struct page *page;
  979. struct mempolicy *mpol;
  980. gfp_t gfp_mask;
  981. nodemask_t *nodemask;
  982. int nid;
  983. /*
  984. * A child process with MAP_PRIVATE mappings created by their parent
  985. * have no page reserves. This check ensures that reservations are
  986. * not "stolen". The child may still get SIGKILLed
  987. */
  988. if (!vma_has_reserves(vma, chg) &&
  989. h->free_huge_pages - h->resv_huge_pages == 0)
  990. goto err;
  991. /* If reserves cannot be used, ensure enough pages are in the pool */
  992. if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
  993. goto err;
  994. gfp_mask = htlb_alloc_mask(h);
  995. nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
  996. page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
  997. if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
  998. SetPagePrivate(page);
  999. h->resv_huge_pages--;
  1000. }
  1001. mpol_cond_put(mpol);
  1002. return page;
  1003. err:
  1004. return NULL;
  1005. }
  1006. /*
  1007. * common helper functions for hstate_next_node_to_{alloc|free}.
  1008. * We may have allocated or freed a huge page based on a different
  1009. * nodes_allowed previously, so h->next_node_to_{alloc|free} might
  1010. * be outside of *nodes_allowed. Ensure that we use an allowed
  1011. * node for alloc or free.
  1012. */
  1013. static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
  1014. {
  1015. nid = next_node_in(nid, *nodes_allowed);
  1016. VM_BUG_ON(nid >= MAX_NUMNODES);
  1017. return nid;
  1018. }
  1019. static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
  1020. {
  1021. if (!node_isset(nid, *nodes_allowed))
  1022. nid = next_node_allowed(nid, nodes_allowed);
  1023. return nid;
  1024. }
  1025. /*
  1026. * returns the previously saved node ["this node"] from which to
  1027. * allocate a persistent huge page for the pool and advance the
  1028. * next node from which to allocate, handling wrap at end of node
  1029. * mask.
  1030. */
  1031. static int hstate_next_node_to_alloc(struct hstate *h,
  1032. nodemask_t *nodes_allowed)
  1033. {
  1034. int nid;
  1035. VM_BUG_ON(!nodes_allowed);
  1036. nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
  1037. h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
  1038. return nid;
  1039. }
  1040. /*
  1041. * helper for free_pool_huge_page() - return the previously saved
  1042. * node ["this node"] from which to free a huge page. Advance the
  1043. * next node id whether or not we find a free huge page to free so
  1044. * that the next attempt to free addresses the next node.
  1045. */
  1046. static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
  1047. {
  1048. int nid;
  1049. VM_BUG_ON(!nodes_allowed);
  1050. nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
  1051. h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
  1052. return nid;
  1053. }
  1054. #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
  1055. for (nr_nodes = nodes_weight(*mask); \
  1056. nr_nodes > 0 && \
  1057. ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
  1058. nr_nodes--)
  1059. #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
  1060. for (nr_nodes = nodes_weight(*mask); \
  1061. nr_nodes > 0 && \
  1062. ((node = hstate_next_node_to_free(hs, mask)) || 1); \
  1063. nr_nodes--)
  1064. #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
  1065. static void destroy_compound_gigantic_page(struct page *page,
  1066. unsigned int order)
  1067. {
  1068. int i;
  1069. int nr_pages = 1 << order;
  1070. struct page *p = page + 1;
  1071. atomic_set(compound_mapcount_ptr(page), 0);
  1072. atomic_set(compound_pincount_ptr(page), 0);
  1073. for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
  1074. clear_compound_head(p);
  1075. set_page_refcounted(p);
  1076. }
  1077. set_compound_order(page, 0);
  1078. page[1].compound_nr = 0;
  1079. __ClearPageHead(page);
  1080. }
  1081. static void free_gigantic_page(struct page *page, unsigned int order)
  1082. {
  1083. /*
  1084. * If the page isn't allocated using the cma allocator,
  1085. * cma_release() returns false.
  1086. */
  1087. #ifdef CONFIG_CMA
  1088. if (cma_release(hugetlb_cma[page_to_nid(page)], page, 1 << order))
  1089. return;
  1090. #endif
  1091. free_contig_range(page_to_pfn(page), 1 << order);
  1092. }
  1093. #ifdef CONFIG_CONTIG_ALLOC
  1094. static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
  1095. int nid, nodemask_t *nodemask)
  1096. {
  1097. unsigned long nr_pages = 1UL << huge_page_order(h);
  1098. if (nid == NUMA_NO_NODE)
  1099. nid = numa_mem_id();
  1100. #ifdef CONFIG_CMA
  1101. {
  1102. struct page *page;
  1103. int node;
  1104. if (hugetlb_cma[nid]) {
  1105. page = cma_alloc(hugetlb_cma[nid], nr_pages,
  1106. huge_page_order(h),
  1107. GFP_KERNEL | __GFP_NOWARN);
  1108. if (page)
  1109. return page;
  1110. }
  1111. if (!(gfp_mask & __GFP_THISNODE)) {
  1112. for_each_node_mask(node, *nodemask) {
  1113. if (node == nid || !hugetlb_cma[node])
  1114. continue;
  1115. page = cma_alloc(hugetlb_cma[node], nr_pages,
  1116. huge_page_order(h),
  1117. GFP_KERNEL | __GFP_NOWARN);
  1118. if (page)
  1119. return page;
  1120. }
  1121. }
  1122. }
  1123. #endif
  1124. return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
  1125. }
  1126. #else /* !CONFIG_CONTIG_ALLOC */
  1127. static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
  1128. int nid, nodemask_t *nodemask)
  1129. {
  1130. return NULL;
  1131. }
  1132. #endif /* CONFIG_CONTIG_ALLOC */
  1133. #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
  1134. static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
  1135. int nid, nodemask_t *nodemask)
  1136. {
  1137. return NULL;
  1138. }
  1139. static inline void free_gigantic_page(struct page *page, unsigned int order) { }
  1140. static inline void destroy_compound_gigantic_page(struct page *page,
  1141. unsigned int order) { }
  1142. #endif
  1143. static void update_and_free_page(struct hstate *h, struct page *page)
  1144. {
  1145. int i;
  1146. struct page *subpage = page;
  1147. if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
  1148. return;
  1149. h->nr_huge_pages--;
  1150. h->nr_huge_pages_node[page_to_nid(page)]--;
  1151. for (i = 0; i < pages_per_huge_page(h);
  1152. i++, subpage = mem_map_next(subpage, page, i)) {
  1153. subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
  1154. 1 << PG_referenced | 1 << PG_dirty |
  1155. 1 << PG_active | 1 << PG_private |
  1156. 1 << PG_writeback);
  1157. }
  1158. VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
  1159. VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
  1160. set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
  1161. set_page_refcounted(page);
  1162. if (hstate_is_gigantic(h)) {
  1163. /*
  1164. * Temporarily drop the hugetlb_lock, because
  1165. * we might block in free_gigantic_page().
  1166. */
  1167. spin_unlock(&hugetlb_lock);
  1168. destroy_compound_gigantic_page(page, huge_page_order(h));
  1169. free_gigantic_page(page, huge_page_order(h));
  1170. spin_lock(&hugetlb_lock);
  1171. } else {
  1172. __free_pages(page, huge_page_order(h));
  1173. }
  1174. }
  1175. struct hstate *size_to_hstate(unsigned long size)
  1176. {
  1177. struct hstate *h;
  1178. for_each_hstate(h) {
  1179. if (huge_page_size(h) == size)
  1180. return h;
  1181. }
  1182. return NULL;
  1183. }
  1184. /*
  1185. * Test to determine whether the hugepage is "active/in-use" (i.e. being linked
  1186. * to hstate->hugepage_activelist.)
  1187. *
  1188. * This function can be called for tail pages, but never returns true for them.
  1189. */
  1190. bool page_huge_active(struct page *page)
  1191. {
  1192. return PageHeadHuge(page) && PagePrivate(&page[1]);
  1193. }
  1194. /* never called for tail page */
  1195. void set_page_huge_active(struct page *page)
  1196. {
  1197. VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
  1198. SetPagePrivate(&page[1]);
  1199. }
  1200. static void clear_page_huge_active(struct page *page)
  1201. {
  1202. VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
  1203. ClearPagePrivate(&page[1]);
  1204. }
  1205. /*
  1206. * Internal hugetlb specific page flag. Do not use outside of the hugetlb
  1207. * code
  1208. */
  1209. static inline bool PageHugeTemporary(struct page *page)
  1210. {
  1211. if (!PageHuge(page))
  1212. return false;
  1213. return (unsigned long)page[2].mapping == -1U;
  1214. }
  1215. static inline void SetPageHugeTemporary(struct page *page)
  1216. {
  1217. page[2].mapping = (void *)-1U;
  1218. }
  1219. static inline void ClearPageHugeTemporary(struct page *page)
  1220. {
  1221. page[2].mapping = NULL;
  1222. }
  1223. static void __free_huge_page(struct page *page)
  1224. {
  1225. /*
  1226. * Can't pass hstate in here because it is called from the
  1227. * compound page destructor.
  1228. */
  1229. struct hstate *h = page_hstate(page);
  1230. int nid = page_to_nid(page);
  1231. struct hugepage_subpool *spool =
  1232. (struct hugepage_subpool *)page_private(page);
  1233. bool restore_reserve;
  1234. VM_BUG_ON_PAGE(page_count(page), page);
  1235. VM_BUG_ON_PAGE(page_mapcount(page), page);
  1236. set_page_private(page, 0);
  1237. page->mapping = NULL;
  1238. restore_reserve = PagePrivate(page);
  1239. ClearPagePrivate(page);
  1240. /*
  1241. * If PagePrivate() was set on page, page allocation consumed a
  1242. * reservation. If the page was associated with a subpool, there
  1243. * would have been a page reserved in the subpool before allocation
  1244. * via hugepage_subpool_get_pages(). Since we are 'restoring' the
  1245. * reservtion, do not call hugepage_subpool_put_pages() as this will
  1246. * remove the reserved page from the subpool.
  1247. */
  1248. if (!restore_reserve) {
  1249. /*
  1250. * A return code of zero implies that the subpool will be
  1251. * under its minimum size if the reservation is not restored
  1252. * after page is free. Therefore, force restore_reserve
  1253. * operation.
  1254. */
  1255. if (hugepage_subpool_put_pages(spool, 1) == 0)
  1256. restore_reserve = true;
  1257. }
  1258. spin_lock(&hugetlb_lock);
  1259. clear_page_huge_active(page);
  1260. hugetlb_cgroup_uncharge_page(hstate_index(h),
  1261. pages_per_huge_page(h), page);
  1262. hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
  1263. pages_per_huge_page(h), page);
  1264. if (restore_reserve)
  1265. h->resv_huge_pages++;
  1266. if (PageHugeTemporary(page)) {
  1267. list_del(&page->lru);
  1268. ClearPageHugeTemporary(page);
  1269. update_and_free_page(h, page);
  1270. } else if (h->surplus_huge_pages_node[nid]) {
  1271. /* remove the page from active list */
  1272. list_del(&page->lru);
  1273. update_and_free_page(h, page);
  1274. h->surplus_huge_pages--;
  1275. h->surplus_huge_pages_node[nid]--;
  1276. } else {
  1277. arch_clear_hugepage_flags(page);
  1278. enqueue_huge_page(h, page);
  1279. }
  1280. spin_unlock(&hugetlb_lock);
  1281. }
  1282. /*
  1283. * As free_huge_page() can be called from a non-task context, we have
  1284. * to defer the actual freeing in a workqueue to prevent potential
  1285. * hugetlb_lock deadlock.
  1286. *
  1287. * free_hpage_workfn() locklessly retrieves the linked list of pages to
  1288. * be freed and frees them one-by-one. As the page->mapping pointer is
  1289. * going to be cleared in __free_huge_page() anyway, it is reused as the
  1290. * llist_node structure of a lockless linked list of huge pages to be freed.
  1291. */
  1292. static LLIST_HEAD(hpage_freelist);
  1293. static void free_hpage_workfn(struct work_struct *work)
  1294. {
  1295. struct llist_node *node;
  1296. struct page *page;
  1297. node = llist_del_all(&hpage_freelist);
  1298. while (node) {
  1299. page = container_of((struct address_space **)node,
  1300. struct page, mapping);
  1301. node = node->next;
  1302. __free_huge_page(page);
  1303. }
  1304. }
  1305. static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
  1306. void free_huge_page(struct page *page)
  1307. {
  1308. /*
  1309. * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
  1310. */
  1311. if (!in_task()) {
  1312. /*
  1313. * Only call schedule_work() if hpage_freelist is previously
  1314. * empty. Otherwise, schedule_work() had been called but the
  1315. * workfn hasn't retrieved the list yet.
  1316. */
  1317. if (llist_add((struct llist_node *)&page->mapping,
  1318. &hpage_freelist))
  1319. schedule_work(&free_hpage_work);
  1320. return;
  1321. }
  1322. __free_huge_page(page);
  1323. }
  1324. static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
  1325. {
  1326. INIT_LIST_HEAD(&page->lru);
  1327. set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
  1328. set_hugetlb_cgroup(page, NULL);
  1329. set_hugetlb_cgroup_rsvd(page, NULL);
  1330. spin_lock(&hugetlb_lock);
  1331. h->nr_huge_pages++;
  1332. h->nr_huge_pages_node[nid]++;
  1333. ClearPageHugeFreed(page);
  1334. spin_unlock(&hugetlb_lock);
  1335. }
  1336. static void prep_compound_gigantic_page(struct page *page, unsigned int order)
  1337. {
  1338. int i;
  1339. int nr_pages = 1 << order;
  1340. struct page *p = page + 1;
  1341. /* we rely on prep_new_huge_page to set the destructor */
  1342. set_compound_order(page, order);
  1343. __ClearPageReserved(page);
  1344. __SetPageHead(page);
  1345. for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
  1346. /*
  1347. * For gigantic hugepages allocated through bootmem at
  1348. * boot, it's safer to be consistent with the not-gigantic
  1349. * hugepages and clear the PG_reserved bit from all tail pages
  1350. * too. Otherwise drivers using get_user_pages() to access tail
  1351. * pages may get the reference counting wrong if they see
  1352. * PG_reserved set on a tail page (despite the head page not
  1353. * having PG_reserved set). Enforcing this consistency between
  1354. * head and tail pages allows drivers to optimize away a check
  1355. * on the head page when they need know if put_page() is needed
  1356. * after get_user_pages().
  1357. */
  1358. __ClearPageReserved(p);
  1359. set_page_count(p, 0);
  1360. set_compound_head(p, page);
  1361. }
  1362. atomic_set(compound_mapcount_ptr(page), -1);
  1363. atomic_set(compound_pincount_ptr(page), 0);
  1364. }
  1365. /*
  1366. * PageHuge() only returns true for hugetlbfs pages, but not for normal or
  1367. * transparent huge pages. See the PageTransHuge() documentation for more
  1368. * details.
  1369. */
  1370. int PageHuge(struct page *page)
  1371. {
  1372. if (!PageCompound(page))
  1373. return 0;
  1374. page = compound_head(page);
  1375. return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
  1376. }
  1377. EXPORT_SYMBOL_GPL(PageHuge);
  1378. /*
  1379. * PageHeadHuge() only returns true for hugetlbfs head page, but not for
  1380. * normal or transparent huge pages.
  1381. */
  1382. int PageHeadHuge(struct page *page_head)
  1383. {
  1384. if (!PageHead(page_head))
  1385. return 0;
  1386. return page_head[1].compound_dtor == HUGETLB_PAGE_DTOR;
  1387. }
  1388. /*
  1389. * Find and lock address space (mapping) in write mode.
  1390. *
  1391. * Upon entry, the page is locked which means that page_mapping() is
  1392. * stable. Due to locking order, we can only trylock_write. If we can
  1393. * not get the lock, simply return NULL to caller.
  1394. */
  1395. struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
  1396. {
  1397. struct address_space *mapping = page_mapping(hpage);
  1398. if (!mapping)
  1399. return mapping;
  1400. if (i_mmap_trylock_write(mapping))
  1401. return mapping;
  1402. return NULL;
  1403. }
  1404. pgoff_t hugetlb_basepage_index(struct page *page)
  1405. {
  1406. struct page *page_head = compound_head(page);
  1407. pgoff_t index = page_index(page_head);
  1408. unsigned long compound_idx;
  1409. if (compound_order(page_head) >= MAX_ORDER)
  1410. compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
  1411. else
  1412. compound_idx = page - page_head;
  1413. return (index << compound_order(page_head)) + compound_idx;
  1414. }
  1415. static struct page *alloc_buddy_huge_page(struct hstate *h,
  1416. gfp_t gfp_mask, int nid, nodemask_t *nmask,
  1417. nodemask_t *node_alloc_noretry)
  1418. {
  1419. int order = huge_page_order(h);
  1420. struct page *page;
  1421. bool alloc_try_hard = true;
  1422. /*
  1423. * By default we always try hard to allocate the page with
  1424. * __GFP_RETRY_MAYFAIL flag. However, if we are allocating pages in
  1425. * a loop (to adjust global huge page counts) and previous allocation
  1426. * failed, do not continue to try hard on the same node. Use the
  1427. * node_alloc_noretry bitmap to manage this state information.
  1428. */
  1429. if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
  1430. alloc_try_hard = false;
  1431. gfp_mask |= __GFP_COMP|__GFP_NOWARN;
  1432. if (alloc_try_hard)
  1433. gfp_mask |= __GFP_RETRY_MAYFAIL;
  1434. if (nid == NUMA_NO_NODE)
  1435. nid = numa_mem_id();
  1436. page = __alloc_pages_nodemask(gfp_mask, order, nid, nmask);
  1437. if (page)
  1438. __count_vm_event(HTLB_BUDDY_PGALLOC);
  1439. else
  1440. __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
  1441. /*
  1442. * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
  1443. * indicates an overall state change. Clear bit so that we resume
  1444. * normal 'try hard' allocations.
  1445. */
  1446. if (node_alloc_noretry && page && !alloc_try_hard)
  1447. node_clear(nid, *node_alloc_noretry);
  1448. /*
  1449. * If we tried hard to get a page but failed, set bit so that
  1450. * subsequent attempts will not try as hard until there is an
  1451. * overall state change.
  1452. */
  1453. if (node_alloc_noretry && !page && alloc_try_hard)
  1454. node_set(nid, *node_alloc_noretry);
  1455. return page;
  1456. }
  1457. /*
  1458. * Common helper to allocate a fresh hugetlb page. All specific allocators
  1459. * should use this function to get new hugetlb pages
  1460. */
  1461. static struct page *alloc_fresh_huge_page(struct hstate *h,
  1462. gfp_t gfp_mask, int nid, nodemask_t *nmask,
  1463. nodemask_t *node_alloc_noretry)
  1464. {
  1465. struct page *page;
  1466. if (hstate_is_gigantic(h))
  1467. page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
  1468. else
  1469. page = alloc_buddy_huge_page(h, gfp_mask,
  1470. nid, nmask, node_alloc_noretry);
  1471. if (!page)
  1472. return NULL;
  1473. if (hstate_is_gigantic(h))
  1474. prep_compound_gigantic_page(page, huge_page_order(h));
  1475. prep_new_huge_page(h, page, page_to_nid(page));
  1476. return page;
  1477. }
  1478. /*
  1479. * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
  1480. * manner.
  1481. */
  1482. static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
  1483. nodemask_t *node_alloc_noretry)
  1484. {
  1485. struct page *page;
  1486. int nr_nodes, node;
  1487. gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
  1488. for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
  1489. page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
  1490. node_alloc_noretry);
  1491. if (page)
  1492. break;
  1493. }
  1494. if (!page)
  1495. return 0;
  1496. put_page(page); /* free it into the hugepage allocator */
  1497. return 1;
  1498. }
  1499. /*
  1500. * Free huge page from pool from next node to free.
  1501. * Attempt to keep persistent huge pages more or less
  1502. * balanced over allowed nodes.
  1503. * Called with hugetlb_lock locked.
  1504. */
  1505. static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
  1506. bool acct_surplus)
  1507. {
  1508. int nr_nodes, node;
  1509. int ret = 0;
  1510. for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
  1511. /*
  1512. * If we're returning unused surplus pages, only examine
  1513. * nodes with surplus pages.
  1514. */
  1515. if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
  1516. !list_empty(&h->hugepage_freelists[node])) {
  1517. struct page *page =
  1518. list_entry(h->hugepage_freelists[node].next,
  1519. struct page, lru);
  1520. list_del(&page->lru);
  1521. h->free_huge_pages--;
  1522. h->free_huge_pages_node[node]--;
  1523. if (acct_surplus) {
  1524. h->surplus_huge_pages--;
  1525. h->surplus_huge_pages_node[node]--;
  1526. }
  1527. update_and_free_page(h, page);
  1528. ret = 1;
  1529. break;
  1530. }
  1531. }
  1532. return ret;
  1533. }
  1534. /*
  1535. * Dissolve a given free hugepage into free buddy pages. This function does
  1536. * nothing for in-use hugepages and non-hugepages.
  1537. * This function returns values like below:
  1538. *
  1539. * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
  1540. * (allocated or reserved.)
  1541. * 0: successfully dissolved free hugepages or the page is not a
  1542. * hugepage (considered as already dissolved)
  1543. */
  1544. int dissolve_free_huge_page(struct page *page)
  1545. {
  1546. int rc = -EBUSY;
  1547. retry:
  1548. /* Not to disrupt normal path by vainly holding hugetlb_lock */
  1549. if (!PageHuge(page))
  1550. return 0;
  1551. spin_lock(&hugetlb_lock);
  1552. if (!PageHuge(page)) {
  1553. rc = 0;
  1554. goto out;
  1555. }
  1556. if (!page_count(page)) {
  1557. struct page *head = compound_head(page);
  1558. struct hstate *h = page_hstate(head);
  1559. int nid = page_to_nid(head);
  1560. if (h->free_huge_pages - h->resv_huge_pages == 0)
  1561. goto out;
  1562. /*
  1563. * We should make sure that the page is already on the free list
  1564. * when it is dissolved.
  1565. */
  1566. if (unlikely(!PageHugeFreed(head))) {
  1567. spin_unlock(&hugetlb_lock);
  1568. cond_resched();
  1569. /*
  1570. * Theoretically, we should return -EBUSY when we
  1571. * encounter this race. In fact, we have a chance
  1572. * to successfully dissolve the page if we do a
  1573. * retry. Because the race window is quite small.
  1574. * If we seize this opportunity, it is an optimization
  1575. * for increasing the success rate of dissolving page.
  1576. */
  1577. goto retry;
  1578. }
  1579. /*
  1580. * Move PageHWPoison flag from head page to the raw error page,
  1581. * which makes any subpages rather than the error page reusable.
  1582. */
  1583. if (PageHWPoison(head) && page != head) {
  1584. SetPageHWPoison(page);
  1585. ClearPageHWPoison(head);
  1586. }
  1587. list_del(&head->lru);
  1588. h->free_huge_pages--;
  1589. h->free_huge_pages_node[nid]--;
  1590. h->max_huge_pages--;
  1591. update_and_free_page(h, head);
  1592. rc = 0;
  1593. }
  1594. out:
  1595. spin_unlock(&hugetlb_lock);
  1596. return rc;
  1597. }
  1598. /*
  1599. * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
  1600. * make specified memory blocks removable from the system.
  1601. * Note that this will dissolve a free gigantic hugepage completely, if any
  1602. * part of it lies within the given range.
  1603. * Also note that if dissolve_free_huge_page() returns with an error, all
  1604. * free hugepages that were dissolved before that error are lost.
  1605. */
  1606. int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
  1607. {
  1608. unsigned long pfn;
  1609. struct page *page;
  1610. int rc = 0;
  1611. if (!hugepages_supported())
  1612. return rc;
  1613. for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) {
  1614. page = pfn_to_page(pfn);
  1615. rc = dissolve_free_huge_page(page);
  1616. if (rc)
  1617. break;
  1618. }
  1619. return rc;
  1620. }
  1621. /*
  1622. * Allocates a fresh surplus page from the page allocator.
  1623. */
  1624. static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
  1625. int nid, nodemask_t *nmask)
  1626. {
  1627. struct page *page = NULL;
  1628. if (hstate_is_gigantic(h))
  1629. return NULL;
  1630. spin_lock(&hugetlb_lock);
  1631. if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
  1632. goto out_unlock;
  1633. spin_unlock(&hugetlb_lock);
  1634. page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
  1635. if (!page)
  1636. return NULL;
  1637. spin_lock(&hugetlb_lock);
  1638. /*
  1639. * We could have raced with the pool size change.
  1640. * Double check that and simply deallocate the new page
  1641. * if we would end up overcommiting the surpluses. Abuse
  1642. * temporary page to workaround the nasty free_huge_page
  1643. * codeflow
  1644. */
  1645. if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
  1646. SetPageHugeTemporary(page);
  1647. spin_unlock(&hugetlb_lock);
  1648. put_page(page);
  1649. return NULL;
  1650. } else {
  1651. h->surplus_huge_pages++;
  1652. h->surplus_huge_pages_node[page_to_nid(page)]++;
  1653. }
  1654. out_unlock:
  1655. spin_unlock(&hugetlb_lock);
  1656. return page;
  1657. }
  1658. static struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
  1659. int nid, nodemask_t *nmask)
  1660. {
  1661. struct page *page;
  1662. if (hstate_is_gigantic(h))
  1663. return NULL;
  1664. page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
  1665. if (!page)
  1666. return NULL;
  1667. /*
  1668. * We do not account these pages as surplus because they are only
  1669. * temporary and will be released properly on the last reference
  1670. */
  1671. SetPageHugeTemporary(page);
  1672. return page;
  1673. }
  1674. /*
  1675. * Use the VMA's mpolicy to allocate a huge page from the buddy.
  1676. */
  1677. static
  1678. struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
  1679. struct vm_area_struct *vma, unsigned long addr)
  1680. {
  1681. struct page *page;
  1682. struct mempolicy *mpol;
  1683. gfp_t gfp_mask = htlb_alloc_mask(h);
  1684. int nid;
  1685. nodemask_t *nodemask;
  1686. nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
  1687. page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
  1688. mpol_cond_put(mpol);
  1689. return page;
  1690. }
  1691. /* page migration callback function */
  1692. struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
  1693. nodemask_t *nmask, gfp_t gfp_mask)
  1694. {
  1695. spin_lock(&hugetlb_lock);
  1696. if (h->free_huge_pages - h->resv_huge_pages > 0) {
  1697. struct page *page;
  1698. page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
  1699. if (page) {
  1700. spin_unlock(&hugetlb_lock);
  1701. return page;
  1702. }
  1703. }
  1704. spin_unlock(&hugetlb_lock);
  1705. return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
  1706. }
  1707. /* mempolicy aware migration callback */
  1708. struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
  1709. unsigned long address)
  1710. {
  1711. struct mempolicy *mpol;
  1712. nodemask_t *nodemask;
  1713. struct page *page;
  1714. gfp_t gfp_mask;
  1715. int node;
  1716. gfp_mask = htlb_alloc_mask(h);
  1717. node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
  1718. page = alloc_huge_page_nodemask(h, node, nodemask, gfp_mask);
  1719. mpol_cond_put(mpol);
  1720. return page;
  1721. }
  1722. /*
  1723. * Increase the hugetlb pool such that it can accommodate a reservation
  1724. * of size 'delta'.
  1725. */
  1726. static int gather_surplus_pages(struct hstate *h, int delta)
  1727. __must_hold(&hugetlb_lock)
  1728. {
  1729. struct list_head surplus_list;
  1730. struct page *page, *tmp;
  1731. int ret, i;
  1732. int needed, allocated;
  1733. bool alloc_ok = true;
  1734. needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
  1735. if (needed <= 0) {
  1736. h->resv_huge_pages += delta;
  1737. return 0;
  1738. }
  1739. allocated = 0;
  1740. INIT_LIST_HEAD(&surplus_list);
  1741. ret = -ENOMEM;
  1742. retry:
  1743. spin_unlock(&hugetlb_lock);
  1744. for (i = 0; i < needed; i++) {
  1745. page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
  1746. NUMA_NO_NODE, NULL);
  1747. if (!page) {
  1748. alloc_ok = false;
  1749. break;
  1750. }
  1751. list_add(&page->lru, &surplus_list);
  1752. cond_resched();
  1753. }
  1754. allocated += i;
  1755. /*
  1756. * After retaking hugetlb_lock, we need to recalculate 'needed'
  1757. * because either resv_huge_pages or free_huge_pages may have changed.
  1758. */
  1759. spin_lock(&hugetlb_lock);
  1760. needed = (h->resv_huge_pages + delta) -
  1761. (h->free_huge_pages + allocated);
  1762. if (needed > 0) {
  1763. if (alloc_ok)
  1764. goto retry;
  1765. /*
  1766. * We were not able to allocate enough pages to
  1767. * satisfy the entire reservation so we free what
  1768. * we've allocated so far.
  1769. */
  1770. goto free;
  1771. }
  1772. /*
  1773. * The surplus_list now contains _at_least_ the number of extra pages
  1774. * needed to accommodate the reservation. Add the appropriate number
  1775. * of pages to the hugetlb pool and free the extras back to the buddy
  1776. * allocator. Commit the entire reservation here to prevent another
  1777. * process from stealing the pages as they are added to the pool but
  1778. * before they are reserved.
  1779. */
  1780. needed += allocated;
  1781. h->resv_huge_pages += delta;
  1782. ret = 0;
  1783. /* Free the needed pages to the hugetlb pool */
  1784. list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
  1785. if ((--needed) < 0)
  1786. break;
  1787. /*
  1788. * This page is now managed by the hugetlb allocator and has
  1789. * no users -- drop the buddy allocator's reference.
  1790. */
  1791. put_page_testzero(page);
  1792. VM_BUG_ON_PAGE(page_count(page), page);
  1793. enqueue_huge_page(h, page);
  1794. }
  1795. free:
  1796. spin_unlock(&hugetlb_lock);
  1797. /* Free unnecessary surplus pages to the buddy allocator */
  1798. list_for_each_entry_safe(page, tmp, &surplus_list, lru)
  1799. put_page(page);
  1800. spin_lock(&hugetlb_lock);
  1801. return ret;
  1802. }
  1803. /*
  1804. * This routine has two main purposes:
  1805. * 1) Decrement the reservation count (resv_huge_pages) by the value passed
  1806. * in unused_resv_pages. This corresponds to the prior adjustments made
  1807. * to the associated reservation map.
  1808. * 2) Free any unused surplus pages that may have been allocated to satisfy
  1809. * the reservation. As many as unused_resv_pages may be freed.
  1810. *
  1811. * Called with hugetlb_lock held. However, the lock could be dropped (and
  1812. * reacquired) during calls to cond_resched_lock. Whenever dropping the lock,
  1813. * we must make sure nobody else can claim pages we are in the process of
  1814. * freeing. Do this by ensuring resv_huge_page always is greater than the
  1815. * number of huge pages we plan to free when dropping the lock.
  1816. */
  1817. static void return_unused_surplus_pages(struct hstate *h,
  1818. unsigned long unused_resv_pages)
  1819. {
  1820. unsigned long nr_pages;
  1821. /* Cannot return gigantic pages currently */
  1822. if (hstate_is_gigantic(h))
  1823. goto out;
  1824. /*
  1825. * Part (or even all) of the reservation could have been backed
  1826. * by pre-allocated pages. Only free surplus pages.
  1827. */
  1828. nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
  1829. /*
  1830. * We want to release as many surplus pages as possible, spread
  1831. * evenly across all nodes with memory. Iterate across these nodes
  1832. * until we can no longer free unreserved surplus pages. This occurs
  1833. * when the nodes with surplus pages have no free pages.
  1834. * free_pool_huge_page() will balance the freed pages across the
  1835. * on-line nodes with memory and will handle the hstate accounting.
  1836. *
  1837. * Note that we decrement resv_huge_pages as we free the pages. If
  1838. * we drop the lock, resv_huge_pages will still be sufficiently large
  1839. * to cover subsequent pages we may free.
  1840. */
  1841. while (nr_pages--) {
  1842. h->resv_huge_pages--;
  1843. unused_resv_pages--;
  1844. if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
  1845. goto out;
  1846. cond_resched_lock(&hugetlb_lock);
  1847. }
  1848. out:
  1849. /* Fully uncommit the reservation */
  1850. h->resv_huge_pages -= unused_resv_pages;
  1851. }
  1852. /*
  1853. * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
  1854. * are used by the huge page allocation routines to manage reservations.
  1855. *
  1856. * vma_needs_reservation is called to determine if the huge page at addr
  1857. * within the vma has an associated reservation. If a reservation is
  1858. * needed, the value 1 is returned. The caller is then responsible for
  1859. * managing the global reservation and subpool usage counts. After
  1860. * the huge page has been allocated, vma_commit_reservation is called
  1861. * to add the page to the reservation map. If the page allocation fails,
  1862. * the reservation must be ended instead of committed. vma_end_reservation
  1863. * is called in such cases.
  1864. *
  1865. * In the normal case, vma_commit_reservation returns the same value
  1866. * as the preceding vma_needs_reservation call. The only time this
  1867. * is not the case is if a reserve map was changed between calls. It
  1868. * is the responsibility of the caller to notice the difference and
  1869. * take appropriate action.
  1870. *
  1871. * vma_add_reservation is used in error paths where a reservation must
  1872. * be restored when a newly allocated huge page must be freed. It is
  1873. * to be called after calling vma_needs_reservation to determine if a
  1874. * reservation exists.
  1875. */
  1876. enum vma_resv_mode {
  1877. VMA_NEEDS_RESV,
  1878. VMA_COMMIT_RESV,
  1879. VMA_END_RESV,
  1880. VMA_ADD_RESV,
  1881. };
  1882. static long __vma_reservation_common(struct hstate *h,
  1883. struct vm_area_struct *vma, unsigned long addr,
  1884. enum vma_resv_mode mode)
  1885. {
  1886. struct resv_map *resv;
  1887. pgoff_t idx;
  1888. long ret;
  1889. long dummy_out_regions_needed;
  1890. resv = vma_resv_map(vma);
  1891. if (!resv)
  1892. return 1;
  1893. idx = vma_hugecache_offset(h, vma, addr);
  1894. switch (mode) {
  1895. case VMA_NEEDS_RESV:
  1896. ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
  1897. /* We assume that vma_reservation_* routines always operate on
  1898. * 1 page, and that adding to resv map a 1 page entry can only
  1899. * ever require 1 region.
  1900. */
  1901. VM_BUG_ON(dummy_out_regions_needed != 1);
  1902. break;
  1903. case VMA_COMMIT_RESV:
  1904. ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
  1905. /* region_add calls of range 1 should never fail. */
  1906. VM_BUG_ON(ret < 0);
  1907. break;
  1908. case VMA_END_RESV:
  1909. region_abort(resv, idx, idx + 1, 1);
  1910. ret = 0;
  1911. break;
  1912. case VMA_ADD_RESV:
  1913. if (vma->vm_flags & VM_MAYSHARE) {
  1914. ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
  1915. /* region_add calls of range 1 should never fail. */
  1916. VM_BUG_ON(ret < 0);
  1917. } else {
  1918. region_abort(resv, idx, idx + 1, 1);
  1919. ret = region_del(resv, idx, idx + 1);
  1920. }
  1921. break;
  1922. default:
  1923. BUG();
  1924. }
  1925. if (vma->vm_flags & VM_MAYSHARE)
  1926. return ret;
  1927. else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) {
  1928. /*
  1929. * In most cases, reserves always exist for private mappings.
  1930. * However, a file associated with mapping could have been
  1931. * hole punched or truncated after reserves were consumed.
  1932. * As subsequent fault on such a range will not use reserves.
  1933. * Subtle - The reserve map for private mappings has the
  1934. * opposite meaning than that of shared mappings. If NO
  1935. * entry is in the reserve map, it means a reservation exists.
  1936. * If an entry exists in the reserve map, it means the
  1937. * reservation has already been consumed. As a result, the
  1938. * return value of this routine is the opposite of the
  1939. * value returned from reserve map manipulation routines above.
  1940. */
  1941. if (ret)
  1942. return 0;
  1943. else
  1944. return 1;
  1945. }
  1946. else
  1947. return ret < 0 ? ret : 0;
  1948. }
  1949. static long vma_needs_reservation(struct hstate *h,
  1950. struct vm_area_struct *vma, unsigned long addr)
  1951. {
  1952. return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
  1953. }
  1954. static long vma_commit_reservation(struct hstate *h,
  1955. struct vm_area_struct *vma, unsigned long addr)
  1956. {
  1957. return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
  1958. }
  1959. static void vma_end_reservation(struct hstate *h,
  1960. struct vm_area_struct *vma, unsigned long addr)
  1961. {
  1962. (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
  1963. }
  1964. static long vma_add_reservation(struct hstate *h,
  1965. struct vm_area_struct *vma, unsigned long addr)
  1966. {
  1967. return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
  1968. }
  1969. /*
  1970. * This routine is called to restore a reservation on error paths. In the
  1971. * specific error paths, a huge page was allocated (via alloc_huge_page)
  1972. * and is about to be freed. If a reservation for the page existed,
  1973. * alloc_huge_page would have consumed the reservation and set PagePrivate
  1974. * in the newly allocated page. When the page is freed via free_huge_page,
  1975. * the global reservation count will be incremented if PagePrivate is set.
  1976. * However, free_huge_page can not adjust the reserve map. Adjust the
  1977. * reserve map here to be consistent with global reserve count adjustments
  1978. * to be made by free_huge_page.
  1979. */
  1980. static void restore_reserve_on_error(struct hstate *h,
  1981. struct vm_area_struct *vma, unsigned long address,
  1982. struct page *page)
  1983. {
  1984. if (unlikely(PagePrivate(page))) {
  1985. long rc = vma_needs_reservation(h, vma, address);
  1986. if (unlikely(rc < 0)) {
  1987. /*
  1988. * Rare out of memory condition in reserve map
  1989. * manipulation. Clear PagePrivate so that
  1990. * global reserve count will not be incremented
  1991. * by free_huge_page. This will make it appear
  1992. * as though the reservation for this page was
  1993. * consumed. This may prevent the task from
  1994. * faulting in the page at a later time. This
  1995. * is better than inconsistent global huge page
  1996. * accounting of reserve counts.
  1997. */
  1998. ClearPagePrivate(page);
  1999. } else if (rc) {
  2000. rc = vma_add_reservation(h, vma, address);
  2001. if (unlikely(rc < 0))
  2002. /*
  2003. * See above comment about rare out of
  2004. * memory condition.
  2005. */
  2006. ClearPagePrivate(page);
  2007. } else
  2008. vma_end_reservation(h, vma, address);
  2009. }
  2010. }
  2011. struct page *alloc_huge_page(struct vm_area_struct *vma,
  2012. unsigned long addr, int avoid_reserve)
  2013. {
  2014. struct hugepage_subpool *spool = subpool_vma(vma);
  2015. struct hstate *h = hstate_vma(vma);
  2016. struct page *page;
  2017. long map_chg, map_commit;
  2018. long gbl_chg;
  2019. int ret, idx;
  2020. struct hugetlb_cgroup *h_cg;
  2021. bool deferred_reserve;
  2022. idx = hstate_index(h);
  2023. /*
  2024. * Examine the region/reserve map to determine if the process
  2025. * has a reservation for the page to be allocated. A return
  2026. * code of zero indicates a reservation exists (no change).
  2027. */
  2028. map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
  2029. if (map_chg < 0)
  2030. return ERR_PTR(-ENOMEM);
  2031. /*
  2032. * Processes that did not create the mapping will have no
  2033. * reserves as indicated by the region/reserve map. Check
  2034. * that the allocation will not exceed the subpool limit.
  2035. * Allocations for MAP_NORESERVE mappings also need to be
  2036. * checked against any subpool limit.
  2037. */
  2038. if (map_chg || avoid_reserve) {
  2039. gbl_chg = hugepage_subpool_get_pages(spool, 1);
  2040. if (gbl_chg < 0) {
  2041. vma_end_reservation(h, vma, addr);
  2042. return ERR_PTR(-ENOSPC);
  2043. }
  2044. /*
  2045. * Even though there was no reservation in the region/reserve
  2046. * map, there could be reservations associated with the
  2047. * subpool that can be used. This would be indicated if the
  2048. * return value of hugepage_subpool_get_pages() is zero.
  2049. * However, if avoid_reserve is specified we still avoid even
  2050. * the subpool reservations.
  2051. */
  2052. if (avoid_reserve)
  2053. gbl_chg = 1;
  2054. }
  2055. /* If this allocation is not consuming a reservation, charge it now.
  2056. */
  2057. deferred_reserve = map_chg || avoid_reserve || !vma_resv_map(vma);
  2058. if (deferred_reserve) {
  2059. ret = hugetlb_cgroup_charge_cgroup_rsvd(
  2060. idx, pages_per_huge_page(h), &h_cg);
  2061. if (ret)
  2062. goto out_subpool_put;
  2063. }
  2064. ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
  2065. if (ret)
  2066. goto out_uncharge_cgroup_reservation;
  2067. spin_lock(&hugetlb_lock);
  2068. /*
  2069. * glb_chg is passed to indicate whether or not a page must be taken
  2070. * from the global free pool (global change). gbl_chg == 0 indicates
  2071. * a reservation exists for the allocation.
  2072. */
  2073. page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
  2074. if (!page) {
  2075. spin_unlock(&hugetlb_lock);
  2076. page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
  2077. if (!page)
  2078. goto out_uncharge_cgroup;
  2079. if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
  2080. SetPagePrivate(page);
  2081. h->resv_huge_pages--;
  2082. }
  2083. spin_lock(&hugetlb_lock);
  2084. list_add(&page->lru, &h->hugepage_activelist);
  2085. /* Fall through */
  2086. }
  2087. hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
  2088. /* If allocation is not consuming a reservation, also store the
  2089. * hugetlb_cgroup pointer on the page.
  2090. */
  2091. if (deferred_reserve) {
  2092. hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
  2093. h_cg, page);
  2094. }
  2095. spin_unlock(&hugetlb_lock);
  2096. set_page_private(page, (unsigned long)spool);
  2097. map_commit = vma_commit_reservation(h, vma, addr);
  2098. if (unlikely(map_chg > map_commit)) {
  2099. /*
  2100. * The page was added to the reservation map between
  2101. * vma_needs_reservation and vma_commit_reservation.
  2102. * This indicates a race with hugetlb_reserve_pages.
  2103. * Adjust for the subpool count incremented above AND
  2104. * in hugetlb_reserve_pages for the same page. Also,
  2105. * the reservation count added in hugetlb_reserve_pages
  2106. * no longer applies.
  2107. */
  2108. long rsv_adjust;
  2109. rsv_adjust = hugepage_subpool_put_pages(spool, 1);
  2110. hugetlb_acct_memory(h, -rsv_adjust);
  2111. if (deferred_reserve)
  2112. hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
  2113. pages_per_huge_page(h), page);
  2114. }
  2115. return page;
  2116. out_uncharge_cgroup:
  2117. hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
  2118. out_uncharge_cgroup_reservation:
  2119. if (deferred_reserve)
  2120. hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
  2121. h_cg);
  2122. out_subpool_put:
  2123. if (map_chg || avoid_reserve)
  2124. hugepage_subpool_put_pages(spool, 1);
  2125. vma_end_reservation(h, vma, addr);
  2126. return ERR_PTR(-ENOSPC);
  2127. }
  2128. int alloc_bootmem_huge_page(struct hstate *h)
  2129. __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
  2130. int __alloc_bootmem_huge_page(struct hstate *h)
  2131. {
  2132. struct huge_bootmem_page *m;
  2133. int nr_nodes, node;
  2134. for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
  2135. void *addr;
  2136. addr = memblock_alloc_try_nid_raw(
  2137. huge_page_size(h), huge_page_size(h),
  2138. 0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
  2139. if (addr) {
  2140. /*
  2141. * Use the beginning of the huge page to store the
  2142. * huge_bootmem_page struct (until gather_bootmem
  2143. * puts them into the mem_map).
  2144. */
  2145. m = addr;
  2146. goto found;
  2147. }
  2148. }
  2149. return 0;
  2150. found:
  2151. BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
  2152. /* Put them into a private list first because mem_map is not up yet */
  2153. INIT_LIST_HEAD(&m->list);
  2154. list_add(&m->list, &huge_boot_pages);
  2155. m->hstate = h;
  2156. return 1;
  2157. }
  2158. /*
  2159. * Put bootmem huge pages into the standard lists after mem_map is up.
  2160. * Note: This only applies to gigantic (order > MAX_ORDER) pages.
  2161. */
  2162. static void __init gather_bootmem_prealloc(void)
  2163. {
  2164. struct huge_bootmem_page *m;
  2165. list_for_each_entry(m, &huge_boot_pages, list) {
  2166. struct page *page = virt_to_page(m);
  2167. struct hstate *h = m->hstate;
  2168. VM_BUG_ON(!hstate_is_gigantic(h));
  2169. WARN_ON(page_count(page) != 1);
  2170. prep_compound_gigantic_page(page, huge_page_order(h));
  2171. WARN_ON(PageReserved(page));
  2172. prep_new_huge_page(h, page, page_to_nid(page));
  2173. put_page(page); /* free it into the hugepage allocator */
  2174. /*
  2175. * We need to restore the 'stolen' pages to totalram_pages
  2176. * in order to fix confusing memory reports from free(1) and
  2177. * other side-effects, like CommitLimit going negative.
  2178. */
  2179. adjust_managed_page_count(page, pages_per_huge_page(h));
  2180. cond_resched();
  2181. }
  2182. }
  2183. static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
  2184. {
  2185. unsigned long i;
  2186. nodemask_t *node_alloc_noretry;
  2187. if (!hstate_is_gigantic(h)) {
  2188. /*
  2189. * Bit mask controlling how hard we retry per-node allocations.
  2190. * Ignore errors as lower level routines can deal with
  2191. * node_alloc_noretry == NULL. If this kmalloc fails at boot
  2192. * time, we are likely in bigger trouble.
  2193. */
  2194. node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
  2195. GFP_KERNEL);
  2196. } else {
  2197. /* allocations done at boot time */
  2198. node_alloc_noretry = NULL;
  2199. }
  2200. /* bit mask controlling how hard we retry per-node allocations */
  2201. if (node_alloc_noretry)
  2202. nodes_clear(*node_alloc_noretry);
  2203. for (i = 0; i < h->max_huge_pages; ++i) {
  2204. if (hstate_is_gigantic(h)) {
  2205. if (hugetlb_cma_size) {
  2206. pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
  2207. goto free;
  2208. }
  2209. if (!alloc_bootmem_huge_page(h))
  2210. break;
  2211. } else if (!alloc_pool_huge_page(h,
  2212. &node_states[N_MEMORY],
  2213. node_alloc_noretry))
  2214. break;
  2215. cond_resched();
  2216. }
  2217. if (i < h->max_huge_pages) {
  2218. char buf[32];
  2219. string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
  2220. pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
  2221. h->max_huge_pages, buf, i);
  2222. h->max_huge_pages = i;
  2223. }
  2224. free:
  2225. kfree(node_alloc_noretry);
  2226. }
  2227. static void __init hugetlb_init_hstates(void)
  2228. {
  2229. struct hstate *h;
  2230. for_each_hstate(h) {
  2231. if (minimum_order > huge_page_order(h))
  2232. minimum_order = huge_page_order(h);
  2233. /* oversize hugepages were init'ed in early boot */
  2234. if (!hstate_is_gigantic(h))
  2235. hugetlb_hstate_alloc_pages(h);
  2236. }
  2237. VM_BUG_ON(minimum_order == UINT_MAX);
  2238. }
  2239. static void __init report_hugepages(void)
  2240. {
  2241. struct hstate *h;
  2242. for_each_hstate(h) {
  2243. char buf[32];
  2244. string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
  2245. pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
  2246. buf, h->free_huge_pages);
  2247. }
  2248. }
  2249. #ifdef CONFIG_HIGHMEM
  2250. static void try_to_free_low(struct hstate *h, unsigned long count,
  2251. nodemask_t *nodes_allowed)
  2252. {
  2253. int i;
  2254. if (hstate_is_gigantic(h))
  2255. return;
  2256. for_each_node_mask(i, *nodes_allowed) {
  2257. struct page *page, *next;
  2258. struct list_head *freel = &h->hugepage_freelists[i];
  2259. list_for_each_entry_safe(page, next, freel, lru) {
  2260. if (count >= h->nr_huge_pages)
  2261. return;
  2262. if (PageHighMem(page))
  2263. continue;
  2264. list_del(&page->lru);
  2265. update_and_free_page(h, page);
  2266. h->free_huge_pages--;
  2267. h->free_huge_pages_node[page_to_nid(page)]--;
  2268. }
  2269. }
  2270. }
  2271. #else
  2272. static inline void try_to_free_low(struct hstate *h, unsigned long count,
  2273. nodemask_t *nodes_allowed)
  2274. {
  2275. }
  2276. #endif
  2277. /*
  2278. * Increment or decrement surplus_huge_pages. Keep node-specific counters
  2279. * balanced by operating on them in a round-robin fashion.
  2280. * Returns 1 if an adjustment was made.
  2281. */
  2282. static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
  2283. int delta)
  2284. {
  2285. int nr_nodes, node;
  2286. VM_BUG_ON(delta != -1 && delta != 1);
  2287. if (delta < 0) {
  2288. for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
  2289. if (h->surplus_huge_pages_node[node])
  2290. goto found;
  2291. }
  2292. } else {
  2293. for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
  2294. if (h->surplus_huge_pages_node[node] <
  2295. h->nr_huge_pages_node[node])
  2296. goto found;
  2297. }
  2298. }
  2299. return 0;
  2300. found:
  2301. h->surplus_huge_pages += delta;
  2302. h->surplus_huge_pages_node[node] += delta;
  2303. return 1;
  2304. }
  2305. #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
  2306. static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
  2307. nodemask_t *nodes_allowed)
  2308. {
  2309. unsigned long min_count, ret;
  2310. NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
  2311. /*
  2312. * Bit mask controlling how hard we retry per-node allocations.
  2313. * If we can not allocate the bit mask, do not attempt to allocate
  2314. * the requested huge pages.
  2315. */
  2316. if (node_alloc_noretry)
  2317. nodes_clear(*node_alloc_noretry);
  2318. else
  2319. return -ENOMEM;
  2320. spin_lock(&hugetlb_lock);
  2321. /*
  2322. * Check for a node specific request.
  2323. * Changing node specific huge page count may require a corresponding
  2324. * change to the global count. In any case, the passed node mask
  2325. * (nodes_allowed) will restrict alloc/free to the specified node.
  2326. */
  2327. if (nid != NUMA_NO_NODE) {
  2328. unsigned long old_count = count;
  2329. count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
  2330. /*
  2331. * User may have specified a large count value which caused the
  2332. * above calculation to overflow. In this case, they wanted
  2333. * to allocate as many huge pages as possible. Set count to
  2334. * largest possible value to align with their intention.
  2335. */
  2336. if (count < old_count)
  2337. count = ULONG_MAX;
  2338. }
  2339. /*
  2340. * Gigantic pages runtime allocation depend on the capability for large
  2341. * page range allocation.
  2342. * If the system does not provide this feature, return an error when
  2343. * the user tries to allocate gigantic pages but let the user free the
  2344. * boottime allocated gigantic pages.
  2345. */
  2346. if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
  2347. if (count > persistent_huge_pages(h)) {
  2348. spin_unlock(&hugetlb_lock);
  2349. NODEMASK_FREE(node_alloc_noretry);
  2350. return -EINVAL;
  2351. }
  2352. /* Fall through to decrease pool */
  2353. }
  2354. /*
  2355. * Increase the pool size
  2356. * First take pages out of surplus state. Then make up the
  2357. * remaining difference by allocating fresh huge pages.
  2358. *
  2359. * We might race with alloc_surplus_huge_page() here and be unable
  2360. * to convert a surplus huge page to a normal huge page. That is
  2361. * not critical, though, it just means the overall size of the
  2362. * pool might be one hugepage larger than it needs to be, but
  2363. * within all the constraints specified by the sysctls.
  2364. */
  2365. while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
  2366. if (!adjust_pool_surplus(h, nodes_allowed, -1))
  2367. break;
  2368. }
  2369. while (count > persistent_huge_pages(h)) {
  2370. /*
  2371. * If this allocation races such that we no longer need the
  2372. * page, free_huge_page will handle it by freeing the page
  2373. * and reducing the surplus.
  2374. */
  2375. spin_unlock(&hugetlb_lock);
  2376. /* yield cpu to avoid soft lockup */
  2377. cond_resched();
  2378. ret = alloc_pool_huge_page(h, nodes_allowed,
  2379. node_alloc_noretry);
  2380. spin_lock(&hugetlb_lock);
  2381. if (!ret)
  2382. goto out;
  2383. /* Bail for signals. Probably ctrl-c from user */
  2384. if (signal_pending(current))
  2385. goto out;
  2386. }
  2387. /*
  2388. * Decrease the pool size
  2389. * First return free pages to the buddy allocator (being careful
  2390. * to keep enough around to satisfy reservations). Then place
  2391. * pages into surplus state as needed so the pool will shrink
  2392. * to the desired size as pages become free.
  2393. *
  2394. * By placing pages into the surplus state independent of the
  2395. * overcommit value, we are allowing the surplus pool size to
  2396. * exceed overcommit. There are few sane options here. Since
  2397. * alloc_surplus_huge_page() is checking the global counter,
  2398. * though, we'll note that we're not allowed to exceed surplus
  2399. * and won't grow the pool anywhere else. Not until one of the
  2400. * sysctls are changed, or the surplus pages go out of use.
  2401. */
  2402. min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
  2403. min_count = max(count, min_count);
  2404. try_to_free_low(h, min_count, nodes_allowed);
  2405. while (min_count < persistent_huge_pages(h)) {
  2406. if (!free_pool_huge_page(h, nodes_allowed, 0))
  2407. break;
  2408. cond_resched_lock(&hugetlb_lock);
  2409. }
  2410. while (count < persistent_huge_pages(h)) {
  2411. if (!adjust_pool_surplus(h, nodes_allowed, 1))
  2412. break;
  2413. }
  2414. out:
  2415. h->max_huge_pages = persistent_huge_pages(h);
  2416. spin_unlock(&hugetlb_lock);
  2417. NODEMASK_FREE(node_alloc_noretry);
  2418. return 0;
  2419. }
  2420. #define HSTATE_ATTR_RO(_name) \
  2421. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  2422. #define HSTATE_ATTR(_name) \
  2423. static struct kobj_attribute _name##_attr = \
  2424. __ATTR(_name, 0644, _name##_show, _name##_store)
  2425. static struct kobject *hugepages_kobj;
  2426. static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
  2427. static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
  2428. static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
  2429. {
  2430. int i;
  2431. for (i = 0; i < HUGE_MAX_HSTATE; i++)
  2432. if (hstate_kobjs[i] == kobj) {
  2433. if (nidp)
  2434. *nidp = NUMA_NO_NODE;
  2435. return &hstates[i];
  2436. }
  2437. return kobj_to_node_hstate(kobj, nidp);
  2438. }
  2439. static ssize_t nr_hugepages_show_common(struct kobject *kobj,
  2440. struct kobj_attribute *attr, char *buf)
  2441. {
  2442. struct hstate *h;
  2443. unsigned long nr_huge_pages;
  2444. int nid;
  2445. h = kobj_to_hstate(kobj, &nid);
  2446. if (nid == NUMA_NO_NODE)
  2447. nr_huge_pages = h->nr_huge_pages;
  2448. else
  2449. nr_huge_pages = h->nr_huge_pages_node[nid];
  2450. return sprintf(buf, "%lu\n", nr_huge_pages);
  2451. }
  2452. static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
  2453. struct hstate *h, int nid,
  2454. unsigned long count, size_t len)
  2455. {
  2456. int err;
  2457. nodemask_t nodes_allowed, *n_mask;
  2458. if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
  2459. return -EINVAL;
  2460. if (nid == NUMA_NO_NODE) {
  2461. /*
  2462. * global hstate attribute
  2463. */
  2464. if (!(obey_mempolicy &&
  2465. init_nodemask_of_mempolicy(&nodes_allowed)))
  2466. n_mask = &node_states[N_MEMORY];
  2467. else
  2468. n_mask = &nodes_allowed;
  2469. } else {
  2470. /*
  2471. * Node specific request. count adjustment happens in
  2472. * set_max_huge_pages() after acquiring hugetlb_lock.
  2473. */
  2474. init_nodemask_of_node(&nodes_allowed, nid);
  2475. n_mask = &nodes_allowed;
  2476. }
  2477. err = set_max_huge_pages(h, count, nid, n_mask);
  2478. return err ? err : len;
  2479. }
  2480. static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
  2481. struct kobject *kobj, const char *buf,
  2482. size_t len)
  2483. {
  2484. struct hstate *h;
  2485. unsigned long count;
  2486. int nid;
  2487. int err;
  2488. err = kstrtoul(buf, 10, &count);
  2489. if (err)
  2490. return err;
  2491. h = kobj_to_hstate(kobj, &nid);
  2492. return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
  2493. }
  2494. static ssize_t nr_hugepages_show(struct kobject *kobj,
  2495. struct kobj_attribute *attr, char *buf)
  2496. {
  2497. return nr_hugepages_show_common(kobj, attr, buf);
  2498. }
  2499. static ssize_t nr_hugepages_store(struct kobject *kobj,
  2500. struct kobj_attribute *attr, const char *buf, size_t len)
  2501. {
  2502. return nr_hugepages_store_common(false, kobj, buf, len);
  2503. }
  2504. HSTATE_ATTR(nr_hugepages);
  2505. #ifdef CONFIG_NUMA
  2506. /*
  2507. * hstate attribute for optionally mempolicy-based constraint on persistent
  2508. * huge page alloc/free.
  2509. */
  2510. static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
  2511. struct kobj_attribute *attr, char *buf)
  2512. {
  2513. return nr_hugepages_show_common(kobj, attr, buf);
  2514. }
  2515. static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
  2516. struct kobj_attribute *attr, const char *buf, size_t len)
  2517. {
  2518. return nr_hugepages_store_common(true, kobj, buf, len);
  2519. }
  2520. HSTATE_ATTR(nr_hugepages_mempolicy);
  2521. #endif
  2522. static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
  2523. struct kobj_attribute *attr, char *buf)
  2524. {
  2525. struct hstate *h = kobj_to_hstate(kobj, NULL);
  2526. return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
  2527. }
  2528. static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
  2529. struct kobj_attribute *attr, const char *buf, size_t count)
  2530. {
  2531. int err;
  2532. unsigned long input;
  2533. struct hstate *h = kobj_to_hstate(kobj, NULL);
  2534. if (hstate_is_gigantic(h))
  2535. return -EINVAL;
  2536. err = kstrtoul(buf, 10, &input);
  2537. if (err)
  2538. return err;
  2539. spin_lock(&hugetlb_lock);
  2540. h->nr_overcommit_huge_pages = input;
  2541. spin_unlock(&hugetlb_lock);
  2542. return count;
  2543. }
  2544. HSTATE_ATTR(nr_overcommit_hugepages);
  2545. static ssize_t free_hugepages_show(struct kobject *kobj,
  2546. struct kobj_attribute *attr, char *buf)
  2547. {
  2548. struct hstate *h;
  2549. unsigned long free_huge_pages;
  2550. int nid;
  2551. h = kobj_to_hstate(kobj, &nid);
  2552. if (nid == NUMA_NO_NODE)
  2553. free_huge_pages = h->free_huge_pages;
  2554. else
  2555. free_huge_pages = h->free_huge_pages_node[nid];
  2556. return sprintf(buf, "%lu\n", free_huge_pages);
  2557. }
  2558. HSTATE_ATTR_RO(free_hugepages);
  2559. static ssize_t resv_hugepages_show(struct kobject *kobj,
  2560. struct kobj_attribute *attr, char *buf)
  2561. {
  2562. struct hstate *h = kobj_to_hstate(kobj, NULL);
  2563. return sprintf(buf, "%lu\n", h->resv_huge_pages);
  2564. }
  2565. HSTATE_ATTR_RO(resv_hugepages);
  2566. static ssize_t surplus_hugepages_show(struct kobject *kobj,
  2567. struct kobj_attribute *attr, char *buf)
  2568. {
  2569. struct hstate *h;
  2570. unsigned long surplus_huge_pages;
  2571. int nid;
  2572. h = kobj_to_hstate(kobj, &nid);
  2573. if (nid == NUMA_NO_NODE)
  2574. surplus_huge_pages = h->surplus_huge_pages;
  2575. else
  2576. surplus_huge_pages = h->surplus_huge_pages_node[nid];
  2577. return sprintf(buf, "%lu\n", surplus_huge_pages);
  2578. }
  2579. HSTATE_ATTR_RO(surplus_hugepages);
  2580. static struct attribute *hstate_attrs[] = {
  2581. &nr_hugepages_attr.attr,
  2582. &nr_overcommit_hugepages_attr.attr,
  2583. &free_hugepages_attr.attr,
  2584. &resv_hugepages_attr.attr,
  2585. &surplus_hugepages_attr.attr,
  2586. #ifdef CONFIG_NUMA
  2587. &nr_hugepages_mempolicy_attr.attr,
  2588. #endif
  2589. NULL,
  2590. };
  2591. static const struct attribute_group hstate_attr_group = {
  2592. .attrs = hstate_attrs,
  2593. };
  2594. static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
  2595. struct kobject **hstate_kobjs,
  2596. const struct attribute_group *hstate_attr_group)
  2597. {
  2598. int retval;
  2599. int hi = hstate_index(h);
  2600. hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
  2601. if (!hstate_kobjs[hi])
  2602. return -ENOMEM;
  2603. retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
  2604. if (retval) {
  2605. kobject_put(hstate_kobjs[hi]);
  2606. hstate_kobjs[hi] = NULL;
  2607. }
  2608. return retval;
  2609. }
  2610. static void __init hugetlb_sysfs_init(void)
  2611. {
  2612. struct hstate *h;
  2613. int err;
  2614. hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
  2615. if (!hugepages_kobj)
  2616. return;
  2617. for_each_hstate(h) {
  2618. err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
  2619. hstate_kobjs, &hstate_attr_group);
  2620. if (err)
  2621. pr_err("HugeTLB: Unable to add hstate %s", h->name);
  2622. }
  2623. }
  2624. #ifdef CONFIG_NUMA
  2625. /*
  2626. * node_hstate/s - associate per node hstate attributes, via their kobjects,
  2627. * with node devices in node_devices[] using a parallel array. The array
  2628. * index of a node device or _hstate == node id.
  2629. * This is here to avoid any static dependency of the node device driver, in
  2630. * the base kernel, on the hugetlb module.
  2631. */
  2632. struct node_hstate {
  2633. struct kobject *hugepages_kobj;
  2634. struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
  2635. };
  2636. static struct node_hstate node_hstates[MAX_NUMNODES];
  2637. /*
  2638. * A subset of global hstate attributes for node devices
  2639. */
  2640. static struct attribute *per_node_hstate_attrs[] = {
  2641. &nr_hugepages_attr.attr,
  2642. &free_hugepages_attr.attr,
  2643. &surplus_hugepages_attr.attr,
  2644. NULL,
  2645. };
  2646. static const struct attribute_group per_node_hstate_attr_group = {
  2647. .attrs = per_node_hstate_attrs,
  2648. };
  2649. /*
  2650. * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
  2651. * Returns node id via non-NULL nidp.
  2652. */
  2653. static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
  2654. {
  2655. int nid;
  2656. for (nid = 0; nid < nr_node_ids; nid++) {
  2657. struct node_hstate *nhs = &node_hstates[nid];
  2658. int i;
  2659. for (i = 0; i < HUGE_MAX_HSTATE; i++)
  2660. if (nhs->hstate_kobjs[i] == kobj) {
  2661. if (nidp)
  2662. *nidp = nid;
  2663. return &hstates[i];
  2664. }
  2665. }
  2666. BUG();
  2667. return NULL;
  2668. }
  2669. /*
  2670. * Unregister hstate attributes from a single node device.
  2671. * No-op if no hstate attributes attached.
  2672. */
  2673. static void hugetlb_unregister_node(struct node *node)
  2674. {
  2675. struct hstate *h;
  2676. struct node_hstate *nhs = &node_hstates[node->dev.id];
  2677. if (!nhs->hugepages_kobj)
  2678. return; /* no hstate attributes */
  2679. for_each_hstate(h) {
  2680. int idx = hstate_index(h);
  2681. if (nhs->hstate_kobjs[idx]) {
  2682. kobject_put(nhs->hstate_kobjs[idx]);
  2683. nhs->hstate_kobjs[idx] = NULL;
  2684. }
  2685. }
  2686. kobject_put(nhs->hugepages_kobj);
  2687. nhs->hugepages_kobj = NULL;
  2688. }
  2689. /*
  2690. * Register hstate attributes for a single node device.
  2691. * No-op if attributes already registered.
  2692. */
  2693. static void hugetlb_register_node(struct node *node)
  2694. {
  2695. struct hstate *h;
  2696. struct node_hstate *nhs = &node_hstates[node->dev.id];
  2697. int err;
  2698. if (nhs->hugepages_kobj)
  2699. return; /* already allocated */
  2700. nhs->hugepages_kobj = kobject_create_and_add("hugepages",
  2701. &node->dev.kobj);
  2702. if (!nhs->hugepages_kobj)
  2703. return;
  2704. for_each_hstate(h) {
  2705. err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
  2706. nhs->hstate_kobjs,
  2707. &per_node_hstate_attr_group);
  2708. if (err) {
  2709. pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
  2710. h->name, node->dev.id);
  2711. hugetlb_unregister_node(node);
  2712. break;
  2713. }
  2714. }
  2715. }
  2716. /*
  2717. * hugetlb init time: register hstate attributes for all registered node
  2718. * devices of nodes that have memory. All on-line nodes should have
  2719. * registered their associated device by this time.
  2720. */
  2721. static void __init hugetlb_register_all_nodes(void)
  2722. {
  2723. int nid;
  2724. for_each_node_state(nid, N_MEMORY) {
  2725. struct node *node = node_devices[nid];
  2726. if (node->dev.id == nid)
  2727. hugetlb_register_node(node);
  2728. }
  2729. /*
  2730. * Let the node device driver know we're here so it can
  2731. * [un]register hstate attributes on node hotplug.
  2732. */
  2733. register_hugetlbfs_with_node(hugetlb_register_node,
  2734. hugetlb_unregister_node);
  2735. }
  2736. #else /* !CONFIG_NUMA */
  2737. static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
  2738. {
  2739. BUG();
  2740. if (nidp)
  2741. *nidp = -1;
  2742. return NULL;
  2743. }
  2744. static void hugetlb_register_all_nodes(void) { }
  2745. #endif
  2746. static int __init hugetlb_init(void)
  2747. {
  2748. int i;
  2749. if (!hugepages_supported()) {
  2750. if (hugetlb_max_hstate || default_hstate_max_huge_pages)
  2751. pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
  2752. return 0;
  2753. }
  2754. /*
  2755. * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
  2756. * architectures depend on setup being done here.
  2757. */
  2758. hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
  2759. if (!parsed_default_hugepagesz) {
  2760. /*
  2761. * If we did not parse a default huge page size, set
  2762. * default_hstate_idx to HPAGE_SIZE hstate. And, if the
  2763. * number of huge pages for this default size was implicitly
  2764. * specified, set that here as well.
  2765. * Note that the implicit setting will overwrite an explicit
  2766. * setting. A warning will be printed in this case.
  2767. */
  2768. default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
  2769. if (default_hstate_max_huge_pages) {
  2770. if (default_hstate.max_huge_pages) {
  2771. char buf[32];
  2772. string_get_size(huge_page_size(&default_hstate),
  2773. 1, STRING_UNITS_2, buf, 32);
  2774. pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
  2775. default_hstate.max_huge_pages, buf);
  2776. pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
  2777. default_hstate_max_huge_pages);
  2778. }
  2779. default_hstate.max_huge_pages =
  2780. default_hstate_max_huge_pages;
  2781. }
  2782. }
  2783. hugetlb_cma_check();
  2784. hugetlb_init_hstates();
  2785. gather_bootmem_prealloc();
  2786. report_hugepages();
  2787. hugetlb_sysfs_init();
  2788. hugetlb_register_all_nodes();
  2789. hugetlb_cgroup_file_init();
  2790. #ifdef CONFIG_SMP
  2791. num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
  2792. #else
  2793. num_fault_mutexes = 1;
  2794. #endif
  2795. hugetlb_fault_mutex_table =
  2796. kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
  2797. GFP_KERNEL);
  2798. BUG_ON(!hugetlb_fault_mutex_table);
  2799. for (i = 0; i < num_fault_mutexes; i++)
  2800. mutex_init(&hugetlb_fault_mutex_table[i]);
  2801. return 0;
  2802. }
  2803. subsys_initcall(hugetlb_init);
  2804. /* Overwritten by architectures with more huge page sizes */
  2805. bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
  2806. {
  2807. return size == HPAGE_SIZE;
  2808. }
  2809. void __init hugetlb_add_hstate(unsigned int order)
  2810. {
  2811. struct hstate *h;
  2812. unsigned long i;
  2813. if (size_to_hstate(PAGE_SIZE << order)) {
  2814. return;
  2815. }
  2816. BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
  2817. BUG_ON(order == 0);
  2818. h = &hstates[hugetlb_max_hstate++];
  2819. h->order = order;
  2820. h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
  2821. h->nr_huge_pages = 0;
  2822. h->free_huge_pages = 0;
  2823. for (i = 0; i < MAX_NUMNODES; ++i)
  2824. INIT_LIST_HEAD(&h->hugepage_freelists[i]);
  2825. INIT_LIST_HEAD(&h->hugepage_activelist);
  2826. h->next_nid_to_alloc = first_memory_node;
  2827. h->next_nid_to_free = first_memory_node;
  2828. snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
  2829. huge_page_size(h)/1024);
  2830. parsed_hstate = h;
  2831. }
  2832. /*
  2833. * hugepages command line processing
  2834. * hugepages normally follows a valid hugepagsz or default_hugepagsz
  2835. * specification. If not, ignore the hugepages value. hugepages can also
  2836. * be the first huge page command line option in which case it implicitly
  2837. * specifies the number of huge pages for the default size.
  2838. */
  2839. static int __init hugepages_setup(char *s)
  2840. {
  2841. unsigned long *mhp;
  2842. static unsigned long *last_mhp;
  2843. if (!parsed_valid_hugepagesz) {
  2844. pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
  2845. parsed_valid_hugepagesz = true;
  2846. return 0;
  2847. }
  2848. /*
  2849. * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
  2850. * yet, so this hugepages= parameter goes to the "default hstate".
  2851. * Otherwise, it goes with the previously parsed hugepagesz or
  2852. * default_hugepagesz.
  2853. */
  2854. else if (!hugetlb_max_hstate)
  2855. mhp = &default_hstate_max_huge_pages;
  2856. else
  2857. mhp = &parsed_hstate->max_huge_pages;
  2858. if (mhp == last_mhp) {
  2859. pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
  2860. return 0;
  2861. }
  2862. if (sscanf(s, "%lu", mhp) <= 0)
  2863. *mhp = 0;
  2864. /*
  2865. * Global state is always initialized later in hugetlb_init.
  2866. * But we need to allocate >= MAX_ORDER hstates here early to still
  2867. * use the bootmem allocator.
  2868. */
  2869. if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
  2870. hugetlb_hstate_alloc_pages(parsed_hstate);
  2871. last_mhp = mhp;
  2872. return 1;
  2873. }
  2874. __setup("hugepages=", hugepages_setup);
  2875. /*
  2876. * hugepagesz command line processing
  2877. * A specific huge page size can only be specified once with hugepagesz.
  2878. * hugepagesz is followed by hugepages on the command line. The global
  2879. * variable 'parsed_valid_hugepagesz' is used to determine if prior
  2880. * hugepagesz argument was valid.
  2881. */
  2882. static int __init hugepagesz_setup(char *s)
  2883. {
  2884. unsigned long size;
  2885. struct hstate *h;
  2886. parsed_valid_hugepagesz = false;
  2887. size = (unsigned long)memparse(s, NULL);
  2888. if (!arch_hugetlb_valid_size(size)) {
  2889. pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
  2890. return 0;
  2891. }
  2892. h = size_to_hstate(size);
  2893. if (h) {
  2894. /*
  2895. * hstate for this size already exists. This is normally
  2896. * an error, but is allowed if the existing hstate is the
  2897. * default hstate. More specifically, it is only allowed if
  2898. * the number of huge pages for the default hstate was not
  2899. * previously specified.
  2900. */
  2901. if (!parsed_default_hugepagesz || h != &default_hstate ||
  2902. default_hstate.max_huge_pages) {
  2903. pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
  2904. return 0;
  2905. }
  2906. /*
  2907. * No need to call hugetlb_add_hstate() as hstate already
  2908. * exists. But, do set parsed_hstate so that a following
  2909. * hugepages= parameter will be applied to this hstate.
  2910. */
  2911. parsed_hstate = h;
  2912. parsed_valid_hugepagesz = true;
  2913. return 1;
  2914. }
  2915. hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
  2916. parsed_valid_hugepagesz = true;
  2917. return 1;
  2918. }
  2919. __setup("hugepagesz=", hugepagesz_setup);
  2920. /*
  2921. * default_hugepagesz command line input
  2922. * Only one instance of default_hugepagesz allowed on command line.
  2923. */
  2924. static int __init default_hugepagesz_setup(char *s)
  2925. {
  2926. unsigned long size;
  2927. parsed_valid_hugepagesz = false;
  2928. if (parsed_default_hugepagesz) {
  2929. pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
  2930. return 0;
  2931. }
  2932. size = (unsigned long)memparse(s, NULL);
  2933. if (!arch_hugetlb_valid_size(size)) {
  2934. pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
  2935. return 0;
  2936. }
  2937. hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
  2938. parsed_valid_hugepagesz = true;
  2939. parsed_default_hugepagesz = true;
  2940. default_hstate_idx = hstate_index(size_to_hstate(size));
  2941. /*
  2942. * The number of default huge pages (for this size) could have been
  2943. * specified as the first hugetlb parameter: hugepages=X. If so,
  2944. * then default_hstate_max_huge_pages is set. If the default huge
  2945. * page size is gigantic (>= MAX_ORDER), then the pages must be
  2946. * allocated here from bootmem allocator.
  2947. */
  2948. if (default_hstate_max_huge_pages) {
  2949. default_hstate.max_huge_pages = default_hstate_max_huge_pages;
  2950. if (hstate_is_gigantic(&default_hstate))
  2951. hugetlb_hstate_alloc_pages(&default_hstate);
  2952. default_hstate_max_huge_pages = 0;
  2953. }
  2954. return 1;
  2955. }
  2956. __setup("default_hugepagesz=", default_hugepagesz_setup);
  2957. static unsigned int allowed_mems_nr(struct hstate *h)
  2958. {
  2959. int node;
  2960. unsigned int nr = 0;
  2961. nodemask_t *mpol_allowed;
  2962. unsigned int *array = h->free_huge_pages_node;
  2963. gfp_t gfp_mask = htlb_alloc_mask(h);
  2964. mpol_allowed = policy_nodemask_current(gfp_mask);
  2965. for_each_node_mask(node, cpuset_current_mems_allowed) {
  2966. if (!mpol_allowed ||
  2967. (mpol_allowed && node_isset(node, *mpol_allowed)))
  2968. nr += array[node];
  2969. }
  2970. return nr;
  2971. }
  2972. #ifdef CONFIG_SYSCTL
  2973. static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
  2974. void *buffer, size_t *length,
  2975. loff_t *ppos, unsigned long *out)
  2976. {
  2977. struct ctl_table dup_table;
  2978. /*
  2979. * In order to avoid races with __do_proc_doulongvec_minmax(), we
  2980. * can duplicate the @table and alter the duplicate of it.
  2981. */
  2982. dup_table = *table;
  2983. dup_table.data = out;
  2984. return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
  2985. }
  2986. static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
  2987. struct ctl_table *table, int write,
  2988. void *buffer, size_t *length, loff_t *ppos)
  2989. {
  2990. struct hstate *h = &default_hstate;
  2991. unsigned long tmp = h->max_huge_pages;
  2992. int ret;
  2993. if (!hugepages_supported())
  2994. return -EOPNOTSUPP;
  2995. ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
  2996. &tmp);
  2997. if (ret)
  2998. goto out;
  2999. if (write)
  3000. ret = __nr_hugepages_store_common(obey_mempolicy, h,
  3001. NUMA_NO_NODE, tmp, *length);
  3002. out:
  3003. return ret;
  3004. }
  3005. int hugetlb_sysctl_handler(struct ctl_table *table, int write,
  3006. void *buffer, size_t *length, loff_t *ppos)
  3007. {
  3008. return hugetlb_sysctl_handler_common(false, table, write,
  3009. buffer, length, ppos);
  3010. }
  3011. #ifdef CONFIG_NUMA
  3012. int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
  3013. void *buffer, size_t *length, loff_t *ppos)
  3014. {
  3015. return hugetlb_sysctl_handler_common(true, table, write,
  3016. buffer, length, ppos);
  3017. }
  3018. #endif /* CONFIG_NUMA */
  3019. int hugetlb_overcommit_handler(struct ctl_table *table, int write,
  3020. void *buffer, size_t *length, loff_t *ppos)
  3021. {
  3022. struct hstate *h = &default_hstate;
  3023. unsigned long tmp;
  3024. int ret;
  3025. if (!hugepages_supported())
  3026. return -EOPNOTSUPP;
  3027. tmp = h->nr_overcommit_huge_pages;
  3028. if (write && hstate_is_gigantic(h))
  3029. return -EINVAL;
  3030. ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
  3031. &tmp);
  3032. if (ret)
  3033. goto out;
  3034. if (write) {
  3035. spin_lock(&hugetlb_lock);
  3036. h->nr_overcommit_huge_pages = tmp;
  3037. spin_unlock(&hugetlb_lock);
  3038. }
  3039. out:
  3040. return ret;
  3041. }
  3042. #endif /* CONFIG_SYSCTL */
  3043. void hugetlb_report_meminfo(struct seq_file *m)
  3044. {
  3045. struct hstate *h;
  3046. unsigned long total = 0;
  3047. if (!hugepages_supported())
  3048. return;
  3049. for_each_hstate(h) {
  3050. unsigned long count = h->nr_huge_pages;
  3051. total += (PAGE_SIZE << huge_page_order(h)) * count;
  3052. if (h == &default_hstate)
  3053. seq_printf(m,
  3054. "HugePages_Total: %5lu\n"
  3055. "HugePages_Free: %5lu\n"
  3056. "HugePages_Rsvd: %5lu\n"
  3057. "HugePages_Surp: %5lu\n"
  3058. "Hugepagesize: %8lu kB\n",
  3059. count,
  3060. h->free_huge_pages,
  3061. h->resv_huge_pages,
  3062. h->surplus_huge_pages,
  3063. (PAGE_SIZE << huge_page_order(h)) / 1024);
  3064. }
  3065. seq_printf(m, "Hugetlb: %8lu kB\n", total / 1024);
  3066. }
  3067. int hugetlb_report_node_meminfo(char *buf, int len, int nid)
  3068. {
  3069. struct hstate *h = &default_hstate;
  3070. if (!hugepages_supported())
  3071. return 0;
  3072. return sysfs_emit_at(buf, len,
  3073. "Node %d HugePages_Total: %5u\n"
  3074. "Node %d HugePages_Free: %5u\n"
  3075. "Node %d HugePages_Surp: %5u\n",
  3076. nid, h->nr_huge_pages_node[nid],
  3077. nid, h->free_huge_pages_node[nid],
  3078. nid, h->surplus_huge_pages_node[nid]);
  3079. }
  3080. void hugetlb_show_meminfo(void)
  3081. {
  3082. struct hstate *h;
  3083. int nid;
  3084. if (!hugepages_supported())
  3085. return;
  3086. for_each_node_state(nid, N_MEMORY)
  3087. for_each_hstate(h)
  3088. pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
  3089. nid,
  3090. h->nr_huge_pages_node[nid],
  3091. h->free_huge_pages_node[nid],
  3092. h->surplus_huge_pages_node[nid],
  3093. 1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
  3094. }
  3095. void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
  3096. {
  3097. seq_printf(m, "HugetlbPages:\t%8lu kB\n",
  3098. atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
  3099. }
  3100. /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
  3101. unsigned long hugetlb_total_pages(void)
  3102. {
  3103. struct hstate *h;
  3104. unsigned long nr_total_pages = 0;
  3105. for_each_hstate(h)
  3106. nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
  3107. return nr_total_pages;
  3108. }
  3109. static int hugetlb_acct_memory(struct hstate *h, long delta)
  3110. {
  3111. int ret = -ENOMEM;
  3112. spin_lock(&hugetlb_lock);
  3113. /*
  3114. * When cpuset is configured, it breaks the strict hugetlb page
  3115. * reservation as the accounting is done on a global variable. Such
  3116. * reservation is completely rubbish in the presence of cpuset because
  3117. * the reservation is not checked against page availability for the
  3118. * current cpuset. Application can still potentially OOM'ed by kernel
  3119. * with lack of free htlb page in cpuset that the task is in.
  3120. * Attempt to enforce strict accounting with cpuset is almost
  3121. * impossible (or too ugly) because cpuset is too fluid that
  3122. * task or memory node can be dynamically moved between cpusets.
  3123. *
  3124. * The change of semantics for shared hugetlb mapping with cpuset is
  3125. * undesirable. However, in order to preserve some of the semantics,
  3126. * we fall back to check against current free page availability as
  3127. * a best attempt and hopefully to minimize the impact of changing
  3128. * semantics that cpuset has.
  3129. *
  3130. * Apart from cpuset, we also have memory policy mechanism that
  3131. * also determines from which node the kernel will allocate memory
  3132. * in a NUMA system. So similar to cpuset, we also should consider
  3133. * the memory policy of the current task. Similar to the description
  3134. * above.
  3135. */
  3136. if (delta > 0) {
  3137. if (gather_surplus_pages(h, delta) < 0)
  3138. goto out;
  3139. if (delta > allowed_mems_nr(h)) {
  3140. return_unused_surplus_pages(h, delta);
  3141. goto out;
  3142. }
  3143. }
  3144. ret = 0;
  3145. if (delta < 0)
  3146. return_unused_surplus_pages(h, (unsigned long) -delta);
  3147. out:
  3148. spin_unlock(&hugetlb_lock);
  3149. return ret;
  3150. }
  3151. static void hugetlb_vm_op_open(struct vm_area_struct *vma)
  3152. {
  3153. struct resv_map *resv = vma_resv_map(vma);
  3154. /*
  3155. * This new VMA should share its siblings reservation map if present.
  3156. * The VMA will only ever have a valid reservation map pointer where
  3157. * it is being copied for another still existing VMA. As that VMA
  3158. * has a reference to the reservation map it cannot disappear until
  3159. * after this open call completes. It is therefore safe to take a
  3160. * new reference here without additional locking.
  3161. */
  3162. if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
  3163. resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
  3164. kref_get(&resv->refs);
  3165. }
  3166. }
  3167. static void hugetlb_vm_op_close(struct vm_area_struct *vma)
  3168. {
  3169. struct hstate *h = hstate_vma(vma);
  3170. struct resv_map *resv = vma_resv_map(vma);
  3171. struct hugepage_subpool *spool = subpool_vma(vma);
  3172. unsigned long reserve, start, end;
  3173. long gbl_reserve;
  3174. if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
  3175. return;
  3176. start = vma_hugecache_offset(h, vma, vma->vm_start);
  3177. end = vma_hugecache_offset(h, vma, vma->vm_end);
  3178. reserve = (end - start) - region_count(resv, start, end);
  3179. hugetlb_cgroup_uncharge_counter(resv, start, end);
  3180. if (reserve) {
  3181. /*
  3182. * Decrement reserve counts. The global reserve count may be
  3183. * adjusted if the subpool has a minimum size.
  3184. */
  3185. gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
  3186. hugetlb_acct_memory(h, -gbl_reserve);
  3187. }
  3188. kref_put(&resv->refs, resv_map_release);
  3189. }
  3190. static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
  3191. {
  3192. if (addr & ~(huge_page_mask(hstate_vma(vma))))
  3193. return -EINVAL;
  3194. return 0;
  3195. }
  3196. static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
  3197. {
  3198. struct hstate *hstate = hstate_vma(vma);
  3199. return 1UL << huge_page_shift(hstate);
  3200. }
  3201. /*
  3202. * We cannot handle pagefaults against hugetlb pages at all. They cause
  3203. * handle_mm_fault() to try to instantiate regular-sized pages in the
  3204. * hugegpage VMA. do_page_fault() is supposed to trap this, so BUG is we get
  3205. * this far.
  3206. */
  3207. static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
  3208. {
  3209. BUG();
  3210. return 0;
  3211. }
  3212. /*
  3213. * When a new function is introduced to vm_operations_struct and added
  3214. * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
  3215. * This is because under System V memory model, mappings created via
  3216. * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
  3217. * their original vm_ops are overwritten with shm_vm_ops.
  3218. */
  3219. const struct vm_operations_struct hugetlb_vm_ops = {
  3220. .fault = hugetlb_vm_op_fault,
  3221. .open = hugetlb_vm_op_open,
  3222. .close = hugetlb_vm_op_close,
  3223. .split = hugetlb_vm_op_split,
  3224. .pagesize = hugetlb_vm_op_pagesize,
  3225. };
  3226. static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
  3227. int writable)
  3228. {
  3229. pte_t entry;
  3230. if (writable) {
  3231. entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
  3232. vma->vm_page_prot)));
  3233. } else {
  3234. entry = huge_pte_wrprotect(mk_huge_pte(page,
  3235. vma->vm_page_prot));
  3236. }
  3237. entry = pte_mkyoung(entry);
  3238. entry = pte_mkhuge(entry);
  3239. entry = arch_make_huge_pte(entry, vma, page, writable);
  3240. return entry;
  3241. }
  3242. static void set_huge_ptep_writable(struct vm_area_struct *vma,
  3243. unsigned long address, pte_t *ptep)
  3244. {
  3245. pte_t entry;
  3246. entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
  3247. if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
  3248. update_mmu_cache(vma, address, ptep);
  3249. }
  3250. bool is_hugetlb_entry_migration(pte_t pte)
  3251. {
  3252. swp_entry_t swp;
  3253. if (huge_pte_none(pte) || pte_present(pte))
  3254. return false;
  3255. swp = pte_to_swp_entry(pte);
  3256. if (is_migration_entry(swp))
  3257. return true;
  3258. else
  3259. return false;
  3260. }
  3261. static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
  3262. {
  3263. swp_entry_t swp;
  3264. if (huge_pte_none(pte) || pte_present(pte))
  3265. return false;
  3266. swp = pte_to_swp_entry(pte);
  3267. if (is_hwpoison_entry(swp))
  3268. return true;
  3269. else
  3270. return false;
  3271. }
  3272. int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
  3273. struct vm_area_struct *vma)
  3274. {
  3275. pte_t *src_pte, *dst_pte, entry, dst_entry;
  3276. struct page *ptepage;
  3277. unsigned long addr;
  3278. int cow;
  3279. struct hstate *h = hstate_vma(vma);
  3280. unsigned long sz = huge_page_size(h);
  3281. struct address_space *mapping = vma->vm_file->f_mapping;
  3282. struct mmu_notifier_range range;
  3283. int ret = 0;
  3284. cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
  3285. if (cow) {
  3286. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, src,
  3287. vma->vm_start,
  3288. vma->vm_end);
  3289. mmu_notifier_invalidate_range_start(&range);
  3290. } else {
  3291. /*
  3292. * For shared mappings i_mmap_rwsem must be held to call
  3293. * huge_pte_alloc, otherwise the returned ptep could go
  3294. * away if part of a shared pmd and another thread calls
  3295. * huge_pmd_unshare.
  3296. */
  3297. i_mmap_lock_read(mapping);
  3298. }
  3299. for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
  3300. spinlock_t *src_ptl, *dst_ptl;
  3301. src_pte = huge_pte_offset(src, addr, sz);
  3302. if (!src_pte)
  3303. continue;
  3304. dst_pte = huge_pte_alloc(dst, vma, addr, sz);
  3305. if (!dst_pte) {
  3306. ret = -ENOMEM;
  3307. break;
  3308. }
  3309. /*
  3310. * If the pagetables are shared don't copy or take references.
  3311. * dst_pte == src_pte is the common case of src/dest sharing.
  3312. *
  3313. * However, src could have 'unshared' and dst shares with
  3314. * another vma. If dst_pte !none, this implies sharing.
  3315. * Check here before taking page table lock, and once again
  3316. * after taking the lock below.
  3317. */
  3318. dst_entry = huge_ptep_get(dst_pte);
  3319. if ((dst_pte == src_pte) || !huge_pte_none(dst_entry))
  3320. continue;
  3321. dst_ptl = huge_pte_lock(h, dst, dst_pte);
  3322. src_ptl = huge_pte_lockptr(h, src, src_pte);
  3323. spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
  3324. entry = huge_ptep_get(src_pte);
  3325. dst_entry = huge_ptep_get(dst_pte);
  3326. if (huge_pte_none(entry) || !huge_pte_none(dst_entry)) {
  3327. /*
  3328. * Skip if src entry none. Also, skip in the
  3329. * unlikely case dst entry !none as this implies
  3330. * sharing with another vma.
  3331. */
  3332. ;
  3333. } else if (unlikely(is_hugetlb_entry_migration(entry) ||
  3334. is_hugetlb_entry_hwpoisoned(entry))) {
  3335. swp_entry_t swp_entry = pte_to_swp_entry(entry);
  3336. if (is_write_migration_entry(swp_entry) && cow) {
  3337. /*
  3338. * COW mappings require pages in both
  3339. * parent and child to be set to read.
  3340. */
  3341. make_migration_entry_read(&swp_entry);
  3342. entry = swp_entry_to_pte(swp_entry);
  3343. set_huge_swap_pte_at(src, addr, src_pte,
  3344. entry, sz);
  3345. }
  3346. set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz);
  3347. } else {
  3348. if (cow) {
  3349. /*
  3350. * No need to notify as we are downgrading page
  3351. * table protection not changing it to point
  3352. * to a new page.
  3353. *
  3354. * See Documentation/vm/mmu_notifier.rst
  3355. */
  3356. huge_ptep_set_wrprotect(src, addr, src_pte);
  3357. }
  3358. entry = huge_ptep_get(src_pte);
  3359. ptepage = pte_page(entry);
  3360. get_page(ptepage);
  3361. page_dup_rmap(ptepage, true);
  3362. set_huge_pte_at(dst, addr, dst_pte, entry);
  3363. hugetlb_count_add(pages_per_huge_page(h), dst);
  3364. }
  3365. spin_unlock(src_ptl);
  3366. spin_unlock(dst_ptl);
  3367. }
  3368. if (cow)
  3369. mmu_notifier_invalidate_range_end(&range);
  3370. else
  3371. i_mmap_unlock_read(mapping);
  3372. return ret;
  3373. }
  3374. void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
  3375. unsigned long start, unsigned long end,
  3376. struct page *ref_page)
  3377. {
  3378. struct mm_struct *mm = vma->vm_mm;
  3379. unsigned long address;
  3380. pte_t *ptep;
  3381. pte_t pte;
  3382. spinlock_t *ptl;
  3383. struct page *page;
  3384. struct hstate *h = hstate_vma(vma);
  3385. unsigned long sz = huge_page_size(h);
  3386. struct mmu_notifier_range range;
  3387. bool force_flush = false;
  3388. WARN_ON(!is_vm_hugetlb_page(vma));
  3389. BUG_ON(start & ~huge_page_mask(h));
  3390. BUG_ON(end & ~huge_page_mask(h));
  3391. /*
  3392. * This is a hugetlb vma, all the pte entries should point
  3393. * to huge page.
  3394. */
  3395. tlb_change_page_size(tlb, sz);
  3396. tlb_start_vma(tlb, vma);
  3397. /*
  3398. * If sharing possible, alert mmu notifiers of worst case.
  3399. */
  3400. mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
  3401. end);
  3402. adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
  3403. mmu_notifier_invalidate_range_start(&range);
  3404. address = start;
  3405. for (; address < end; address += sz) {
  3406. ptep = huge_pte_offset(mm, address, sz);
  3407. if (!ptep)
  3408. continue;
  3409. ptl = huge_pte_lock(h, mm, ptep);
  3410. if (huge_pmd_unshare(mm, vma, &address, ptep)) {
  3411. spin_unlock(ptl);
  3412. tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
  3413. force_flush = true;
  3414. continue;
  3415. }
  3416. pte = huge_ptep_get(ptep);
  3417. if (huge_pte_none(pte)) {
  3418. spin_unlock(ptl);
  3419. continue;
  3420. }
  3421. /*
  3422. * Migrating hugepage or HWPoisoned hugepage is already
  3423. * unmapped and its refcount is dropped, so just clear pte here.
  3424. */
  3425. if (unlikely(!pte_present(pte))) {
  3426. huge_pte_clear(mm, address, ptep, sz);
  3427. spin_unlock(ptl);
  3428. continue;
  3429. }
  3430. page = pte_page(pte);
  3431. /*
  3432. * If a reference page is supplied, it is because a specific
  3433. * page is being unmapped, not a range. Ensure the page we
  3434. * are about to unmap is the actual page of interest.
  3435. */
  3436. if (ref_page) {
  3437. if (page != ref_page) {
  3438. spin_unlock(ptl);
  3439. continue;
  3440. }
  3441. /*
  3442. * Mark the VMA as having unmapped its page so that
  3443. * future faults in this VMA will fail rather than
  3444. * looking like data was lost
  3445. */
  3446. set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
  3447. }
  3448. pte = huge_ptep_get_and_clear(mm, address, ptep);
  3449. tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
  3450. if (huge_pte_dirty(pte))
  3451. set_page_dirty(page);
  3452. hugetlb_count_sub(pages_per_huge_page(h), mm);
  3453. page_remove_rmap(page, true);
  3454. spin_unlock(ptl);
  3455. tlb_remove_page_size(tlb, page, huge_page_size(h));
  3456. /*
  3457. * Bail out after unmapping reference page if supplied
  3458. */
  3459. if (ref_page)
  3460. break;
  3461. }
  3462. mmu_notifier_invalidate_range_end(&range);
  3463. tlb_end_vma(tlb, vma);
  3464. /*
  3465. * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
  3466. * could defer the flush until now, since by holding i_mmap_rwsem we
  3467. * guaranteed that the last refernece would not be dropped. But we must
  3468. * do the flushing before we return, as otherwise i_mmap_rwsem will be
  3469. * dropped and the last reference to the shared PMDs page might be
  3470. * dropped as well.
  3471. *
  3472. * In theory we could defer the freeing of the PMD pages as well, but
  3473. * huge_pmd_unshare() relies on the exact page_count for the PMD page to
  3474. * detect sharing, so we cannot defer the release of the page either.
  3475. * Instead, do flush now.
  3476. */
  3477. if (force_flush)
  3478. tlb_flush_mmu_tlbonly(tlb);
  3479. }
  3480. void __unmap_hugepage_range_final(struct mmu_gather *tlb,
  3481. struct vm_area_struct *vma, unsigned long start,
  3482. unsigned long end, struct page *ref_page)
  3483. {
  3484. __unmap_hugepage_range(tlb, vma, start, end, ref_page);
  3485. /*
  3486. * Clear this flag so that x86's huge_pmd_share page_table_shareable
  3487. * test will fail on a vma being torn down, and not grab a page table
  3488. * on its way out. We're lucky that the flag has such an appropriate
  3489. * name, and can in fact be safely cleared here. We could clear it
  3490. * before the __unmap_hugepage_range above, but all that's necessary
  3491. * is to clear it before releasing the i_mmap_rwsem. This works
  3492. * because in the context this is called, the VMA is about to be
  3493. * destroyed and the i_mmap_rwsem is held.
  3494. */
  3495. vma->vm_flags &= ~VM_MAYSHARE;
  3496. }
  3497. void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
  3498. unsigned long end, struct page *ref_page)
  3499. {
  3500. struct mm_struct *mm;
  3501. struct mmu_gather tlb;
  3502. unsigned long tlb_start = start;
  3503. unsigned long tlb_end = end;
  3504. /*
  3505. * If shared PMDs were possibly used within this vma range, adjust
  3506. * start/end for worst case tlb flushing.
  3507. * Note that we can not be sure if PMDs are shared until we try to
  3508. * unmap pages. However, we want to make sure TLB flushing covers
  3509. * the largest possible range.
  3510. */
  3511. adjust_range_if_pmd_sharing_possible(vma, &tlb_start, &tlb_end);
  3512. mm = vma->vm_mm;
  3513. tlb_gather_mmu(&tlb, mm, tlb_start, tlb_end);
  3514. __unmap_hugepage_range(&tlb, vma, start, end, ref_page);
  3515. tlb_finish_mmu(&tlb, tlb_start, tlb_end);
  3516. }
  3517. /*
  3518. * This is called when the original mapper is failing to COW a MAP_PRIVATE
  3519. * mappping it owns the reserve page for. The intention is to unmap the page
  3520. * from other VMAs and let the children be SIGKILLed if they are faulting the
  3521. * same region.
  3522. */
  3523. static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
  3524. struct page *page, unsigned long address)
  3525. {
  3526. struct hstate *h = hstate_vma(vma);
  3527. struct vm_area_struct *iter_vma;
  3528. struct address_space *mapping;
  3529. pgoff_t pgoff;
  3530. /*
  3531. * vm_pgoff is in PAGE_SIZE units, hence the different calculation
  3532. * from page cache lookup which is in HPAGE_SIZE units.
  3533. */
  3534. address = address & huge_page_mask(h);
  3535. pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
  3536. vma->vm_pgoff;
  3537. mapping = vma->vm_file->f_mapping;
  3538. /*
  3539. * Take the mapping lock for the duration of the table walk. As
  3540. * this mapping should be shared between all the VMAs,
  3541. * __unmap_hugepage_range() is called as the lock is already held
  3542. */
  3543. i_mmap_lock_write(mapping);
  3544. vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
  3545. /* Do not unmap the current VMA */
  3546. if (iter_vma == vma)
  3547. continue;
  3548. /*
  3549. * Shared VMAs have their own reserves and do not affect
  3550. * MAP_PRIVATE accounting but it is possible that a shared
  3551. * VMA is using the same page so check and skip such VMAs.
  3552. */
  3553. if (iter_vma->vm_flags & VM_MAYSHARE)
  3554. continue;
  3555. /*
  3556. * Unmap the page from other VMAs without their own reserves.
  3557. * They get marked to be SIGKILLed if they fault in these
  3558. * areas. This is because a future no-page fault on this VMA
  3559. * could insert a zeroed page instead of the data existing
  3560. * from the time of fork. This would look like data corruption
  3561. */
  3562. if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
  3563. unmap_hugepage_range(iter_vma, address,
  3564. address + huge_page_size(h), page);
  3565. }
  3566. i_mmap_unlock_write(mapping);
  3567. }
  3568. /*
  3569. * Hugetlb_cow() should be called with page lock of the original hugepage held.
  3570. * Called with hugetlb_instantiation_mutex held and pte_page locked so we
  3571. * cannot race with other handlers or page migration.
  3572. * Keep the pte_same checks anyway to make transition from the mutex easier.
  3573. */
  3574. static vm_fault_t hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
  3575. unsigned long address, pte_t *ptep,
  3576. struct page *pagecache_page, spinlock_t *ptl)
  3577. {
  3578. pte_t pte;
  3579. struct hstate *h = hstate_vma(vma);
  3580. struct page *old_page, *new_page;
  3581. int outside_reserve = 0;
  3582. vm_fault_t ret = 0;
  3583. unsigned long haddr = address & huge_page_mask(h);
  3584. struct mmu_notifier_range range;
  3585. pte = huge_ptep_get(ptep);
  3586. old_page = pte_page(pte);
  3587. retry_avoidcopy:
  3588. /* If no-one else is actually using this page, avoid the copy
  3589. * and just make the page writable */
  3590. if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
  3591. page_move_anon_rmap(old_page, vma);
  3592. set_huge_ptep_writable(vma, haddr, ptep);
  3593. return 0;
  3594. }
  3595. /*
  3596. * If the process that created a MAP_PRIVATE mapping is about to
  3597. * perform a COW due to a shared page count, attempt to satisfy
  3598. * the allocation without using the existing reserves. The pagecache
  3599. * page is used to determine if the reserve at this address was
  3600. * consumed or not. If reserves were used, a partial faulted mapping
  3601. * at the time of fork() could consume its reserves on COW instead
  3602. * of the full address range.
  3603. */
  3604. if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
  3605. old_page != pagecache_page)
  3606. outside_reserve = 1;
  3607. get_page(old_page);
  3608. /*
  3609. * Drop page table lock as buddy allocator may be called. It will
  3610. * be acquired again before returning to the caller, as expected.
  3611. */
  3612. spin_unlock(ptl);
  3613. new_page = alloc_huge_page(vma, haddr, outside_reserve);
  3614. if (IS_ERR(new_page)) {
  3615. /*
  3616. * If a process owning a MAP_PRIVATE mapping fails to COW,
  3617. * it is due to references held by a child and an insufficient
  3618. * huge page pool. To guarantee the original mappers
  3619. * reliability, unmap the page from child processes. The child
  3620. * may get SIGKILLed if it later faults.
  3621. */
  3622. if (outside_reserve) {
  3623. struct address_space *mapping = vma->vm_file->f_mapping;
  3624. pgoff_t idx;
  3625. u32 hash;
  3626. put_page(old_page);
  3627. BUG_ON(huge_pte_none(pte));
  3628. /*
  3629. * Drop hugetlb_fault_mutex and i_mmap_rwsem before
  3630. * unmapping. unmapping needs to hold i_mmap_rwsem
  3631. * in write mode. Dropping i_mmap_rwsem in read mode
  3632. * here is OK as COW mappings do not interact with
  3633. * PMD sharing.
  3634. *
  3635. * Reacquire both after unmap operation.
  3636. */
  3637. idx = vma_hugecache_offset(h, vma, haddr);
  3638. hash = hugetlb_fault_mutex_hash(mapping, idx);
  3639. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  3640. i_mmap_unlock_read(mapping);
  3641. unmap_ref_private(mm, vma, old_page, haddr);
  3642. i_mmap_lock_read(mapping);
  3643. mutex_lock(&hugetlb_fault_mutex_table[hash]);
  3644. spin_lock(ptl);
  3645. ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
  3646. if (likely(ptep &&
  3647. pte_same(huge_ptep_get(ptep), pte)))
  3648. goto retry_avoidcopy;
  3649. /*
  3650. * race occurs while re-acquiring page table
  3651. * lock, and our job is done.
  3652. */
  3653. return 0;
  3654. }
  3655. ret = vmf_error(PTR_ERR(new_page));
  3656. goto out_release_old;
  3657. }
  3658. /*
  3659. * When the original hugepage is shared one, it does not have
  3660. * anon_vma prepared.
  3661. */
  3662. if (unlikely(anon_vma_prepare(vma))) {
  3663. ret = VM_FAULT_OOM;
  3664. goto out_release_all;
  3665. }
  3666. copy_user_huge_page(new_page, old_page, address, vma,
  3667. pages_per_huge_page(h));
  3668. __SetPageUptodate(new_page);
  3669. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
  3670. haddr + huge_page_size(h));
  3671. mmu_notifier_invalidate_range_start(&range);
  3672. /*
  3673. * Retake the page table lock to check for racing updates
  3674. * before the page tables are altered
  3675. */
  3676. spin_lock(ptl);
  3677. ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
  3678. if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
  3679. ClearPagePrivate(new_page);
  3680. /* Break COW */
  3681. huge_ptep_clear_flush(vma, haddr, ptep);
  3682. mmu_notifier_invalidate_range(mm, range.start, range.end);
  3683. set_huge_pte_at(mm, haddr, ptep,
  3684. make_huge_pte(vma, new_page, 1));
  3685. page_remove_rmap(old_page, true);
  3686. hugepage_add_new_anon_rmap(new_page, vma, haddr);
  3687. set_page_huge_active(new_page);
  3688. /* Make the old page be freed below */
  3689. new_page = old_page;
  3690. }
  3691. spin_unlock(ptl);
  3692. mmu_notifier_invalidate_range_end(&range);
  3693. out_release_all:
  3694. restore_reserve_on_error(h, vma, haddr, new_page);
  3695. put_page(new_page);
  3696. out_release_old:
  3697. put_page(old_page);
  3698. spin_lock(ptl); /* Caller expects lock to be held */
  3699. return ret;
  3700. }
  3701. /* Return the pagecache page at a given address within a VMA */
  3702. static struct page *hugetlbfs_pagecache_page(struct hstate *h,
  3703. struct vm_area_struct *vma, unsigned long address)
  3704. {
  3705. struct address_space *mapping;
  3706. pgoff_t idx;
  3707. mapping = vma->vm_file->f_mapping;
  3708. idx = vma_hugecache_offset(h, vma, address);
  3709. return find_lock_page(mapping, idx);
  3710. }
  3711. /*
  3712. * Return whether there is a pagecache page to back given address within VMA.
  3713. * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
  3714. */
  3715. static bool hugetlbfs_pagecache_present(struct hstate *h,
  3716. struct vm_area_struct *vma, unsigned long address)
  3717. {
  3718. struct address_space *mapping;
  3719. pgoff_t idx;
  3720. struct page *page;
  3721. mapping = vma->vm_file->f_mapping;
  3722. idx = vma_hugecache_offset(h, vma, address);
  3723. page = find_get_page(mapping, idx);
  3724. if (page)
  3725. put_page(page);
  3726. return page != NULL;
  3727. }
  3728. int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
  3729. pgoff_t idx)
  3730. {
  3731. struct inode *inode = mapping->host;
  3732. struct hstate *h = hstate_inode(inode);
  3733. int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
  3734. if (err)
  3735. return err;
  3736. ClearPagePrivate(page);
  3737. /*
  3738. * set page dirty so that it will not be removed from cache/file
  3739. * by non-hugetlbfs specific code paths.
  3740. */
  3741. set_page_dirty(page);
  3742. spin_lock(&inode->i_lock);
  3743. inode->i_blocks += blocks_per_huge_page(h);
  3744. spin_unlock(&inode->i_lock);
  3745. return 0;
  3746. }
  3747. static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
  3748. struct address_space *mapping,
  3749. pgoff_t idx,
  3750. unsigned int flags,
  3751. unsigned long haddr,
  3752. unsigned long reason)
  3753. {
  3754. vm_fault_t ret;
  3755. u32 hash;
  3756. struct vm_fault vmf = {
  3757. .vma = vma,
  3758. .address = haddr,
  3759. .flags = flags,
  3760. .vma_flags = vma->vm_flags,
  3761. .vma_page_prot = vma->vm_page_prot,
  3762. /*
  3763. * Hard to debug if it ends up being
  3764. * used by a callee that assumes
  3765. * something about the other
  3766. * uninitialized fields... same as in
  3767. * memory.c
  3768. */
  3769. };
  3770. /*
  3771. * hugetlb_fault_mutex and i_mmap_rwsem must be
  3772. * dropped before handling userfault. Reacquire
  3773. * after handling fault to make calling code simpler.
  3774. */
  3775. hash = hugetlb_fault_mutex_hash(mapping, idx);
  3776. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  3777. i_mmap_unlock_read(mapping);
  3778. ret = handle_userfault(&vmf, reason);
  3779. i_mmap_lock_read(mapping);
  3780. mutex_lock(&hugetlb_fault_mutex_table[hash]);
  3781. return ret;
  3782. }
  3783. static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
  3784. struct vm_area_struct *vma,
  3785. struct address_space *mapping, pgoff_t idx,
  3786. unsigned long address, pte_t *ptep, unsigned int flags)
  3787. {
  3788. struct hstate *h = hstate_vma(vma);
  3789. vm_fault_t ret = VM_FAULT_SIGBUS;
  3790. int anon_rmap = 0;
  3791. unsigned long size;
  3792. struct page *page;
  3793. pte_t new_pte;
  3794. spinlock_t *ptl;
  3795. unsigned long haddr = address & huge_page_mask(h);
  3796. bool new_page = false;
  3797. /*
  3798. * Currently, we are forced to kill the process in the event the
  3799. * original mapper has unmapped pages from the child due to a failed
  3800. * COW. Warn that such a situation has occurred as it may not be obvious
  3801. */
  3802. if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
  3803. pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
  3804. current->pid);
  3805. return ret;
  3806. }
  3807. /*
  3808. * We can not race with truncation due to holding i_mmap_rwsem.
  3809. * i_size is modified when holding i_mmap_rwsem, so check here
  3810. * once for faults beyond end of file.
  3811. */
  3812. size = i_size_read(mapping->host) >> huge_page_shift(h);
  3813. if (idx >= size)
  3814. goto out;
  3815. retry:
  3816. page = find_lock_page(mapping, idx);
  3817. if (!page) {
  3818. /* Check for page in userfault range */
  3819. if (userfaultfd_missing(vma)) {
  3820. ret = hugetlb_handle_userfault(vma, mapping, idx,
  3821. flags, haddr,
  3822. VM_UFFD_MISSING);
  3823. goto out;
  3824. }
  3825. page = alloc_huge_page(vma, haddr, 0);
  3826. if (IS_ERR(page)) {
  3827. /*
  3828. * Returning error will result in faulting task being
  3829. * sent SIGBUS. The hugetlb fault mutex prevents two
  3830. * tasks from racing to fault in the same page which
  3831. * could result in false unable to allocate errors.
  3832. * Page migration does not take the fault mutex, but
  3833. * does a clear then write of pte's under page table
  3834. * lock. Page fault code could race with migration,
  3835. * notice the clear pte and try to allocate a page
  3836. * here. Before returning error, get ptl and make
  3837. * sure there really is no pte entry.
  3838. */
  3839. ptl = huge_pte_lock(h, mm, ptep);
  3840. if (!huge_pte_none(huge_ptep_get(ptep))) {
  3841. ret = 0;
  3842. spin_unlock(ptl);
  3843. goto out;
  3844. }
  3845. spin_unlock(ptl);
  3846. ret = vmf_error(PTR_ERR(page));
  3847. goto out;
  3848. }
  3849. clear_huge_page(page, address, pages_per_huge_page(h));
  3850. __SetPageUptodate(page);
  3851. new_page = true;
  3852. if (vma->vm_flags & VM_MAYSHARE) {
  3853. int err = huge_add_to_page_cache(page, mapping, idx);
  3854. if (err) {
  3855. put_page(page);
  3856. if (err == -EEXIST)
  3857. goto retry;
  3858. goto out;
  3859. }
  3860. } else {
  3861. lock_page(page);
  3862. if (unlikely(anon_vma_prepare(vma))) {
  3863. ret = VM_FAULT_OOM;
  3864. goto backout_unlocked;
  3865. }
  3866. anon_rmap = 1;
  3867. }
  3868. } else {
  3869. /*
  3870. * If memory error occurs between mmap() and fault, some process
  3871. * don't have hwpoisoned swap entry for errored virtual address.
  3872. * So we need to block hugepage fault by PG_hwpoison bit check.
  3873. */
  3874. if (unlikely(PageHWPoison(page))) {
  3875. ret = VM_FAULT_HWPOISON_LARGE |
  3876. VM_FAULT_SET_HINDEX(hstate_index(h));
  3877. goto backout_unlocked;
  3878. }
  3879. /* Check for page in userfault range. */
  3880. if (userfaultfd_minor(vma)) {
  3881. unlock_page(page);
  3882. put_page(page);
  3883. ret = hugetlb_handle_userfault(vma, mapping, idx,
  3884. flags, haddr,
  3885. VM_UFFD_MINOR);
  3886. goto out;
  3887. }
  3888. }
  3889. /*
  3890. * If we are going to COW a private mapping later, we examine the
  3891. * pending reservations for this page now. This will ensure that
  3892. * any allocations necessary to record that reservation occur outside
  3893. * the spinlock.
  3894. */
  3895. if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
  3896. if (vma_needs_reservation(h, vma, haddr) < 0) {
  3897. ret = VM_FAULT_OOM;
  3898. goto backout_unlocked;
  3899. }
  3900. /* Just decrements count, does not deallocate */
  3901. vma_end_reservation(h, vma, haddr);
  3902. }
  3903. ptl = huge_pte_lock(h, mm, ptep);
  3904. ret = 0;
  3905. if (!huge_pte_none(huge_ptep_get(ptep)))
  3906. goto backout;
  3907. if (anon_rmap) {
  3908. ClearPagePrivate(page);
  3909. hugepage_add_new_anon_rmap(page, vma, haddr);
  3910. } else
  3911. page_dup_rmap(page, true);
  3912. new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
  3913. && (vma->vm_flags & VM_SHARED)));
  3914. set_huge_pte_at(mm, haddr, ptep, new_pte);
  3915. hugetlb_count_add(pages_per_huge_page(h), mm);
  3916. if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
  3917. /* Optimization, do the COW without a second fault */
  3918. ret = hugetlb_cow(mm, vma, address, ptep, page, ptl);
  3919. }
  3920. spin_unlock(ptl);
  3921. /*
  3922. * Only make newly allocated pages active. Existing pages found
  3923. * in the pagecache could be !page_huge_active() if they have been
  3924. * isolated for migration.
  3925. */
  3926. if (new_page)
  3927. set_page_huge_active(page);
  3928. unlock_page(page);
  3929. out:
  3930. return ret;
  3931. backout:
  3932. spin_unlock(ptl);
  3933. backout_unlocked:
  3934. unlock_page(page);
  3935. restore_reserve_on_error(h, vma, haddr, page);
  3936. put_page(page);
  3937. goto out;
  3938. }
  3939. #ifdef CONFIG_SMP
  3940. u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
  3941. {
  3942. unsigned long key[2];
  3943. u32 hash;
  3944. key[0] = (unsigned long) mapping;
  3945. key[1] = idx;
  3946. hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
  3947. return hash & (num_fault_mutexes - 1);
  3948. }
  3949. #else
  3950. /*
  3951. * For uniprocesor systems we always use a single mutex, so just
  3952. * return 0 and avoid the hashing overhead.
  3953. */
  3954. u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
  3955. {
  3956. return 0;
  3957. }
  3958. #endif
  3959. vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
  3960. unsigned long address, unsigned int flags)
  3961. {
  3962. pte_t *ptep, entry;
  3963. spinlock_t *ptl;
  3964. vm_fault_t ret;
  3965. u32 hash;
  3966. pgoff_t idx;
  3967. struct page *page = NULL;
  3968. struct page *pagecache_page = NULL;
  3969. struct hstate *h = hstate_vma(vma);
  3970. struct address_space *mapping;
  3971. int need_wait_lock = 0;
  3972. unsigned long haddr = address & huge_page_mask(h);
  3973. ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
  3974. if (ptep) {
  3975. /*
  3976. * Since we hold no locks, ptep could be stale. That is
  3977. * OK as we are only making decisions based on content and
  3978. * not actually modifying content here.
  3979. */
  3980. entry = huge_ptep_get(ptep);
  3981. if (unlikely(is_hugetlb_entry_migration(entry))) {
  3982. migration_entry_wait_huge(vma, mm, ptep);
  3983. return 0;
  3984. } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
  3985. return VM_FAULT_HWPOISON_LARGE |
  3986. VM_FAULT_SET_HINDEX(hstate_index(h));
  3987. }
  3988. /*
  3989. * Acquire i_mmap_rwsem before calling huge_pte_alloc and hold
  3990. * until finished with ptep. This serves two purposes:
  3991. * 1) It prevents huge_pmd_unshare from being called elsewhere
  3992. * and making the ptep no longer valid.
  3993. * 2) It synchronizes us with i_size modifications during truncation.
  3994. *
  3995. * ptep could have already be assigned via huge_pte_offset. That
  3996. * is OK, as huge_pte_alloc will return the same value unless
  3997. * something has changed.
  3998. */
  3999. mapping = vma->vm_file->f_mapping;
  4000. i_mmap_lock_read(mapping);
  4001. ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
  4002. if (!ptep) {
  4003. i_mmap_unlock_read(mapping);
  4004. return VM_FAULT_OOM;
  4005. }
  4006. /*
  4007. * Serialize hugepage allocation and instantiation, so that we don't
  4008. * get spurious allocation failures if two CPUs race to instantiate
  4009. * the same page in the page cache.
  4010. */
  4011. idx = vma_hugecache_offset(h, vma, haddr);
  4012. hash = hugetlb_fault_mutex_hash(mapping, idx);
  4013. mutex_lock(&hugetlb_fault_mutex_table[hash]);
  4014. entry = huge_ptep_get(ptep);
  4015. if (huge_pte_none(entry)) {
  4016. ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
  4017. goto out_mutex;
  4018. }
  4019. ret = 0;
  4020. /*
  4021. * entry could be a migration/hwpoison entry at this point, so this
  4022. * check prevents the kernel from going below assuming that we have
  4023. * an active hugepage in pagecache. This goto expects the 2nd page
  4024. * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
  4025. * properly handle it.
  4026. */
  4027. if (!pte_present(entry))
  4028. goto out_mutex;
  4029. /*
  4030. * If we are going to COW the mapping later, we examine the pending
  4031. * reservations for this page now. This will ensure that any
  4032. * allocations necessary to record that reservation occur outside the
  4033. * spinlock. For private mappings, we also lookup the pagecache
  4034. * page now as it is used to determine if a reservation has been
  4035. * consumed.
  4036. */
  4037. if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
  4038. if (vma_needs_reservation(h, vma, haddr) < 0) {
  4039. ret = VM_FAULT_OOM;
  4040. goto out_mutex;
  4041. }
  4042. /* Just decrements count, does not deallocate */
  4043. vma_end_reservation(h, vma, haddr);
  4044. if (!(vma->vm_flags & VM_MAYSHARE))
  4045. pagecache_page = hugetlbfs_pagecache_page(h,
  4046. vma, haddr);
  4047. }
  4048. ptl = huge_pte_lock(h, mm, ptep);
  4049. /* Check for a racing update before calling hugetlb_cow */
  4050. if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
  4051. goto out_ptl;
  4052. /*
  4053. * hugetlb_cow() requires page locks of pte_page(entry) and
  4054. * pagecache_page, so here we need take the former one
  4055. * when page != pagecache_page or !pagecache_page.
  4056. */
  4057. page = pte_page(entry);
  4058. if (page != pagecache_page)
  4059. if (!trylock_page(page)) {
  4060. need_wait_lock = 1;
  4061. goto out_ptl;
  4062. }
  4063. get_page(page);
  4064. if (flags & FAULT_FLAG_WRITE) {
  4065. if (!huge_pte_write(entry)) {
  4066. ret = hugetlb_cow(mm, vma, address, ptep,
  4067. pagecache_page, ptl);
  4068. goto out_put_page;
  4069. }
  4070. entry = huge_pte_mkdirty(entry);
  4071. }
  4072. entry = pte_mkyoung(entry);
  4073. if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
  4074. flags & FAULT_FLAG_WRITE))
  4075. update_mmu_cache(vma, haddr, ptep);
  4076. out_put_page:
  4077. if (page != pagecache_page)
  4078. unlock_page(page);
  4079. put_page(page);
  4080. out_ptl:
  4081. spin_unlock(ptl);
  4082. if (pagecache_page) {
  4083. unlock_page(pagecache_page);
  4084. put_page(pagecache_page);
  4085. }
  4086. out_mutex:
  4087. mutex_unlock(&hugetlb_fault_mutex_table[hash]);
  4088. i_mmap_unlock_read(mapping);
  4089. /*
  4090. * Generally it's safe to hold refcount during waiting page lock. But
  4091. * here we just wait to defer the next page fault to avoid busy loop and
  4092. * the page is not used after unlocked before returning from the current
  4093. * page fault. So we are safe from accessing freed page, even if we wait
  4094. * here without taking refcount.
  4095. */
  4096. if (need_wait_lock)
  4097. wait_on_page_locked(page);
  4098. return ret;
  4099. }
  4100. #ifdef CONFIG_USERFAULTFD
  4101. /*
  4102. * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
  4103. * modifications for huge pages.
  4104. */
  4105. int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
  4106. pte_t *dst_pte,
  4107. struct vm_area_struct *dst_vma,
  4108. unsigned long dst_addr,
  4109. unsigned long src_addr,
  4110. enum mcopy_atomic_mode mode,
  4111. struct page **pagep)
  4112. {
  4113. bool is_continue = (mode == MCOPY_ATOMIC_CONTINUE);
  4114. struct address_space *mapping;
  4115. pgoff_t idx;
  4116. unsigned long size;
  4117. int vm_shared = dst_vma->vm_flags & VM_SHARED;
  4118. struct hstate *h = hstate_vma(dst_vma);
  4119. pte_t _dst_pte;
  4120. spinlock_t *ptl;
  4121. int ret;
  4122. struct page *page;
  4123. int writable;
  4124. mapping = dst_vma->vm_file->f_mapping;
  4125. idx = vma_hugecache_offset(h, dst_vma, dst_addr);
  4126. if (is_continue) {
  4127. ret = -EFAULT;
  4128. page = find_lock_page(mapping, idx);
  4129. if (!page)
  4130. goto out;
  4131. } else if (!*pagep) {
  4132. /* If a page already exists, then it's UFFDIO_COPY for
  4133. * a non-missing case. Return -EEXIST.
  4134. */
  4135. if (vm_shared &&
  4136. hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
  4137. ret = -EEXIST;
  4138. goto out;
  4139. }
  4140. page = alloc_huge_page(dst_vma, dst_addr, 0);
  4141. if (IS_ERR(page)) {
  4142. ret = -ENOMEM;
  4143. goto out;
  4144. }
  4145. ret = copy_huge_page_from_user(page,
  4146. (const void __user *) src_addr,
  4147. pages_per_huge_page(h), false);
  4148. /* fallback to copy_from_user outside mmap_lock */
  4149. if (unlikely(ret)) {
  4150. ret = -ENOENT;
  4151. *pagep = page;
  4152. /* don't free the page */
  4153. goto out;
  4154. }
  4155. } else {
  4156. page = *pagep;
  4157. *pagep = NULL;
  4158. }
  4159. /*
  4160. * The memory barrier inside __SetPageUptodate makes sure that
  4161. * preceding stores to the page contents become visible before
  4162. * the set_pte_at() write.
  4163. */
  4164. __SetPageUptodate(page);
  4165. /* Add shared, newly allocated pages to the page cache. */
  4166. if (vm_shared && !is_continue) {
  4167. size = i_size_read(mapping->host) >> huge_page_shift(h);
  4168. ret = -EFAULT;
  4169. if (idx >= size)
  4170. goto out_release_nounlock;
  4171. /*
  4172. * Serialization between remove_inode_hugepages() and
  4173. * huge_add_to_page_cache() below happens through the
  4174. * hugetlb_fault_mutex_table that here must be hold by
  4175. * the caller.
  4176. */
  4177. ret = huge_add_to_page_cache(page, mapping, idx);
  4178. if (ret)
  4179. goto out_release_nounlock;
  4180. }
  4181. ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
  4182. spin_lock(ptl);
  4183. /*
  4184. * Recheck the i_size after holding PT lock to make sure not
  4185. * to leave any page mapped (as page_mapped()) beyond the end
  4186. * of the i_size (remove_inode_hugepages() is strict about
  4187. * enforcing that). If we bail out here, we'll also leave a
  4188. * page in the radix tree in the vm_shared case beyond the end
  4189. * of the i_size, but remove_inode_hugepages() will take care
  4190. * of it as soon as we drop the hugetlb_fault_mutex_table.
  4191. */
  4192. size = i_size_read(mapping->host) >> huge_page_shift(h);
  4193. ret = -EFAULT;
  4194. if (idx >= size)
  4195. goto out_release_unlock;
  4196. ret = -EEXIST;
  4197. if (!huge_pte_none(huge_ptep_get(dst_pte)))
  4198. goto out_release_unlock;
  4199. if (vm_shared) {
  4200. page_dup_rmap(page, true);
  4201. } else {
  4202. ClearPagePrivate(page);
  4203. hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
  4204. }
  4205. /* For CONTINUE on a non-shared VMA, don't set VM_WRITE for CoW. */
  4206. if (is_continue && !vm_shared)
  4207. writable = 0;
  4208. else
  4209. writable = dst_vma->vm_flags & VM_WRITE;
  4210. _dst_pte = make_huge_pte(dst_vma, page, writable);
  4211. if (writable)
  4212. _dst_pte = huge_pte_mkdirty(_dst_pte);
  4213. _dst_pte = pte_mkyoung(_dst_pte);
  4214. set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
  4215. (void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
  4216. dst_vma->vm_flags & VM_WRITE);
  4217. hugetlb_count_add(pages_per_huge_page(h), dst_mm);
  4218. /* No need to invalidate - it was non-present before */
  4219. update_mmu_cache(dst_vma, dst_addr, dst_pte);
  4220. spin_unlock(ptl);
  4221. if (!is_continue)
  4222. set_page_huge_active(page);
  4223. if (vm_shared || is_continue)
  4224. unlock_page(page);
  4225. ret = 0;
  4226. out:
  4227. return ret;
  4228. out_release_unlock:
  4229. spin_unlock(ptl);
  4230. if (vm_shared || is_continue)
  4231. unlock_page(page);
  4232. out_release_nounlock:
  4233. put_page(page);
  4234. goto out;
  4235. }
  4236. #endif /* CONFIG_USERFAULTFD */
  4237. long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
  4238. struct page **pages, struct vm_area_struct **vmas,
  4239. unsigned long *position, unsigned long *nr_pages,
  4240. long i, unsigned int flags, int *locked)
  4241. {
  4242. unsigned long pfn_offset;
  4243. unsigned long vaddr = *position;
  4244. unsigned long remainder = *nr_pages;
  4245. struct hstate *h = hstate_vma(vma);
  4246. int err = -EFAULT;
  4247. while (vaddr < vma->vm_end && remainder) {
  4248. pte_t *pte;
  4249. spinlock_t *ptl = NULL;
  4250. int absent;
  4251. struct page *page;
  4252. /*
  4253. * If we have a pending SIGKILL, don't keep faulting pages and
  4254. * potentially allocating memory.
  4255. */
  4256. if (fatal_signal_pending(current)) {
  4257. remainder = 0;
  4258. break;
  4259. }
  4260. /*
  4261. * Some archs (sparc64, sh*) have multiple pte_ts to
  4262. * each hugepage. We have to make sure we get the
  4263. * first, for the page indexing below to work.
  4264. *
  4265. * Note that page table lock is not held when pte is null.
  4266. */
  4267. pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
  4268. huge_page_size(h));
  4269. if (pte)
  4270. ptl = huge_pte_lock(h, mm, pte);
  4271. absent = !pte || huge_pte_none(huge_ptep_get(pte));
  4272. /*
  4273. * When coredumping, it suits get_dump_page if we just return
  4274. * an error where there's an empty slot with no huge pagecache
  4275. * to back it. This way, we avoid allocating a hugepage, and
  4276. * the sparse dumpfile avoids allocating disk blocks, but its
  4277. * huge holes still show up with zeroes where they need to be.
  4278. */
  4279. if (absent && (flags & FOLL_DUMP) &&
  4280. !hugetlbfs_pagecache_present(h, vma, vaddr)) {
  4281. if (pte)
  4282. spin_unlock(ptl);
  4283. remainder = 0;
  4284. break;
  4285. }
  4286. /*
  4287. * We need call hugetlb_fault for both hugepages under migration
  4288. * (in which case hugetlb_fault waits for the migration,) and
  4289. * hwpoisoned hugepages (in which case we need to prevent the
  4290. * caller from accessing to them.) In order to do this, we use
  4291. * here is_swap_pte instead of is_hugetlb_entry_migration and
  4292. * is_hugetlb_entry_hwpoisoned. This is because it simply covers
  4293. * both cases, and because we can't follow correct pages
  4294. * directly from any kind of swap entries.
  4295. */
  4296. if (absent || is_swap_pte(huge_ptep_get(pte)) ||
  4297. ((flags & FOLL_WRITE) &&
  4298. !huge_pte_write(huge_ptep_get(pte)))) {
  4299. vm_fault_t ret;
  4300. unsigned int fault_flags = 0;
  4301. if (pte)
  4302. spin_unlock(ptl);
  4303. if (flags & FOLL_WRITE)
  4304. fault_flags |= FAULT_FLAG_WRITE;
  4305. if (locked)
  4306. fault_flags |= FAULT_FLAG_ALLOW_RETRY |
  4307. FAULT_FLAG_KILLABLE;
  4308. if (flags & FOLL_NOWAIT)
  4309. fault_flags |= FAULT_FLAG_ALLOW_RETRY |
  4310. FAULT_FLAG_RETRY_NOWAIT;
  4311. if (flags & FOLL_TRIED) {
  4312. /*
  4313. * Note: FAULT_FLAG_ALLOW_RETRY and
  4314. * FAULT_FLAG_TRIED can co-exist
  4315. */
  4316. fault_flags |= FAULT_FLAG_TRIED;
  4317. }
  4318. ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
  4319. if (ret & VM_FAULT_ERROR) {
  4320. err = vm_fault_to_errno(ret, flags);
  4321. remainder = 0;
  4322. break;
  4323. }
  4324. if (ret & VM_FAULT_RETRY) {
  4325. if (locked &&
  4326. !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
  4327. *locked = 0;
  4328. *nr_pages = 0;
  4329. /*
  4330. * VM_FAULT_RETRY must not return an
  4331. * error, it will return zero
  4332. * instead.
  4333. *
  4334. * No need to update "position" as the
  4335. * caller will not check it after
  4336. * *nr_pages is set to 0.
  4337. */
  4338. return i;
  4339. }
  4340. continue;
  4341. }
  4342. pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
  4343. page = pte_page(huge_ptep_get(pte));
  4344. /*
  4345. * If subpage information not requested, update counters
  4346. * and skip the same_page loop below.
  4347. */
  4348. if (!pages && !vmas && !pfn_offset &&
  4349. (vaddr + huge_page_size(h) < vma->vm_end) &&
  4350. (remainder >= pages_per_huge_page(h))) {
  4351. vaddr += huge_page_size(h);
  4352. remainder -= pages_per_huge_page(h);
  4353. i += pages_per_huge_page(h);
  4354. spin_unlock(ptl);
  4355. continue;
  4356. }
  4357. same_page:
  4358. if (pages) {
  4359. pages[i] = mem_map_offset(page, pfn_offset);
  4360. /*
  4361. * try_grab_page() should always succeed here, because:
  4362. * a) we hold the ptl lock, and b) we've just checked
  4363. * that the huge page is present in the page tables. If
  4364. * the huge page is present, then the tail pages must
  4365. * also be present. The ptl prevents the head page and
  4366. * tail pages from being rearranged in any way. So this
  4367. * page must be available at this point, unless the page
  4368. * refcount overflowed:
  4369. */
  4370. if (WARN_ON_ONCE(!try_grab_page(pages[i], flags))) {
  4371. spin_unlock(ptl);
  4372. remainder = 0;
  4373. err = -ENOMEM;
  4374. break;
  4375. }
  4376. }
  4377. if (vmas)
  4378. vmas[i] = vma;
  4379. vaddr += PAGE_SIZE;
  4380. ++pfn_offset;
  4381. --remainder;
  4382. ++i;
  4383. if (vaddr < vma->vm_end && remainder &&
  4384. pfn_offset < pages_per_huge_page(h)) {
  4385. /*
  4386. * We use pfn_offset to avoid touching the pageframes
  4387. * of this compound page.
  4388. */
  4389. goto same_page;
  4390. }
  4391. spin_unlock(ptl);
  4392. }
  4393. *nr_pages = remainder;
  4394. /*
  4395. * setting position is actually required only if remainder is
  4396. * not zero but it's faster not to add a "if (remainder)"
  4397. * branch.
  4398. */
  4399. *position = vaddr;
  4400. return i ? i : err;
  4401. }
  4402. unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
  4403. unsigned long address, unsigned long end, pgprot_t newprot)
  4404. {
  4405. struct mm_struct *mm = vma->vm_mm;
  4406. unsigned long start = address;
  4407. pte_t *ptep;
  4408. pte_t pte;
  4409. struct hstate *h = hstate_vma(vma);
  4410. unsigned long pages = 0;
  4411. bool shared_pmd = false;
  4412. struct mmu_notifier_range range;
  4413. /*
  4414. * In the case of shared PMDs, the area to flush could be beyond
  4415. * start/end. Set range.start/range.end to cover the maximum possible
  4416. * range if PMD sharing is possible.
  4417. */
  4418. mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
  4419. 0, vma, mm, start, end);
  4420. adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
  4421. BUG_ON(address >= end);
  4422. flush_cache_range(vma, range.start, range.end);
  4423. mmu_notifier_invalidate_range_start(&range);
  4424. i_mmap_lock_write(vma->vm_file->f_mapping);
  4425. for (; address < end; address += huge_page_size(h)) {
  4426. spinlock_t *ptl;
  4427. ptep = huge_pte_offset(mm, address, huge_page_size(h));
  4428. if (!ptep)
  4429. continue;
  4430. ptl = huge_pte_lock(h, mm, ptep);
  4431. if (huge_pmd_unshare(mm, vma, &address, ptep)) {
  4432. pages++;
  4433. spin_unlock(ptl);
  4434. shared_pmd = true;
  4435. continue;
  4436. }
  4437. pte = huge_ptep_get(ptep);
  4438. if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
  4439. spin_unlock(ptl);
  4440. continue;
  4441. }
  4442. if (unlikely(is_hugetlb_entry_migration(pte))) {
  4443. swp_entry_t entry = pte_to_swp_entry(pte);
  4444. if (is_write_migration_entry(entry)) {
  4445. pte_t newpte;
  4446. make_migration_entry_read(&entry);
  4447. newpte = swp_entry_to_pte(entry);
  4448. set_huge_swap_pte_at(mm, address, ptep,
  4449. newpte, huge_page_size(h));
  4450. pages++;
  4451. }
  4452. spin_unlock(ptl);
  4453. continue;
  4454. }
  4455. if (!huge_pte_none(pte)) {
  4456. pte_t old_pte;
  4457. old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
  4458. pte = pte_mkhuge(huge_pte_modify(old_pte, newprot));
  4459. pte = arch_make_huge_pte(pte, vma, NULL, 0);
  4460. huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
  4461. pages++;
  4462. }
  4463. spin_unlock(ptl);
  4464. }
  4465. /*
  4466. * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
  4467. * may have cleared our pud entry and done put_page on the page table:
  4468. * once we release i_mmap_rwsem, another task can do the final put_page
  4469. * and that page table be reused and filled with junk. If we actually
  4470. * did unshare a page of pmds, flush the range corresponding to the pud.
  4471. */
  4472. if (shared_pmd)
  4473. flush_hugetlb_tlb_range(vma, range.start, range.end);
  4474. else
  4475. flush_hugetlb_tlb_range(vma, start, end);
  4476. /*
  4477. * No need to call mmu_notifier_invalidate_range() we are downgrading
  4478. * page table protection not changing it to point to a new page.
  4479. *
  4480. * See Documentation/vm/mmu_notifier.rst
  4481. */
  4482. i_mmap_unlock_write(vma->vm_file->f_mapping);
  4483. mmu_notifier_invalidate_range_end(&range);
  4484. return pages << h->order;
  4485. }
  4486. int hugetlb_reserve_pages(struct inode *inode,
  4487. long from, long to,
  4488. struct vm_area_struct *vma,
  4489. vm_flags_t vm_flags)
  4490. {
  4491. long ret, chg, add = -1;
  4492. struct hstate *h = hstate_inode(inode);
  4493. struct hugepage_subpool *spool = subpool_inode(inode);
  4494. struct resv_map *resv_map;
  4495. struct hugetlb_cgroup *h_cg = NULL;
  4496. long gbl_reserve, regions_needed = 0;
  4497. /* This should never happen */
  4498. if (from > to) {
  4499. VM_WARN(1, "%s called with a negative range\n", __func__);
  4500. return -EINVAL;
  4501. }
  4502. /*
  4503. * Only apply hugepage reservation if asked. At fault time, an
  4504. * attempt will be made for VM_NORESERVE to allocate a page
  4505. * without using reserves
  4506. */
  4507. if (vm_flags & VM_NORESERVE)
  4508. return 0;
  4509. /*
  4510. * Shared mappings base their reservation on the number of pages that
  4511. * are already allocated on behalf of the file. Private mappings need
  4512. * to reserve the full area even if read-only as mprotect() may be
  4513. * called to make the mapping read-write. Assume !vma is a shm mapping
  4514. */
  4515. if (!vma || vma->vm_flags & VM_MAYSHARE) {
  4516. /*
  4517. * resv_map can not be NULL as hugetlb_reserve_pages is only
  4518. * called for inodes for which resv_maps were created (see
  4519. * hugetlbfs_get_inode).
  4520. */
  4521. resv_map = inode_resv_map(inode);
  4522. chg = region_chg(resv_map, from, to, &regions_needed);
  4523. } else {
  4524. /* Private mapping. */
  4525. resv_map = resv_map_alloc();
  4526. if (!resv_map)
  4527. return -ENOMEM;
  4528. chg = to - from;
  4529. set_vma_resv_map(vma, resv_map);
  4530. set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
  4531. }
  4532. if (chg < 0) {
  4533. ret = chg;
  4534. goto out_err;
  4535. }
  4536. ret = hugetlb_cgroup_charge_cgroup_rsvd(
  4537. hstate_index(h), chg * pages_per_huge_page(h), &h_cg);
  4538. if (ret < 0) {
  4539. ret = -ENOMEM;
  4540. goto out_err;
  4541. }
  4542. if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
  4543. /* For private mappings, the hugetlb_cgroup uncharge info hangs
  4544. * of the resv_map.
  4545. */
  4546. resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
  4547. }
  4548. /*
  4549. * There must be enough pages in the subpool for the mapping. If
  4550. * the subpool has a minimum size, there may be some global
  4551. * reservations already in place (gbl_reserve).
  4552. */
  4553. gbl_reserve = hugepage_subpool_get_pages(spool, chg);
  4554. if (gbl_reserve < 0) {
  4555. ret = -ENOSPC;
  4556. goto out_uncharge_cgroup;
  4557. }
  4558. /*
  4559. * Check enough hugepages are available for the reservation.
  4560. * Hand the pages back to the subpool if there are not
  4561. */
  4562. ret = hugetlb_acct_memory(h, gbl_reserve);
  4563. if (ret < 0) {
  4564. goto out_put_pages;
  4565. }
  4566. /*
  4567. * Account for the reservations made. Shared mappings record regions
  4568. * that have reservations as they are shared by multiple VMAs.
  4569. * When the last VMA disappears, the region map says how much
  4570. * the reservation was and the page cache tells how much of
  4571. * the reservation was consumed. Private mappings are per-VMA and
  4572. * only the consumed reservations are tracked. When the VMA
  4573. * disappears, the original reservation is the VMA size and the
  4574. * consumed reservations are stored in the map. Hence, nothing
  4575. * else has to be done for private mappings here
  4576. */
  4577. if (!vma || vma->vm_flags & VM_MAYSHARE) {
  4578. add = region_add(resv_map, from, to, regions_needed, h, h_cg);
  4579. if (unlikely(add < 0)) {
  4580. hugetlb_acct_memory(h, -gbl_reserve);
  4581. ret = add;
  4582. goto out_put_pages;
  4583. } else if (unlikely(chg > add)) {
  4584. /*
  4585. * pages in this range were added to the reserve
  4586. * map between region_chg and region_add. This
  4587. * indicates a race with alloc_huge_page. Adjust
  4588. * the subpool and reserve counts modified above
  4589. * based on the difference.
  4590. */
  4591. long rsv_adjust;
  4592. /*
  4593. * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
  4594. * reference to h_cg->css. See comment below for detail.
  4595. */
  4596. hugetlb_cgroup_uncharge_cgroup_rsvd(
  4597. hstate_index(h),
  4598. (chg - add) * pages_per_huge_page(h), h_cg);
  4599. rsv_adjust = hugepage_subpool_put_pages(spool,
  4600. chg - add);
  4601. hugetlb_acct_memory(h, -rsv_adjust);
  4602. } else if (h_cg) {
  4603. /*
  4604. * The file_regions will hold their own reference to
  4605. * h_cg->css. So we should release the reference held
  4606. * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
  4607. * done.
  4608. */
  4609. hugetlb_cgroup_put_rsvd_cgroup(h_cg);
  4610. }
  4611. }
  4612. return 0;
  4613. out_put_pages:
  4614. /* put back original number of pages, chg */
  4615. (void)hugepage_subpool_put_pages(spool, chg);
  4616. out_uncharge_cgroup:
  4617. hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
  4618. chg * pages_per_huge_page(h), h_cg);
  4619. out_err:
  4620. if (!vma || vma->vm_flags & VM_MAYSHARE)
  4621. /* Only call region_abort if the region_chg succeeded but the
  4622. * region_add failed or didn't run.
  4623. */
  4624. if (chg >= 0 && add < 0)
  4625. region_abort(resv_map, from, to, regions_needed);
  4626. if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
  4627. kref_put(&resv_map->refs, resv_map_release);
  4628. return ret;
  4629. }
  4630. long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
  4631. long freed)
  4632. {
  4633. struct hstate *h = hstate_inode(inode);
  4634. struct resv_map *resv_map = inode_resv_map(inode);
  4635. long chg = 0;
  4636. struct hugepage_subpool *spool = subpool_inode(inode);
  4637. long gbl_reserve;
  4638. /*
  4639. * Since this routine can be called in the evict inode path for all
  4640. * hugetlbfs inodes, resv_map could be NULL.
  4641. */
  4642. if (resv_map) {
  4643. chg = region_del(resv_map, start, end);
  4644. /*
  4645. * region_del() can fail in the rare case where a region
  4646. * must be split and another region descriptor can not be
  4647. * allocated. If end == LONG_MAX, it will not fail.
  4648. */
  4649. if (chg < 0)
  4650. return chg;
  4651. }
  4652. spin_lock(&inode->i_lock);
  4653. inode->i_blocks -= (blocks_per_huge_page(h) * freed);
  4654. spin_unlock(&inode->i_lock);
  4655. /*
  4656. * If the subpool has a minimum size, the number of global
  4657. * reservations to be released may be adjusted.
  4658. */
  4659. gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
  4660. hugetlb_acct_memory(h, -gbl_reserve);
  4661. return 0;
  4662. }
  4663. #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
  4664. static unsigned long page_table_shareable(struct vm_area_struct *svma,
  4665. struct vm_area_struct *vma,
  4666. unsigned long addr, pgoff_t idx)
  4667. {
  4668. unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
  4669. svma->vm_start;
  4670. unsigned long sbase = saddr & PUD_MASK;
  4671. unsigned long s_end = sbase + PUD_SIZE;
  4672. /* Allow segments to share if only one is marked locked */
  4673. unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
  4674. unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
  4675. /*
  4676. * match the virtual addresses, permission and the alignment of the
  4677. * page table page.
  4678. */
  4679. if (pmd_index(addr) != pmd_index(saddr) ||
  4680. vm_flags != svm_flags ||
  4681. sbase < svma->vm_start || svma->vm_end < s_end)
  4682. return 0;
  4683. return saddr;
  4684. }
  4685. static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
  4686. {
  4687. unsigned long base = addr & PUD_MASK;
  4688. unsigned long end = base + PUD_SIZE;
  4689. /*
  4690. * check on proper vm_flags and page table alignment
  4691. */
  4692. if (vma->vm_flags & VM_MAYSHARE && range_in_vma(vma, base, end))
  4693. return true;
  4694. return false;
  4695. }
  4696. bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
  4697. {
  4698. #ifdef CONFIG_USERFAULTFD
  4699. if (uffd_disable_huge_pmd_share(vma))
  4700. return false;
  4701. #endif
  4702. return vma_shareable(vma, addr);
  4703. }
  4704. /*
  4705. * Determine if start,end range within vma could be mapped by shared pmd.
  4706. * If yes, adjust start and end to cover range associated with possible
  4707. * shared pmd mappings.
  4708. */
  4709. void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
  4710. unsigned long *start, unsigned long *end)
  4711. {
  4712. unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
  4713. v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
  4714. /*
  4715. * vma need span at least one aligned PUD size and the start,end range
  4716. * must at least partialy within it.
  4717. */
  4718. if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
  4719. (*end <= v_start) || (*start >= v_end))
  4720. return;
  4721. /* Extend the range to be PUD aligned for a worst case scenario */
  4722. if (*start > v_start)
  4723. *start = ALIGN_DOWN(*start, PUD_SIZE);
  4724. if (*end < v_end)
  4725. *end = ALIGN(*end, PUD_SIZE);
  4726. }
  4727. /*
  4728. * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
  4729. * and returns the corresponding pte. While this is not necessary for the
  4730. * !shared pmd case because we can allocate the pmd later as well, it makes the
  4731. * code much cleaner.
  4732. *
  4733. * This routine must be called with i_mmap_rwsem held in at least read mode if
  4734. * sharing is possible. For hugetlbfs, this prevents removal of any page
  4735. * table entries associated with the address space. This is important as we
  4736. * are setting up sharing based on existing page table entries (mappings).
  4737. *
  4738. * NOTE: This routine is only called from huge_pte_alloc. Some callers of
  4739. * huge_pte_alloc know that sharing is not possible and do not take
  4740. * i_mmap_rwsem as a performance optimization. This is handled by the
  4741. * if !vma_shareable check at the beginning of the routine. i_mmap_rwsem is
  4742. * only required for subsequent processing.
  4743. */
  4744. pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
  4745. unsigned long addr, pud_t *pud)
  4746. {
  4747. struct address_space *mapping = vma->vm_file->f_mapping;
  4748. pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
  4749. vma->vm_pgoff;
  4750. struct vm_area_struct *svma;
  4751. unsigned long saddr;
  4752. pte_t *spte = NULL;
  4753. pte_t *pte;
  4754. spinlock_t *ptl;
  4755. i_mmap_assert_locked(mapping);
  4756. vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
  4757. if (svma == vma)
  4758. continue;
  4759. saddr = page_table_shareable(svma, vma, addr, idx);
  4760. if (saddr) {
  4761. spte = huge_pte_offset(svma->vm_mm, saddr,
  4762. vma_mmu_pagesize(svma));
  4763. if (spte) {
  4764. get_page(virt_to_page(spte));
  4765. break;
  4766. }
  4767. }
  4768. }
  4769. if (!spte)
  4770. goto out;
  4771. ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
  4772. if (pud_none(*pud)) {
  4773. pud_populate(mm, pud,
  4774. (pmd_t *)((unsigned long)spte & PAGE_MASK));
  4775. mm_inc_nr_pmds(mm);
  4776. } else {
  4777. put_page(virt_to_page(spte));
  4778. }
  4779. spin_unlock(ptl);
  4780. out:
  4781. pte = (pte_t *)pmd_alloc(mm, pud, addr);
  4782. return pte;
  4783. }
  4784. /*
  4785. * unmap huge page backed by shared pte.
  4786. *
  4787. * Hugetlb pte page is ref counted at the time of mapping. If pte is shared
  4788. * indicated by page_count > 1, unmap is achieved by clearing pud and
  4789. * decrementing the ref count. If count == 1, the pte page is not shared.
  4790. *
  4791. * Called with page table lock held and i_mmap_rwsem held in write mode.
  4792. *
  4793. * returns: 1 successfully unmapped a shared pte page
  4794. * 0 the underlying pte page is not shared, or it is the last user
  4795. */
  4796. int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
  4797. unsigned long *addr, pte_t *ptep)
  4798. {
  4799. pgd_t *pgd = pgd_offset(mm, *addr);
  4800. p4d_t *p4d = p4d_offset(pgd, *addr);
  4801. pud_t *pud = pud_offset(p4d, *addr);
  4802. i_mmap_assert_write_locked(vma->vm_file->f_mapping);
  4803. BUG_ON(page_count(virt_to_page(ptep)) == 0);
  4804. if (page_count(virt_to_page(ptep)) == 1)
  4805. return 0;
  4806. pud_clear(pud);
  4807. put_page(virt_to_page(ptep));
  4808. mm_dec_nr_pmds(mm);
  4809. *addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE;
  4810. return 1;
  4811. }
  4812. #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
  4813. pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
  4814. unsigned long addr, pud_t *pud)
  4815. {
  4816. return NULL;
  4817. }
  4818. int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
  4819. unsigned long *addr, pte_t *ptep)
  4820. {
  4821. return 0;
  4822. }
  4823. void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
  4824. unsigned long *start, unsigned long *end)
  4825. {
  4826. }
  4827. bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
  4828. {
  4829. return false;
  4830. }
  4831. #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
  4832. #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
  4833. pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
  4834. unsigned long addr, unsigned long sz)
  4835. {
  4836. pgd_t *pgd;
  4837. p4d_t *p4d;
  4838. pud_t *pud;
  4839. pte_t *pte = NULL;
  4840. pgd = pgd_offset(mm, addr);
  4841. p4d = p4d_alloc(mm, pgd, addr);
  4842. if (!p4d)
  4843. return NULL;
  4844. pud = pud_alloc(mm, p4d, addr);
  4845. if (pud) {
  4846. if (sz == PUD_SIZE) {
  4847. pte = (pte_t *)pud;
  4848. } else {
  4849. BUG_ON(sz != PMD_SIZE);
  4850. if (want_pmd_share(vma, addr) && pud_none(*pud))
  4851. pte = huge_pmd_share(mm, vma, addr, pud);
  4852. else
  4853. pte = (pte_t *)pmd_alloc(mm, pud, addr);
  4854. }
  4855. }
  4856. BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
  4857. return pte;
  4858. }
  4859. /*
  4860. * huge_pte_offset() - Walk the page table to resolve the hugepage
  4861. * entry at address @addr
  4862. *
  4863. * Return: Pointer to page table entry (PUD or PMD) for
  4864. * address @addr, or NULL if a !p*d_present() entry is encountered and the
  4865. * size @sz doesn't match the hugepage size at this level of the page
  4866. * table.
  4867. */
  4868. pte_t *huge_pte_offset(struct mm_struct *mm,
  4869. unsigned long addr, unsigned long sz)
  4870. {
  4871. pgd_t *pgd;
  4872. p4d_t *p4d;
  4873. pud_t *pud;
  4874. pmd_t *pmd;
  4875. pgd = pgd_offset(mm, addr);
  4876. if (!pgd_present(*pgd))
  4877. return NULL;
  4878. p4d = p4d_offset(pgd, addr);
  4879. if (!p4d_present(*p4d))
  4880. return NULL;
  4881. pud = pud_offset(p4d, addr);
  4882. if (sz == PUD_SIZE)
  4883. /* must be pud huge, non-present or none */
  4884. return (pte_t *)pud;
  4885. if (!pud_present(*pud))
  4886. return NULL;
  4887. /* must have a valid entry and size to go further */
  4888. pmd = pmd_offset(pud, addr);
  4889. /* must be pmd huge, non-present or none */
  4890. return (pte_t *)pmd;
  4891. }
  4892. #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
  4893. /*
  4894. * These functions are overwritable if your architecture needs its own
  4895. * behavior.
  4896. */
  4897. struct page * __weak
  4898. follow_huge_addr(struct mm_struct *mm, unsigned long address,
  4899. int write)
  4900. {
  4901. return ERR_PTR(-EINVAL);
  4902. }
  4903. struct page * __weak
  4904. follow_huge_pd(struct vm_area_struct *vma,
  4905. unsigned long address, hugepd_t hpd, int flags, int pdshift)
  4906. {
  4907. WARN(1, "hugepd follow called with no support for hugepage directory format\n");
  4908. return NULL;
  4909. }
  4910. struct page * __weak
  4911. follow_huge_pmd(struct mm_struct *mm, unsigned long address,
  4912. pmd_t *pmd, int flags)
  4913. {
  4914. struct page *page = NULL;
  4915. spinlock_t *ptl;
  4916. pte_t pte;
  4917. /* FOLL_GET and FOLL_PIN are mutually exclusive. */
  4918. if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
  4919. (FOLL_PIN | FOLL_GET)))
  4920. return NULL;
  4921. retry:
  4922. ptl = pmd_lockptr(mm, pmd);
  4923. spin_lock(ptl);
  4924. /*
  4925. * make sure that the address range covered by this pmd is not
  4926. * unmapped from other threads.
  4927. */
  4928. if (!pmd_huge(*pmd))
  4929. goto out;
  4930. pte = huge_ptep_get((pte_t *)pmd);
  4931. if (pte_present(pte)) {
  4932. page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
  4933. /*
  4934. * try_grab_page() should always succeed here, because: a) we
  4935. * hold the pmd (ptl) lock, and b) we've just checked that the
  4936. * huge pmd (head) page is present in the page tables. The ptl
  4937. * prevents the head page and tail pages from being rearranged
  4938. * in any way. So this page must be available at this point,
  4939. * unless the page refcount overflowed:
  4940. */
  4941. if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
  4942. page = NULL;
  4943. goto out;
  4944. }
  4945. } else {
  4946. if (is_hugetlb_entry_migration(pte)) {
  4947. spin_unlock(ptl);
  4948. __migration_entry_wait(mm, (pte_t *)pmd, ptl);
  4949. goto retry;
  4950. }
  4951. /*
  4952. * hwpoisoned entry is treated as no_page_table in
  4953. * follow_page_mask().
  4954. */
  4955. }
  4956. out:
  4957. spin_unlock(ptl);
  4958. return page;
  4959. }
  4960. struct page * __weak
  4961. follow_huge_pud(struct mm_struct *mm, unsigned long address,
  4962. pud_t *pud, int flags)
  4963. {
  4964. if (flags & (FOLL_GET | FOLL_PIN))
  4965. return NULL;
  4966. return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
  4967. }
  4968. struct page * __weak
  4969. follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
  4970. {
  4971. if (flags & (FOLL_GET | FOLL_PIN))
  4972. return NULL;
  4973. return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
  4974. }
  4975. bool isolate_huge_page(struct page *page, struct list_head *list)
  4976. {
  4977. bool ret = true;
  4978. spin_lock(&hugetlb_lock);
  4979. if (!PageHeadHuge(page) || !page_huge_active(page) ||
  4980. !get_page_unless_zero(page)) {
  4981. ret = false;
  4982. goto unlock;
  4983. }
  4984. clear_page_huge_active(page);
  4985. list_move_tail(&page->lru, list);
  4986. unlock:
  4987. spin_unlock(&hugetlb_lock);
  4988. return ret;
  4989. }
  4990. void putback_active_hugepage(struct page *page)
  4991. {
  4992. VM_BUG_ON_PAGE(!PageHead(page), page);
  4993. spin_lock(&hugetlb_lock);
  4994. set_page_huge_active(page);
  4995. list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
  4996. spin_unlock(&hugetlb_lock);
  4997. put_page(page);
  4998. }
  4999. void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
  5000. {
  5001. struct hstate *h = page_hstate(oldpage);
  5002. hugetlb_cgroup_migrate(oldpage, newpage);
  5003. set_page_owner_migrate_reason(newpage, reason);
  5004. /*
  5005. * transfer temporary state of the new huge page. This is
  5006. * reverse to other transitions because the newpage is going to
  5007. * be final while the old one will be freed so it takes over
  5008. * the temporary status.
  5009. *
  5010. * Also note that we have to transfer the per-node surplus state
  5011. * here as well otherwise the global surplus count will not match
  5012. * the per-node's.
  5013. */
  5014. if (PageHugeTemporary(newpage)) {
  5015. int old_nid = page_to_nid(oldpage);
  5016. int new_nid = page_to_nid(newpage);
  5017. SetPageHugeTemporary(oldpage);
  5018. ClearPageHugeTemporary(newpage);
  5019. spin_lock(&hugetlb_lock);
  5020. if (h->surplus_huge_pages_node[old_nid]) {
  5021. h->surplus_huge_pages_node[old_nid]--;
  5022. h->surplus_huge_pages_node[new_nid]++;
  5023. }
  5024. spin_unlock(&hugetlb_lock);
  5025. }
  5026. }
  5027. /*
  5028. * This function will unconditionally remove all the shared pmd pgtable entries
  5029. * within the specific vma for a hugetlbfs memory range.
  5030. */
  5031. void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
  5032. {
  5033. struct hstate *h = hstate_vma(vma);
  5034. unsigned long sz = huge_page_size(h);
  5035. struct mm_struct *mm = vma->vm_mm;
  5036. struct mmu_notifier_range range;
  5037. unsigned long address, start, end;
  5038. spinlock_t *ptl;
  5039. pte_t *ptep;
  5040. if (!(vma->vm_flags & VM_MAYSHARE))
  5041. return;
  5042. start = ALIGN(vma->vm_start, PUD_SIZE);
  5043. end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
  5044. if (start >= end)
  5045. return;
  5046. /*
  5047. * No need to call adjust_range_if_pmd_sharing_possible(), because
  5048. * we have already done the PUD_SIZE alignment.
  5049. */
  5050. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
  5051. start, end);
  5052. mmu_notifier_invalidate_range_start(&range);
  5053. i_mmap_lock_write(vma->vm_file->f_mapping);
  5054. for (address = start; address < end; address += PUD_SIZE) {
  5055. unsigned long tmp = address;
  5056. ptep = huge_pte_offset(mm, address, sz);
  5057. if (!ptep)
  5058. continue;
  5059. ptl = huge_pte_lock(h, mm, ptep);
  5060. /* We don't want 'address' to be changed */
  5061. huge_pmd_unshare(mm, vma, &tmp, ptep);
  5062. spin_unlock(ptl);
  5063. }
  5064. flush_hugetlb_tlb_range(vma, start, end);
  5065. i_mmap_unlock_write(vma->vm_file->f_mapping);
  5066. /*
  5067. * No need to call mmu_notifier_invalidate_range(), see
  5068. * Documentation/vm/mmu_notifier.rst.
  5069. */
  5070. mmu_notifier_invalidate_range_end(&range);
  5071. }
  5072. #ifdef CONFIG_CMA
  5073. static bool cma_reserve_called __initdata;
  5074. static int __init cmdline_parse_hugetlb_cma(char *p)
  5075. {
  5076. hugetlb_cma_size = memparse(p, &p);
  5077. return 0;
  5078. }
  5079. early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
  5080. void __init hugetlb_cma_reserve(int order)
  5081. {
  5082. unsigned long size, reserved, per_node;
  5083. int nid;
  5084. cma_reserve_called = true;
  5085. if (!hugetlb_cma_size)
  5086. return;
  5087. if (hugetlb_cma_size < (PAGE_SIZE << order)) {
  5088. pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
  5089. (PAGE_SIZE << order) / SZ_1M);
  5090. return;
  5091. }
  5092. /*
  5093. * If 3 GB area is requested on a machine with 4 numa nodes,
  5094. * let's allocate 1 GB on first three nodes and ignore the last one.
  5095. */
  5096. per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
  5097. pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
  5098. hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
  5099. reserved = 0;
  5100. for_each_node_state(nid, N_ONLINE) {
  5101. int res;
  5102. char name[CMA_MAX_NAME];
  5103. size = min(per_node, hugetlb_cma_size - reserved);
  5104. size = round_up(size, PAGE_SIZE << order);
  5105. snprintf(name, sizeof(name), "hugetlb%d", nid);
  5106. res = cma_declare_contiguous_nid(0, size, 0, PAGE_SIZE << order,
  5107. 0, false, name,
  5108. &hugetlb_cma[nid], nid);
  5109. if (res) {
  5110. pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
  5111. res, nid);
  5112. continue;
  5113. }
  5114. reserved += size;
  5115. pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
  5116. size / SZ_1M, nid);
  5117. if (reserved >= hugetlb_cma_size)
  5118. break;
  5119. }
  5120. }
  5121. void __init hugetlb_cma_check(void)
  5122. {
  5123. if (!hugetlb_cma_size || cma_reserve_called)
  5124. return;
  5125. pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
  5126. }
  5127. #endif /* CONFIG_CMA */