hugetlb.c 215 KB

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