memory.c 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/memory.c
  4. *
  5. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  6. */
  7. /*
  8. * demand-loading started 01.12.91 - seems it is high on the list of
  9. * things wanted, and it should be easy to implement. - Linus
  10. */
  11. /*
  12. * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
  13. * pages started 02.12.91, seems to work. - Linus.
  14. *
  15. * Tested sharing by executing about 30 /bin/sh: under the old kernel it
  16. * would have taken more than the 6M I have free, but it worked well as
  17. * far as I could see.
  18. *
  19. * Also corrected some "invalidate()"s - I wasn't doing enough of them.
  20. */
  21. /*
  22. * Real VM (paging to/from disk) started 18.12.91. Much more work and
  23. * thought has to go into this. Oh, well..
  24. * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why.
  25. * Found it. Everything seems to work now.
  26. * 20.12.91 - Ok, making the swap-device changeable like the root.
  27. */
  28. /*
  29. * 05.04.94 - Multi-page memory management added for v1.1.
  30. * Idea by Alex Bligh (alex@cconcepts.co.uk)
  31. *
  32. * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG
  33. * (Gerhard.Wichert@pdb.siemens.de)
  34. *
  35. * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
  36. */
  37. #include <linux/kernel_stat.h>
  38. #include <linux/mm.h>
  39. #include <linux/mm_inline.h>
  40. #include <linux/sched/mm.h>
  41. #include <linux/sched/coredump.h>
  42. #include <linux/sched/numa_balancing.h>
  43. #include <linux/sched/task.h>
  44. #include <linux/hugetlb.h>
  45. #include <linux/mman.h>
  46. #include <linux/swap.h>
  47. #include <linux/highmem.h>
  48. #include <linux/pagemap.h>
  49. #include <linux/memremap.h>
  50. #include <linux/kmsan.h>
  51. #include <linux/ksm.h>
  52. #include <linux/rmap.h>
  53. #include <linux/export.h>
  54. #include <linux/delayacct.h>
  55. #include <linux/init.h>
  56. #include <linux/pfn_t.h>
  57. #include <linux/writeback.h>
  58. #include <linux/memcontrol.h>
  59. #include <linux/mmu_notifier.h>
  60. #include <linux/swapops.h>
  61. #include <linux/elf.h>
  62. #include <linux/gfp.h>
  63. #include <linux/migrate.h>
  64. #include <linux/string.h>
  65. #include <linux/memory-tiers.h>
  66. #include <linux/debugfs.h>
  67. #include <linux/userfaultfd_k.h>
  68. #include <linux/dax.h>
  69. #include <linux/oom.h>
  70. #include <linux/numa.h>
  71. #include <linux/perf_event.h>
  72. #include <linux/ptrace.h>
  73. #include <linux/vmalloc.h>
  74. #include <linux/sched/sysctl.h>
  75. #include <trace/events/kmem.h>
  76. #include <asm/io.h>
  77. #include <asm/mmu_context.h>
  78. #include <asm/pgalloc.h>
  79. #include <linux/uaccess.h>
  80. #include <asm/tlb.h>
  81. #include <asm/tlbflush.h>
  82. #include "pgalloc-track.h"
  83. #include "internal.h"
  84. #include "swap.h"
  85. #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
  86. #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
  87. #endif
  88. #ifndef CONFIG_NUMA
  89. unsigned long max_mapnr;
  90. EXPORT_SYMBOL(max_mapnr);
  91. struct page *mem_map;
  92. EXPORT_SYMBOL(mem_map);
  93. #endif
  94. static vm_fault_t do_fault(struct vm_fault *vmf);
  95. static vm_fault_t do_anonymous_page(struct vm_fault *vmf);
  96. static bool vmf_pte_changed(struct vm_fault *vmf);
  97. /*
  98. * Return true if the original pte was a uffd-wp pte marker (so the pte was
  99. * wr-protected).
  100. */
  101. static __always_inline bool vmf_orig_pte_uffd_wp(struct vm_fault *vmf)
  102. {
  103. if (!userfaultfd_wp(vmf->vma))
  104. return false;
  105. if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID))
  106. return false;
  107. return pte_marker_uffd_wp(vmf->orig_pte);
  108. }
  109. /*
  110. * A number of key systems in x86 including ioremap() rely on the assumption
  111. * that high_memory defines the upper bound on direct map memory, then end
  112. * of ZONE_NORMAL.
  113. */
  114. void *high_memory;
  115. EXPORT_SYMBOL(high_memory);
  116. /*
  117. * Randomize the address space (stacks, mmaps, brk, etc.).
  118. *
  119. * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
  120. * as ancient (libc5 based) binaries can segfault. )
  121. */
  122. int randomize_va_space __read_mostly =
  123. #ifdef CONFIG_COMPAT_BRK
  124. 1;
  125. #else
  126. 2;
  127. #endif
  128. #ifndef arch_wants_old_prefaulted_pte
  129. static inline bool arch_wants_old_prefaulted_pte(void)
  130. {
  131. /*
  132. * Transitioning a PTE from 'old' to 'young' can be expensive on
  133. * some architectures, even if it's performed in hardware. By
  134. * default, "false" means prefaulted entries will be 'young'.
  135. */
  136. return false;
  137. }
  138. #endif
  139. static int __init disable_randmaps(char *s)
  140. {
  141. randomize_va_space = 0;
  142. return 1;
  143. }
  144. __setup("norandmaps", disable_randmaps);
  145. unsigned long zero_pfn __read_mostly;
  146. EXPORT_SYMBOL(zero_pfn);
  147. unsigned long highest_memmap_pfn __read_mostly;
  148. /*
  149. * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
  150. */
  151. static int __init init_zero_pfn(void)
  152. {
  153. zero_pfn = page_to_pfn(ZERO_PAGE(0));
  154. return 0;
  155. }
  156. early_initcall(init_zero_pfn);
  157. void mm_trace_rss_stat(struct mm_struct *mm, int member)
  158. {
  159. trace_rss_stat(mm, member);
  160. }
  161. /*
  162. * Note: this doesn't free the actual pages themselves. That
  163. * has been handled earlier when unmapping all the memory regions.
  164. */
  165. static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
  166. unsigned long addr)
  167. {
  168. pgtable_t token = pmd_pgtable(*pmd);
  169. pmd_clear(pmd);
  170. pte_free_tlb(tlb, token, addr);
  171. mm_dec_nr_ptes(tlb->mm);
  172. }
  173. static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
  174. unsigned long addr, unsigned long end,
  175. unsigned long floor, unsigned long ceiling)
  176. {
  177. pmd_t *pmd;
  178. unsigned long next;
  179. unsigned long start;
  180. start = addr;
  181. pmd = pmd_offset(pud, addr);
  182. do {
  183. next = pmd_addr_end(addr, end);
  184. if (pmd_none_or_clear_bad(pmd))
  185. continue;
  186. free_pte_range(tlb, pmd, addr);
  187. } while (pmd++, addr = next, addr != end);
  188. start &= PUD_MASK;
  189. if (start < floor)
  190. return;
  191. if (ceiling) {
  192. ceiling &= PUD_MASK;
  193. if (!ceiling)
  194. return;
  195. }
  196. if (end - 1 > ceiling - 1)
  197. return;
  198. pmd = pmd_offset(pud, start);
  199. pud_clear(pud);
  200. pmd_free_tlb(tlb, pmd, start);
  201. mm_dec_nr_pmds(tlb->mm);
  202. }
  203. static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
  204. unsigned long addr, unsigned long end,
  205. unsigned long floor, unsigned long ceiling)
  206. {
  207. pud_t *pud;
  208. unsigned long next;
  209. unsigned long start;
  210. start = addr;
  211. pud = pud_offset(p4d, addr);
  212. do {
  213. next = pud_addr_end(addr, end);
  214. if (pud_none_or_clear_bad(pud))
  215. continue;
  216. free_pmd_range(tlb, pud, addr, next, floor, ceiling);
  217. } while (pud++, addr = next, addr != end);
  218. start &= P4D_MASK;
  219. if (start < floor)
  220. return;
  221. if (ceiling) {
  222. ceiling &= P4D_MASK;
  223. if (!ceiling)
  224. return;
  225. }
  226. if (end - 1 > ceiling - 1)
  227. return;
  228. pud = pud_offset(p4d, start);
  229. p4d_clear(p4d);
  230. pud_free_tlb(tlb, pud, start);
  231. mm_dec_nr_puds(tlb->mm);
  232. }
  233. static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
  234. unsigned long addr, unsigned long end,
  235. unsigned long floor, unsigned long ceiling)
  236. {
  237. p4d_t *p4d;
  238. unsigned long next;
  239. unsigned long start;
  240. start = addr;
  241. p4d = p4d_offset(pgd, addr);
  242. do {
  243. next = p4d_addr_end(addr, end);
  244. if (p4d_none_or_clear_bad(p4d))
  245. continue;
  246. free_pud_range(tlb, p4d, addr, next, floor, ceiling);
  247. } while (p4d++, addr = next, addr != end);
  248. start &= PGDIR_MASK;
  249. if (start < floor)
  250. return;
  251. if (ceiling) {
  252. ceiling &= PGDIR_MASK;
  253. if (!ceiling)
  254. return;
  255. }
  256. if (end - 1 > ceiling - 1)
  257. return;
  258. p4d = p4d_offset(pgd, start);
  259. pgd_clear(pgd);
  260. p4d_free_tlb(tlb, p4d, start);
  261. }
  262. /*
  263. * This function frees user-level page tables of a process.
  264. */
  265. void free_pgd_range(struct mmu_gather *tlb,
  266. unsigned long addr, unsigned long end,
  267. unsigned long floor, unsigned long ceiling)
  268. {
  269. pgd_t *pgd;
  270. unsigned long next;
  271. /*
  272. * The next few lines have given us lots of grief...
  273. *
  274. * Why are we testing PMD* at this top level? Because often
  275. * there will be no work to do at all, and we'd prefer not to
  276. * go all the way down to the bottom just to discover that.
  277. *
  278. * Why all these "- 1"s? Because 0 represents both the bottom
  279. * of the address space and the top of it (using -1 for the
  280. * top wouldn't help much: the masks would do the wrong thing).
  281. * The rule is that addr 0 and floor 0 refer to the bottom of
  282. * the address space, but end 0 and ceiling 0 refer to the top
  283. * Comparisons need to use "end - 1" and "ceiling - 1" (though
  284. * that end 0 case should be mythical).
  285. *
  286. * Wherever addr is brought up or ceiling brought down, we must
  287. * be careful to reject "the opposite 0" before it confuses the
  288. * subsequent tests. But what about where end is brought down
  289. * by PMD_SIZE below? no, end can't go down to 0 there.
  290. *
  291. * Whereas we round start (addr) and ceiling down, by different
  292. * masks at different levels, in order to test whether a table
  293. * now has no other vmas using it, so can be freed, we don't
  294. * bother to round floor or end up - the tests don't need that.
  295. */
  296. addr &= PMD_MASK;
  297. if (addr < floor) {
  298. addr += PMD_SIZE;
  299. if (!addr)
  300. return;
  301. }
  302. if (ceiling) {
  303. ceiling &= PMD_MASK;
  304. if (!ceiling)
  305. return;
  306. }
  307. if (end - 1 > ceiling - 1)
  308. end -= PMD_SIZE;
  309. if (addr > end - 1)
  310. return;
  311. /*
  312. * We add page table cache pages with PAGE_SIZE,
  313. * (see pte_free_tlb()), flush the tlb if we need
  314. */
  315. tlb_change_page_size(tlb, PAGE_SIZE);
  316. pgd = pgd_offset(tlb->mm, addr);
  317. do {
  318. next = pgd_addr_end(addr, end);
  319. if (pgd_none_or_clear_bad(pgd))
  320. continue;
  321. free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
  322. } while (pgd++, addr = next, addr != end);
  323. }
  324. void free_pgtables(struct mmu_gather *tlb, struct ma_state *mas,
  325. struct vm_area_struct *vma, unsigned long floor,
  326. unsigned long ceiling, bool mm_wr_locked)
  327. {
  328. struct unlink_vma_file_batch vb;
  329. do {
  330. unsigned long addr = vma->vm_start;
  331. struct vm_area_struct *next;
  332. /*
  333. * Note: USER_PGTABLES_CEILING may be passed as ceiling and may
  334. * be 0. This will underflow and is okay.
  335. */
  336. next = mas_find(mas, ceiling - 1);
  337. if (unlikely(xa_is_zero(next)))
  338. next = NULL;
  339. /*
  340. * Hide vma from rmap and truncate_pagecache before freeing
  341. * pgtables
  342. */
  343. if (mm_wr_locked)
  344. vma_start_write(vma);
  345. unlink_anon_vmas(vma);
  346. if (is_vm_hugetlb_page(vma)) {
  347. unlink_file_vma(vma);
  348. hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
  349. floor, next ? next->vm_start : ceiling);
  350. } else {
  351. unlink_file_vma_batch_init(&vb);
  352. unlink_file_vma_batch_add(&vb, vma);
  353. /*
  354. * Optimization: gather nearby vmas into one call down
  355. */
  356. while (next && next->vm_start <= vma->vm_end + PMD_SIZE
  357. && !is_vm_hugetlb_page(next)) {
  358. vma = next;
  359. next = mas_find(mas, ceiling - 1);
  360. if (unlikely(xa_is_zero(next)))
  361. next = NULL;
  362. if (mm_wr_locked)
  363. vma_start_write(vma);
  364. unlink_anon_vmas(vma);
  365. unlink_file_vma_batch_add(&vb, vma);
  366. }
  367. unlink_file_vma_batch_final(&vb);
  368. free_pgd_range(tlb, addr, vma->vm_end,
  369. floor, next ? next->vm_start : ceiling);
  370. }
  371. vma = next;
  372. } while (vma);
  373. }
  374. void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte)
  375. {
  376. spinlock_t *ptl = pmd_lock(mm, pmd);
  377. if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
  378. mm_inc_nr_ptes(mm);
  379. /*
  380. * Ensure all pte setup (eg. pte page lock and page clearing) are
  381. * visible before the pte is made visible to other CPUs by being
  382. * put into page tables.
  383. *
  384. * The other side of the story is the pointer chasing in the page
  385. * table walking code (when walking the page table without locking;
  386. * ie. most of the time). Fortunately, these data accesses consist
  387. * of a chain of data-dependent loads, meaning most CPUs (alpha
  388. * being the notable exception) will already guarantee loads are
  389. * seen in-order. See the alpha page table accessors for the
  390. * smp_rmb() barriers in page table walking code.
  391. */
  392. smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
  393. pmd_populate(mm, pmd, *pte);
  394. *pte = NULL;
  395. }
  396. spin_unlock(ptl);
  397. }
  398. int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
  399. {
  400. pgtable_t new = pte_alloc_one(mm);
  401. if (!new)
  402. return -ENOMEM;
  403. pmd_install(mm, pmd, &new);
  404. if (new)
  405. pte_free(mm, new);
  406. return 0;
  407. }
  408. int __pte_alloc_kernel(pmd_t *pmd)
  409. {
  410. pte_t *new = pte_alloc_one_kernel(&init_mm);
  411. if (!new)
  412. return -ENOMEM;
  413. spin_lock(&init_mm.page_table_lock);
  414. if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
  415. smp_wmb(); /* See comment in pmd_install() */
  416. pmd_populate_kernel(&init_mm, pmd, new);
  417. new = NULL;
  418. }
  419. spin_unlock(&init_mm.page_table_lock);
  420. if (new)
  421. pte_free_kernel(&init_mm, new);
  422. return 0;
  423. }
  424. static inline void init_rss_vec(int *rss)
  425. {
  426. memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
  427. }
  428. static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
  429. {
  430. int i;
  431. for (i = 0; i < NR_MM_COUNTERS; i++)
  432. if (rss[i])
  433. add_mm_counter(mm, i, rss[i]);
  434. }
  435. /*
  436. * This function is called to print an error when a bad pte
  437. * is found. For example, we might have a PFN-mapped pte in
  438. * a region that doesn't allow it.
  439. *
  440. * The calling function must still handle the error.
  441. */
  442. static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
  443. pte_t pte, struct page *page)
  444. {
  445. pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
  446. p4d_t *p4d = p4d_offset(pgd, addr);
  447. pud_t *pud = pud_offset(p4d, addr);
  448. pmd_t *pmd = pmd_offset(pud, addr);
  449. struct address_space *mapping;
  450. pgoff_t index;
  451. static unsigned long resume;
  452. static unsigned long nr_shown;
  453. static unsigned long nr_unshown;
  454. /*
  455. * Allow a burst of 60 reports, then keep quiet for that minute;
  456. * or allow a steady drip of one report per second.
  457. */
  458. if (nr_shown == 60) {
  459. if (time_before(jiffies, resume)) {
  460. nr_unshown++;
  461. return;
  462. }
  463. if (nr_unshown) {
  464. pr_alert("BUG: Bad page map: %lu messages suppressed\n",
  465. nr_unshown);
  466. nr_unshown = 0;
  467. }
  468. nr_shown = 0;
  469. }
  470. if (nr_shown++ == 0)
  471. resume = jiffies + 60 * HZ;
  472. mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
  473. index = linear_page_index(vma, addr);
  474. pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
  475. current->comm,
  476. (long long)pte_val(pte), (long long)pmd_val(*pmd));
  477. if (page)
  478. dump_page(page, "bad pte");
  479. pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
  480. (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
  481. pr_alert("file:%pD fault:%ps mmap:%ps read_folio:%ps\n",
  482. vma->vm_file,
  483. vma->vm_ops ? vma->vm_ops->fault : NULL,
  484. vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
  485. mapping ? mapping->a_ops->read_folio : NULL);
  486. dump_stack();
  487. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  488. }
  489. /*
  490. * vm_normal_page -- This function gets the "struct page" associated with a pte.
  491. *
  492. * "Special" mappings do not wish to be associated with a "struct page" (either
  493. * it doesn't exist, or it exists but they don't want to touch it). In this
  494. * case, NULL is returned here. "Normal" mappings do have a struct page.
  495. *
  496. * There are 2 broad cases. Firstly, an architecture may define a pte_special()
  497. * pte bit, in which case this function is trivial. Secondly, an architecture
  498. * may not have a spare pte bit, which requires a more complicated scheme,
  499. * described below.
  500. *
  501. * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
  502. * special mapping (even if there are underlying and valid "struct pages").
  503. * COWed pages of a VM_PFNMAP are always normal.
  504. *
  505. * The way we recognize COWed pages within VM_PFNMAP mappings is through the
  506. * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
  507. * set, and the vm_pgoff will point to the first PFN mapped: thus every special
  508. * mapping will always honor the rule
  509. *
  510. * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
  511. *
  512. * And for normal mappings this is false.
  513. *
  514. * This restricts such mappings to be a linear translation from virtual address
  515. * to pfn. To get around this restriction, we allow arbitrary mappings so long
  516. * as the vma is not a COW mapping; in that case, we know that all ptes are
  517. * special (because none can have been COWed).
  518. *
  519. *
  520. * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
  521. *
  522. * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
  523. * page" backing, however the difference is that _all_ pages with a struct
  524. * page (that is, those where pfn_valid is true) are refcounted and considered
  525. * normal pages by the VM. The only exception are zeropages, which are
  526. * *never* refcounted.
  527. *
  528. * The disadvantage is that pages are refcounted (which can be slower and
  529. * simply not an option for some PFNMAP users). The advantage is that we
  530. * don't have to follow the strict linearity rule of PFNMAP mappings in
  531. * order to support COWable mappings.
  532. *
  533. */
  534. struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
  535. pte_t pte)
  536. {
  537. unsigned long pfn = pte_pfn(pte);
  538. if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
  539. if (likely(!pte_special(pte)))
  540. goto check_pfn;
  541. if (vma->vm_ops && vma->vm_ops->find_special_page)
  542. return vma->vm_ops->find_special_page(vma, addr);
  543. if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
  544. return NULL;
  545. if (is_zero_pfn(pfn))
  546. return NULL;
  547. if (pte_devmap(pte))
  548. /*
  549. * NOTE: New users of ZONE_DEVICE will not set pte_devmap()
  550. * and will have refcounts incremented on their struct pages
  551. * when they are inserted into PTEs, thus they are safe to
  552. * return here. Legacy ZONE_DEVICE pages that set pte_devmap()
  553. * do not have refcounts. Example of legacy ZONE_DEVICE is
  554. * MEMORY_DEVICE_FS_DAX type in pmem or virtio_fs drivers.
  555. */
  556. return NULL;
  557. print_bad_pte(vma, addr, pte, NULL);
  558. return NULL;
  559. }
  560. /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
  561. if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
  562. if (vma->vm_flags & VM_MIXEDMAP) {
  563. if (!pfn_valid(pfn))
  564. return NULL;
  565. if (is_zero_pfn(pfn))
  566. return NULL;
  567. goto out;
  568. } else {
  569. unsigned long off;
  570. off = (addr - vma->vm_start) >> PAGE_SHIFT;
  571. if (pfn == vma->vm_pgoff + off)
  572. return NULL;
  573. if (!is_cow_mapping(vma->vm_flags))
  574. return NULL;
  575. }
  576. }
  577. if (is_zero_pfn(pfn))
  578. return NULL;
  579. check_pfn:
  580. if (unlikely(pfn > highest_memmap_pfn)) {
  581. print_bad_pte(vma, addr, pte, NULL);
  582. return NULL;
  583. }
  584. /*
  585. * NOTE! We still have PageReserved() pages in the page tables.
  586. * eg. VDSO mappings can cause them to exist.
  587. */
  588. out:
  589. VM_WARN_ON_ONCE(is_zero_pfn(pfn));
  590. return pfn_to_page(pfn);
  591. }
  592. struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr,
  593. pte_t pte)
  594. {
  595. struct page *page = vm_normal_page(vma, addr, pte);
  596. if (page)
  597. return page_folio(page);
  598. return NULL;
  599. }
  600. #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
  601. struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
  602. pmd_t pmd)
  603. {
  604. unsigned long pfn = pmd_pfn(pmd);
  605. /* Currently it's only used for huge pfnmaps */
  606. if (unlikely(pmd_special(pmd)))
  607. return NULL;
  608. if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
  609. if (vma->vm_flags & VM_MIXEDMAP) {
  610. if (!pfn_valid(pfn))
  611. return NULL;
  612. goto out;
  613. } else {
  614. unsigned long off;
  615. off = (addr - vma->vm_start) >> PAGE_SHIFT;
  616. if (pfn == vma->vm_pgoff + off)
  617. return NULL;
  618. if (!is_cow_mapping(vma->vm_flags))
  619. return NULL;
  620. }
  621. }
  622. if (pmd_devmap(pmd))
  623. return NULL;
  624. if (is_huge_zero_pmd(pmd))
  625. return NULL;
  626. if (unlikely(pfn > highest_memmap_pfn))
  627. return NULL;
  628. /*
  629. * NOTE! We still have PageReserved() pages in the page tables.
  630. * eg. VDSO mappings can cause them to exist.
  631. */
  632. out:
  633. return pfn_to_page(pfn);
  634. }
  635. struct folio *vm_normal_folio_pmd(struct vm_area_struct *vma,
  636. unsigned long addr, pmd_t pmd)
  637. {
  638. struct page *page = vm_normal_page_pmd(vma, addr, pmd);
  639. if (page)
  640. return page_folio(page);
  641. return NULL;
  642. }
  643. #endif
  644. static void restore_exclusive_pte(struct vm_area_struct *vma,
  645. struct page *page, unsigned long address,
  646. pte_t *ptep)
  647. {
  648. struct folio *folio = page_folio(page);
  649. pte_t orig_pte;
  650. pte_t pte;
  651. swp_entry_t entry;
  652. orig_pte = ptep_get(ptep);
  653. pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
  654. if (pte_swp_soft_dirty(orig_pte))
  655. pte = pte_mksoft_dirty(pte);
  656. entry = pte_to_swp_entry(orig_pte);
  657. if (pte_swp_uffd_wp(orig_pte))
  658. pte = pte_mkuffd_wp(pte);
  659. else if (is_writable_device_exclusive_entry(entry))
  660. pte = maybe_mkwrite(pte_mkdirty(pte), vma);
  661. VM_BUG_ON_FOLIO(pte_write(pte) && (!folio_test_anon(folio) &&
  662. PageAnonExclusive(page)), folio);
  663. /*
  664. * No need to take a page reference as one was already
  665. * created when the swap entry was made.
  666. */
  667. if (folio_test_anon(folio))
  668. folio_add_anon_rmap_pte(folio, page, vma, address, RMAP_NONE);
  669. else
  670. /*
  671. * Currently device exclusive access only supports anonymous
  672. * memory so the entry shouldn't point to a filebacked page.
  673. */
  674. WARN_ON_ONCE(1);
  675. set_pte_at(vma->vm_mm, address, ptep, pte);
  676. /*
  677. * No need to invalidate - it was non-present before. However
  678. * secondary CPUs may have mappings that need invalidating.
  679. */
  680. update_mmu_cache(vma, address, ptep);
  681. }
  682. /*
  683. * Tries to restore an exclusive pte if the page lock can be acquired without
  684. * sleeping.
  685. */
  686. static int
  687. try_restore_exclusive_pte(pte_t *src_pte, struct vm_area_struct *vma,
  688. unsigned long addr)
  689. {
  690. swp_entry_t entry = pte_to_swp_entry(ptep_get(src_pte));
  691. struct page *page = pfn_swap_entry_to_page(entry);
  692. if (trylock_page(page)) {
  693. restore_exclusive_pte(vma, page, addr, src_pte);
  694. unlock_page(page);
  695. return 0;
  696. }
  697. return -EBUSY;
  698. }
  699. /*
  700. * copy one vm_area from one task to the other. Assumes the page tables
  701. * already present in the new task to be cleared in the whole range
  702. * covered by this vma.
  703. */
  704. static unsigned long
  705. copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
  706. pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
  707. struct vm_area_struct *src_vma, unsigned long addr, int *rss)
  708. {
  709. unsigned long vm_flags = dst_vma->vm_flags;
  710. pte_t orig_pte = ptep_get(src_pte);
  711. pte_t pte = orig_pte;
  712. struct folio *folio;
  713. struct page *page;
  714. swp_entry_t entry = pte_to_swp_entry(orig_pte);
  715. if (likely(!non_swap_entry(entry))) {
  716. if (swap_duplicate(entry) < 0)
  717. return -EIO;
  718. /* make sure dst_mm is on swapoff's mmlist. */
  719. if (unlikely(list_empty(&dst_mm->mmlist))) {
  720. spin_lock(&mmlist_lock);
  721. if (list_empty(&dst_mm->mmlist))
  722. list_add(&dst_mm->mmlist,
  723. &src_mm->mmlist);
  724. spin_unlock(&mmlist_lock);
  725. }
  726. /* Mark the swap entry as shared. */
  727. if (pte_swp_exclusive(orig_pte)) {
  728. pte = pte_swp_clear_exclusive(orig_pte);
  729. set_pte_at(src_mm, addr, src_pte, pte);
  730. }
  731. rss[MM_SWAPENTS]++;
  732. } else if (is_migration_entry(entry)) {
  733. folio = pfn_swap_entry_folio(entry);
  734. rss[mm_counter(folio)]++;
  735. if (!is_readable_migration_entry(entry) &&
  736. is_cow_mapping(vm_flags)) {
  737. /*
  738. * COW mappings require pages in both parent and child
  739. * to be set to read. A previously exclusive entry is
  740. * now shared.
  741. */
  742. entry = make_readable_migration_entry(
  743. swp_offset(entry));
  744. pte = swp_entry_to_pte(entry);
  745. if (pte_swp_soft_dirty(orig_pte))
  746. pte = pte_swp_mksoft_dirty(pte);
  747. if (pte_swp_uffd_wp(orig_pte))
  748. pte = pte_swp_mkuffd_wp(pte);
  749. set_pte_at(src_mm, addr, src_pte, pte);
  750. }
  751. } else if (is_device_private_entry(entry)) {
  752. page = pfn_swap_entry_to_page(entry);
  753. folio = page_folio(page);
  754. /*
  755. * Update rss count even for unaddressable pages, as
  756. * they should treated just like normal pages in this
  757. * respect.
  758. *
  759. * We will likely want to have some new rss counters
  760. * for unaddressable pages, at some point. But for now
  761. * keep things as they are.
  762. */
  763. folio_get(folio);
  764. rss[mm_counter(folio)]++;
  765. /* Cannot fail as these pages cannot get pinned. */
  766. folio_try_dup_anon_rmap_pte(folio, page, src_vma);
  767. /*
  768. * We do not preserve soft-dirty information, because so
  769. * far, checkpoint/restore is the only feature that
  770. * requires that. And checkpoint/restore does not work
  771. * when a device driver is involved (you cannot easily
  772. * save and restore device driver state).
  773. */
  774. if (is_writable_device_private_entry(entry) &&
  775. is_cow_mapping(vm_flags)) {
  776. entry = make_readable_device_private_entry(
  777. swp_offset(entry));
  778. pte = swp_entry_to_pte(entry);
  779. if (pte_swp_uffd_wp(orig_pte))
  780. pte = pte_swp_mkuffd_wp(pte);
  781. set_pte_at(src_mm, addr, src_pte, pte);
  782. }
  783. } else if (is_device_exclusive_entry(entry)) {
  784. /*
  785. * Make device exclusive entries present by restoring the
  786. * original entry then copying as for a present pte. Device
  787. * exclusive entries currently only support private writable
  788. * (ie. COW) mappings.
  789. */
  790. VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags));
  791. if (try_restore_exclusive_pte(src_pte, src_vma, addr))
  792. return -EBUSY;
  793. return -ENOENT;
  794. } else if (is_pte_marker_entry(entry)) {
  795. pte_marker marker = copy_pte_marker(entry, dst_vma);
  796. if (marker)
  797. set_pte_at(dst_mm, addr, dst_pte,
  798. make_pte_marker(marker));
  799. return 0;
  800. }
  801. if (!userfaultfd_wp(dst_vma))
  802. pte = pte_swp_clear_uffd_wp(pte);
  803. set_pte_at(dst_mm, addr, dst_pte, pte);
  804. return 0;
  805. }
  806. /*
  807. * Copy a present and normal page.
  808. *
  809. * NOTE! The usual case is that this isn't required;
  810. * instead, the caller can just increase the page refcount
  811. * and re-use the pte the traditional way.
  812. *
  813. * And if we need a pre-allocated page but don't yet have
  814. * one, return a negative error to let the preallocation
  815. * code know so that it can do so outside the page table
  816. * lock.
  817. */
  818. static inline int
  819. copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  820. pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
  821. struct folio **prealloc, struct page *page)
  822. {
  823. struct folio *new_folio;
  824. pte_t pte;
  825. new_folio = *prealloc;
  826. if (!new_folio)
  827. return -EAGAIN;
  828. /*
  829. * We have a prealloc page, all good! Take it
  830. * over and copy the page & arm it.
  831. */
  832. if (copy_mc_user_highpage(&new_folio->page, page, addr, src_vma))
  833. return -EHWPOISON;
  834. *prealloc = NULL;
  835. __folio_mark_uptodate(new_folio);
  836. folio_add_new_anon_rmap(new_folio, dst_vma, addr, RMAP_EXCLUSIVE);
  837. folio_add_lru_vma(new_folio, dst_vma);
  838. rss[MM_ANONPAGES]++;
  839. /* All done, just insert the new page copy in the child */
  840. pte = mk_pte(&new_folio->page, dst_vma->vm_page_prot);
  841. pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
  842. if (userfaultfd_pte_wp(dst_vma, ptep_get(src_pte)))
  843. /* Uffd-wp needs to be delivered to dest pte as well */
  844. pte = pte_mkuffd_wp(pte);
  845. set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
  846. return 0;
  847. }
  848. static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma,
  849. struct vm_area_struct *src_vma, pte_t *dst_pte, pte_t *src_pte,
  850. pte_t pte, unsigned long addr, int nr)
  851. {
  852. struct mm_struct *src_mm = src_vma->vm_mm;
  853. /* If it's a COW mapping, write protect it both processes. */
  854. if (is_cow_mapping(src_vma->vm_flags) && pte_write(pte)) {
  855. wrprotect_ptes(src_mm, addr, src_pte, nr);
  856. pte = pte_wrprotect(pte);
  857. }
  858. /* If it's a shared mapping, mark it clean in the child. */
  859. if (src_vma->vm_flags & VM_SHARED)
  860. pte = pte_mkclean(pte);
  861. pte = pte_mkold(pte);
  862. if (!userfaultfd_wp(dst_vma))
  863. pte = pte_clear_uffd_wp(pte);
  864. set_ptes(dst_vma->vm_mm, addr, dst_pte, pte, nr);
  865. }
  866. /*
  867. * Copy one present PTE, trying to batch-process subsequent PTEs that map
  868. * consecutive pages of the same folio by copying them as well.
  869. *
  870. * Returns -EAGAIN if one preallocated page is required to copy the next PTE.
  871. * Otherwise, returns the number of copied PTEs (at least 1).
  872. */
  873. static inline int
  874. copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  875. pte_t *dst_pte, pte_t *src_pte, pte_t pte, unsigned long addr,
  876. int max_nr, int *rss, struct folio **prealloc)
  877. {
  878. struct page *page;
  879. struct folio *folio;
  880. bool any_writable;
  881. fpb_t flags = 0;
  882. int err, nr;
  883. page = vm_normal_page(src_vma, addr, pte);
  884. if (unlikely(!page))
  885. goto copy_pte;
  886. folio = page_folio(page);
  887. /*
  888. * If we likely have to copy, just don't bother with batching. Make
  889. * sure that the common "small folio" case is as fast as possible
  890. * by keeping the batching logic separate.
  891. */
  892. if (unlikely(!*prealloc && folio_test_large(folio) && max_nr != 1)) {
  893. if (src_vma->vm_flags & VM_SHARED)
  894. flags |= FPB_IGNORE_DIRTY;
  895. if (!vma_soft_dirty_enabled(src_vma))
  896. flags |= FPB_IGNORE_SOFT_DIRTY;
  897. nr = folio_pte_batch(folio, addr, src_pte, pte, max_nr, flags,
  898. &any_writable, NULL, NULL);
  899. folio_ref_add(folio, nr);
  900. if (folio_test_anon(folio)) {
  901. if (unlikely(folio_try_dup_anon_rmap_ptes(folio, page,
  902. nr, src_vma))) {
  903. folio_ref_sub(folio, nr);
  904. return -EAGAIN;
  905. }
  906. rss[MM_ANONPAGES] += nr;
  907. VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
  908. } else {
  909. folio_dup_file_rmap_ptes(folio, page, nr);
  910. rss[mm_counter_file(folio)] += nr;
  911. }
  912. if (any_writable)
  913. pte = pte_mkwrite(pte, src_vma);
  914. __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte,
  915. addr, nr);
  916. return nr;
  917. }
  918. folio_get(folio);
  919. if (folio_test_anon(folio)) {
  920. /*
  921. * If this page may have been pinned by the parent process,
  922. * copy the page immediately for the child so that we'll always
  923. * guarantee the pinned page won't be randomly replaced in the
  924. * future.
  925. */
  926. if (unlikely(folio_try_dup_anon_rmap_pte(folio, page, src_vma))) {
  927. /* Page may be pinned, we have to copy. */
  928. folio_put(folio);
  929. err = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
  930. addr, rss, prealloc, page);
  931. return err ? err : 1;
  932. }
  933. rss[MM_ANONPAGES]++;
  934. VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
  935. } else {
  936. folio_dup_file_rmap_pte(folio, page);
  937. rss[mm_counter_file(folio)]++;
  938. }
  939. copy_pte:
  940. __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte, addr, 1);
  941. return 1;
  942. }
  943. static inline struct folio *folio_prealloc(struct mm_struct *src_mm,
  944. struct vm_area_struct *vma, unsigned long addr, bool need_zero)
  945. {
  946. struct folio *new_folio;
  947. if (need_zero)
  948. new_folio = vma_alloc_zeroed_movable_folio(vma, addr);
  949. else
  950. new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma,
  951. addr, false);
  952. if (!new_folio)
  953. return NULL;
  954. if (mem_cgroup_charge(new_folio, src_mm, GFP_KERNEL)) {
  955. folio_put(new_folio);
  956. return NULL;
  957. }
  958. folio_throttle_swaprate(new_folio, GFP_KERNEL);
  959. return new_folio;
  960. }
  961. static int
  962. copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  963. pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
  964. unsigned long end)
  965. {
  966. struct mm_struct *dst_mm = dst_vma->vm_mm;
  967. struct mm_struct *src_mm = src_vma->vm_mm;
  968. pte_t *orig_src_pte, *orig_dst_pte;
  969. pte_t *src_pte, *dst_pte;
  970. pte_t ptent;
  971. spinlock_t *src_ptl, *dst_ptl;
  972. int progress, max_nr, ret = 0;
  973. int rss[NR_MM_COUNTERS];
  974. swp_entry_t entry = (swp_entry_t){0};
  975. struct folio *prealloc = NULL;
  976. int nr;
  977. again:
  978. progress = 0;
  979. init_rss_vec(rss);
  980. /*
  981. * copy_pmd_range()'s prior pmd_none_or_clear_bad(src_pmd), and the
  982. * error handling here, assume that exclusive mmap_lock on dst and src
  983. * protects anon from unexpected THP transitions; with shmem and file
  984. * protected by mmap_lock-less collapse skipping areas with anon_vma
  985. * (whereas vma_needs_copy() skips areas without anon_vma). A rework
  986. * can remove such assumptions later, but this is good enough for now.
  987. */
  988. dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
  989. if (!dst_pte) {
  990. ret = -ENOMEM;
  991. goto out;
  992. }
  993. src_pte = pte_offset_map_nolock(src_mm, src_pmd, addr, &src_ptl);
  994. if (!src_pte) {
  995. pte_unmap_unlock(dst_pte, dst_ptl);
  996. /* ret == 0 */
  997. goto out;
  998. }
  999. spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
  1000. orig_src_pte = src_pte;
  1001. orig_dst_pte = dst_pte;
  1002. arch_enter_lazy_mmu_mode();
  1003. do {
  1004. nr = 1;
  1005. /*
  1006. * We are holding two locks at this point - either of them
  1007. * could generate latencies in another task on another CPU.
  1008. */
  1009. if (progress >= 32) {
  1010. progress = 0;
  1011. if (need_resched() ||
  1012. spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
  1013. break;
  1014. }
  1015. ptent = ptep_get(src_pte);
  1016. if (pte_none(ptent)) {
  1017. progress++;
  1018. continue;
  1019. }
  1020. if (unlikely(!pte_present(ptent))) {
  1021. ret = copy_nonpresent_pte(dst_mm, src_mm,
  1022. dst_pte, src_pte,
  1023. dst_vma, src_vma,
  1024. addr, rss);
  1025. if (ret == -EIO) {
  1026. entry = pte_to_swp_entry(ptep_get(src_pte));
  1027. break;
  1028. } else if (ret == -EBUSY) {
  1029. break;
  1030. } else if (!ret) {
  1031. progress += 8;
  1032. continue;
  1033. }
  1034. ptent = ptep_get(src_pte);
  1035. VM_WARN_ON_ONCE(!pte_present(ptent));
  1036. /*
  1037. * Device exclusive entry restored, continue by copying
  1038. * the now present pte.
  1039. */
  1040. WARN_ON_ONCE(ret != -ENOENT);
  1041. }
  1042. /* copy_present_ptes() will clear `*prealloc' if consumed */
  1043. max_nr = (end - addr) / PAGE_SIZE;
  1044. ret = copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte,
  1045. ptent, addr, max_nr, rss, &prealloc);
  1046. /*
  1047. * If we need a pre-allocated page for this pte, drop the
  1048. * locks, allocate, and try again.
  1049. * If copy failed due to hwpoison in source page, break out.
  1050. */
  1051. if (unlikely(ret == -EAGAIN || ret == -EHWPOISON))
  1052. break;
  1053. if (unlikely(prealloc)) {
  1054. /*
  1055. * pre-alloc page cannot be reused by next time so as
  1056. * to strictly follow mempolicy (e.g., alloc_page_vma()
  1057. * will allocate page according to address). This
  1058. * could only happen if one pinned pte changed.
  1059. */
  1060. folio_put(prealloc);
  1061. prealloc = NULL;
  1062. }
  1063. nr = ret;
  1064. progress += 8 * nr;
  1065. } while (dst_pte += nr, src_pte += nr, addr += PAGE_SIZE * nr,
  1066. addr != end);
  1067. arch_leave_lazy_mmu_mode();
  1068. pte_unmap_unlock(orig_src_pte, src_ptl);
  1069. add_mm_rss_vec(dst_mm, rss);
  1070. pte_unmap_unlock(orig_dst_pte, dst_ptl);
  1071. cond_resched();
  1072. if (ret == -EIO) {
  1073. VM_WARN_ON_ONCE(!entry.val);
  1074. if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
  1075. ret = -ENOMEM;
  1076. goto out;
  1077. }
  1078. entry.val = 0;
  1079. } else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) {
  1080. goto out;
  1081. } else if (ret == -EAGAIN) {
  1082. prealloc = folio_prealloc(src_mm, src_vma, addr, false);
  1083. if (!prealloc)
  1084. return -ENOMEM;
  1085. } else if (ret < 0) {
  1086. VM_WARN_ON_ONCE(1);
  1087. }
  1088. /* We've captured and resolved the error. Reset, try again. */
  1089. ret = 0;
  1090. if (addr != end)
  1091. goto again;
  1092. out:
  1093. if (unlikely(prealloc))
  1094. folio_put(prealloc);
  1095. return ret;
  1096. }
  1097. static inline int
  1098. copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  1099. pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
  1100. unsigned long end)
  1101. {
  1102. struct mm_struct *dst_mm = dst_vma->vm_mm;
  1103. struct mm_struct *src_mm = src_vma->vm_mm;
  1104. pmd_t *src_pmd, *dst_pmd;
  1105. unsigned long next;
  1106. dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
  1107. if (!dst_pmd)
  1108. return -ENOMEM;
  1109. src_pmd = pmd_offset(src_pud, addr);
  1110. do {
  1111. next = pmd_addr_end(addr, end);
  1112. if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
  1113. || pmd_devmap(*src_pmd)) {
  1114. int err;
  1115. VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
  1116. err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
  1117. addr, dst_vma, src_vma);
  1118. if (err == -ENOMEM)
  1119. return -ENOMEM;
  1120. if (!err)
  1121. continue;
  1122. /* fall through */
  1123. }
  1124. if (pmd_none_or_clear_bad(src_pmd))
  1125. continue;
  1126. if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
  1127. addr, next))
  1128. return -ENOMEM;
  1129. } while (dst_pmd++, src_pmd++, addr = next, addr != end);
  1130. return 0;
  1131. }
  1132. static inline int
  1133. copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  1134. p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
  1135. unsigned long end)
  1136. {
  1137. struct mm_struct *dst_mm = dst_vma->vm_mm;
  1138. struct mm_struct *src_mm = src_vma->vm_mm;
  1139. pud_t *src_pud, *dst_pud;
  1140. unsigned long next;
  1141. dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
  1142. if (!dst_pud)
  1143. return -ENOMEM;
  1144. src_pud = pud_offset(src_p4d, addr);
  1145. do {
  1146. next = pud_addr_end(addr, end);
  1147. if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
  1148. int err;
  1149. VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
  1150. err = copy_huge_pud(dst_mm, src_mm,
  1151. dst_pud, src_pud, addr, src_vma);
  1152. if (err == -ENOMEM)
  1153. return -ENOMEM;
  1154. if (!err)
  1155. continue;
  1156. /* fall through */
  1157. }
  1158. if (pud_none_or_clear_bad(src_pud))
  1159. continue;
  1160. if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
  1161. addr, next))
  1162. return -ENOMEM;
  1163. } while (dst_pud++, src_pud++, addr = next, addr != end);
  1164. return 0;
  1165. }
  1166. static inline int
  1167. copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
  1168. pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
  1169. unsigned long end)
  1170. {
  1171. struct mm_struct *dst_mm = dst_vma->vm_mm;
  1172. p4d_t *src_p4d, *dst_p4d;
  1173. unsigned long next;
  1174. dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
  1175. if (!dst_p4d)
  1176. return -ENOMEM;
  1177. src_p4d = p4d_offset(src_pgd, addr);
  1178. do {
  1179. next = p4d_addr_end(addr, end);
  1180. if (p4d_none_or_clear_bad(src_p4d))
  1181. continue;
  1182. if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
  1183. addr, next))
  1184. return -ENOMEM;
  1185. } while (dst_p4d++, src_p4d++, addr = next, addr != end);
  1186. return 0;
  1187. }
  1188. /*
  1189. * Return true if the vma needs to copy the pgtable during this fork(). Return
  1190. * false when we can speed up fork() by allowing lazy page faults later until
  1191. * when the child accesses the memory range.
  1192. */
  1193. static bool
  1194. vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
  1195. {
  1196. /*
  1197. * Always copy pgtables when dst_vma has uffd-wp enabled even if it's
  1198. * file-backed (e.g. shmem). Because when uffd-wp is enabled, pgtable
  1199. * contains uffd-wp protection information, that's something we can't
  1200. * retrieve from page cache, and skip copying will lose those info.
  1201. */
  1202. if (userfaultfd_wp(dst_vma))
  1203. return true;
  1204. if (src_vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
  1205. return true;
  1206. if (src_vma->anon_vma)
  1207. return true;
  1208. /*
  1209. * Don't copy ptes where a page fault will fill them correctly. Fork
  1210. * becomes much lighter when there are big shared or private readonly
  1211. * mappings. The tradeoff is that copy_page_range is more efficient
  1212. * than faulting.
  1213. */
  1214. return false;
  1215. }
  1216. int
  1217. copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
  1218. {
  1219. pgd_t *src_pgd, *dst_pgd;
  1220. unsigned long addr = src_vma->vm_start;
  1221. unsigned long end = src_vma->vm_end;
  1222. struct mm_struct *dst_mm = dst_vma->vm_mm;
  1223. struct mm_struct *src_mm = src_vma->vm_mm;
  1224. struct mmu_notifier_range range;
  1225. unsigned long next, pfn;
  1226. bool is_cow;
  1227. int ret;
  1228. if (!vma_needs_copy(dst_vma, src_vma))
  1229. return 0;
  1230. if (is_vm_hugetlb_page(src_vma))
  1231. return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma);
  1232. if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
  1233. ret = track_pfn_copy(dst_vma, src_vma, &pfn);
  1234. if (ret)
  1235. return ret;
  1236. }
  1237. /*
  1238. * We need to invalidate the secondary MMU mappings only when
  1239. * there could be a permission downgrade on the ptes of the
  1240. * parent mm. And a permission downgrade will only happen if
  1241. * is_cow_mapping() returns true.
  1242. */
  1243. is_cow = is_cow_mapping(src_vma->vm_flags);
  1244. if (is_cow) {
  1245. mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
  1246. 0, src_mm, addr, end);
  1247. mmu_notifier_invalidate_range_start(&range);
  1248. /*
  1249. * Disabling preemption is not needed for the write side, as
  1250. * the read side doesn't spin, but goes to the mmap_lock.
  1251. *
  1252. * Use the raw variant of the seqcount_t write API to avoid
  1253. * lockdep complaining about preemptibility.
  1254. */
  1255. vma_assert_write_locked(src_vma);
  1256. raw_write_seqcount_begin(&src_mm->write_protect_seq);
  1257. }
  1258. ret = 0;
  1259. dst_pgd = pgd_offset(dst_mm, addr);
  1260. src_pgd = pgd_offset(src_mm, addr);
  1261. do {
  1262. next = pgd_addr_end(addr, end);
  1263. if (pgd_none_or_clear_bad(src_pgd))
  1264. continue;
  1265. if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
  1266. addr, next))) {
  1267. ret = -ENOMEM;
  1268. break;
  1269. }
  1270. } while (dst_pgd++, src_pgd++, addr = next, addr != end);
  1271. if (is_cow) {
  1272. raw_write_seqcount_end(&src_mm->write_protect_seq);
  1273. mmu_notifier_invalidate_range_end(&range);
  1274. }
  1275. if (ret && unlikely(src_vma->vm_flags & VM_PFNMAP))
  1276. untrack_pfn_copy(dst_vma, pfn);
  1277. return ret;
  1278. }
  1279. /* Whether we should zap all COWed (private) pages too */
  1280. static inline bool should_zap_cows(struct zap_details *details)
  1281. {
  1282. /* By default, zap all pages */
  1283. if (!details)
  1284. return true;
  1285. /* Or, we zap COWed pages only if the caller wants to */
  1286. return details->even_cows;
  1287. }
  1288. /* Decides whether we should zap this folio with the folio pointer specified */
  1289. static inline bool should_zap_folio(struct zap_details *details,
  1290. struct folio *folio)
  1291. {
  1292. /* If we can make a decision without *folio.. */
  1293. if (should_zap_cows(details))
  1294. return true;
  1295. /* Otherwise we should only zap non-anon folios */
  1296. return !folio_test_anon(folio);
  1297. }
  1298. static inline bool zap_drop_file_uffd_wp(struct zap_details *details)
  1299. {
  1300. if (!details)
  1301. return false;
  1302. return details->zap_flags & ZAP_FLAG_DROP_MARKER;
  1303. }
  1304. /*
  1305. * This function makes sure that we'll replace the none pte with an uffd-wp
  1306. * swap special pte marker when necessary. Must be with the pgtable lock held.
  1307. */
  1308. static inline void
  1309. zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
  1310. unsigned long addr, pte_t *pte, int nr,
  1311. struct zap_details *details, pte_t pteval)
  1312. {
  1313. /* Zap on anonymous always means dropping everything */
  1314. if (vma_is_anonymous(vma))
  1315. return;
  1316. if (zap_drop_file_uffd_wp(details))
  1317. return;
  1318. for (;;) {
  1319. /* the PFN in the PTE is irrelevant. */
  1320. pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
  1321. if (--nr == 0)
  1322. break;
  1323. pte++;
  1324. addr += PAGE_SIZE;
  1325. }
  1326. }
  1327. static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb,
  1328. struct vm_area_struct *vma, struct folio *folio,
  1329. struct page *page, pte_t *pte, pte_t ptent, unsigned int nr,
  1330. unsigned long addr, struct zap_details *details, int *rss,
  1331. bool *force_flush, bool *force_break)
  1332. {
  1333. struct mm_struct *mm = tlb->mm;
  1334. bool delay_rmap = false;
  1335. if (!folio_test_anon(folio)) {
  1336. ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
  1337. if (pte_dirty(ptent)) {
  1338. folio_mark_dirty(folio);
  1339. if (tlb_delay_rmap(tlb)) {
  1340. delay_rmap = true;
  1341. *force_flush = true;
  1342. }
  1343. }
  1344. if (pte_young(ptent) && likely(vma_has_recency(vma)))
  1345. folio_mark_accessed(folio);
  1346. rss[mm_counter(folio)] -= nr;
  1347. } else {
  1348. /* We don't need up-to-date accessed/dirty bits. */
  1349. clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
  1350. rss[MM_ANONPAGES] -= nr;
  1351. }
  1352. /* Checking a single PTE in a batch is sufficient. */
  1353. arch_check_zapped_pte(vma, ptent);
  1354. tlb_remove_tlb_entries(tlb, pte, nr, addr);
  1355. if (unlikely(userfaultfd_pte_wp(vma, ptent)))
  1356. zap_install_uffd_wp_if_needed(vma, addr, pte, nr, details,
  1357. ptent);
  1358. if (!delay_rmap) {
  1359. folio_remove_rmap_ptes(folio, page, nr, vma);
  1360. if (unlikely(folio_mapcount(folio) < 0))
  1361. print_bad_pte(vma, addr, ptent, page);
  1362. }
  1363. if (unlikely(__tlb_remove_folio_pages(tlb, page, nr, delay_rmap))) {
  1364. *force_flush = true;
  1365. *force_break = true;
  1366. }
  1367. }
  1368. /*
  1369. * Zap or skip at least one present PTE, trying to batch-process subsequent
  1370. * PTEs that map consecutive pages of the same folio.
  1371. *
  1372. * Returns the number of processed (skipped or zapped) PTEs (at least 1).
  1373. */
  1374. static inline int zap_present_ptes(struct mmu_gather *tlb,
  1375. struct vm_area_struct *vma, pte_t *pte, pte_t ptent,
  1376. unsigned int max_nr, unsigned long addr,
  1377. struct zap_details *details, int *rss, bool *force_flush,
  1378. bool *force_break)
  1379. {
  1380. const fpb_t fpb_flags = FPB_IGNORE_DIRTY | FPB_IGNORE_SOFT_DIRTY;
  1381. struct mm_struct *mm = tlb->mm;
  1382. struct folio *folio;
  1383. struct page *page;
  1384. int nr;
  1385. page = vm_normal_page(vma, addr, ptent);
  1386. if (!page) {
  1387. /* We don't need up-to-date accessed/dirty bits. */
  1388. ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
  1389. arch_check_zapped_pte(vma, ptent);
  1390. tlb_remove_tlb_entry(tlb, pte, addr);
  1391. if (userfaultfd_pte_wp(vma, ptent))
  1392. zap_install_uffd_wp_if_needed(vma, addr, pte, 1,
  1393. details, ptent);
  1394. ksm_might_unmap_zero_page(mm, ptent);
  1395. return 1;
  1396. }
  1397. folio = page_folio(page);
  1398. if (unlikely(!should_zap_folio(details, folio)))
  1399. return 1;
  1400. /*
  1401. * Make sure that the common "small folio" case is as fast as possible
  1402. * by keeping the batching logic separate.
  1403. */
  1404. if (unlikely(folio_test_large(folio) && max_nr != 1)) {
  1405. nr = folio_pte_batch(folio, addr, pte, ptent, max_nr, fpb_flags,
  1406. NULL, NULL, NULL);
  1407. zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, nr,
  1408. addr, details, rss, force_flush,
  1409. force_break);
  1410. return nr;
  1411. }
  1412. zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, 1, addr,
  1413. details, rss, force_flush, force_break);
  1414. return 1;
  1415. }
  1416. static unsigned long zap_pte_range(struct mmu_gather *tlb,
  1417. struct vm_area_struct *vma, pmd_t *pmd,
  1418. unsigned long addr, unsigned long end,
  1419. struct zap_details *details)
  1420. {
  1421. bool force_flush = false, force_break = false;
  1422. struct mm_struct *mm = tlb->mm;
  1423. int rss[NR_MM_COUNTERS];
  1424. spinlock_t *ptl;
  1425. pte_t *start_pte;
  1426. pte_t *pte;
  1427. swp_entry_t entry;
  1428. int nr;
  1429. tlb_change_page_size(tlb, PAGE_SIZE);
  1430. init_rss_vec(rss);
  1431. start_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
  1432. if (!pte)
  1433. return addr;
  1434. flush_tlb_batched_pending(mm);
  1435. arch_enter_lazy_mmu_mode();
  1436. do {
  1437. pte_t ptent = ptep_get(pte);
  1438. struct folio *folio;
  1439. struct page *page;
  1440. int max_nr;
  1441. nr = 1;
  1442. if (pte_none(ptent))
  1443. continue;
  1444. if (need_resched())
  1445. break;
  1446. if (pte_present(ptent)) {
  1447. max_nr = (end - addr) / PAGE_SIZE;
  1448. nr = zap_present_ptes(tlb, vma, pte, ptent, max_nr,
  1449. addr, details, rss, &force_flush,
  1450. &force_break);
  1451. if (unlikely(force_break)) {
  1452. addr += nr * PAGE_SIZE;
  1453. break;
  1454. }
  1455. continue;
  1456. }
  1457. entry = pte_to_swp_entry(ptent);
  1458. if (is_device_private_entry(entry) ||
  1459. is_device_exclusive_entry(entry)) {
  1460. page = pfn_swap_entry_to_page(entry);
  1461. folio = page_folio(page);
  1462. if (unlikely(!should_zap_folio(details, folio)))
  1463. continue;
  1464. /*
  1465. * Both device private/exclusive mappings should only
  1466. * work with anonymous page so far, so we don't need to
  1467. * consider uffd-wp bit when zap. For more information,
  1468. * see zap_install_uffd_wp_if_needed().
  1469. */
  1470. WARN_ON_ONCE(!vma_is_anonymous(vma));
  1471. rss[mm_counter(folio)]--;
  1472. if (is_device_private_entry(entry))
  1473. folio_remove_rmap_pte(folio, page, vma);
  1474. folio_put(folio);
  1475. } else if (!non_swap_entry(entry)) {
  1476. max_nr = (end - addr) / PAGE_SIZE;
  1477. nr = swap_pte_batch(pte, max_nr, ptent);
  1478. /* Genuine swap entries, hence a private anon pages */
  1479. if (!should_zap_cows(details))
  1480. continue;
  1481. rss[MM_SWAPENTS] -= nr;
  1482. free_swap_and_cache_nr(entry, nr);
  1483. } else if (is_migration_entry(entry)) {
  1484. folio = pfn_swap_entry_folio(entry);
  1485. if (!should_zap_folio(details, folio))
  1486. continue;
  1487. rss[mm_counter(folio)]--;
  1488. } else if (pte_marker_entry_uffd_wp(entry)) {
  1489. /*
  1490. * For anon: always drop the marker; for file: only
  1491. * drop the marker if explicitly requested.
  1492. */
  1493. if (!vma_is_anonymous(vma) &&
  1494. !zap_drop_file_uffd_wp(details))
  1495. continue;
  1496. } else if (is_hwpoison_entry(entry) ||
  1497. is_poisoned_swp_entry(entry)) {
  1498. if (!should_zap_cows(details))
  1499. continue;
  1500. } else {
  1501. /* We should have covered all the swap entry types */
  1502. pr_alert("unrecognized swap entry 0x%lx\n", entry.val);
  1503. WARN_ON_ONCE(1);
  1504. }
  1505. clear_not_present_full_ptes(mm, addr, pte, nr, tlb->fullmm);
  1506. zap_install_uffd_wp_if_needed(vma, addr, pte, nr, details, ptent);
  1507. } while (pte += nr, addr += PAGE_SIZE * nr, addr != end);
  1508. add_mm_rss_vec(mm, rss);
  1509. arch_leave_lazy_mmu_mode();
  1510. /* Do the actual TLB flush before dropping ptl */
  1511. if (force_flush) {
  1512. tlb_flush_mmu_tlbonly(tlb);
  1513. tlb_flush_rmaps(tlb, vma);
  1514. }
  1515. pte_unmap_unlock(start_pte, ptl);
  1516. /*
  1517. * If we forced a TLB flush (either due to running out of
  1518. * batch buffers or because we needed to flush dirty TLB
  1519. * entries before releasing the ptl), free the batched
  1520. * memory too. Come back again if we didn't do everything.
  1521. */
  1522. if (force_flush)
  1523. tlb_flush_mmu(tlb);
  1524. return addr;
  1525. }
  1526. static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
  1527. struct vm_area_struct *vma, pud_t *pud,
  1528. unsigned long addr, unsigned long end,
  1529. struct zap_details *details)
  1530. {
  1531. pmd_t *pmd;
  1532. unsigned long next;
  1533. pmd = pmd_offset(pud, addr);
  1534. do {
  1535. next = pmd_addr_end(addr, end);
  1536. if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
  1537. if (next - addr != HPAGE_PMD_SIZE)
  1538. __split_huge_pmd(vma, pmd, addr, false, NULL);
  1539. else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
  1540. addr = next;
  1541. continue;
  1542. }
  1543. /* fall through */
  1544. } else if (details && details->single_folio &&
  1545. folio_test_pmd_mappable(details->single_folio) &&
  1546. next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
  1547. spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
  1548. /*
  1549. * Take and drop THP pmd lock so that we cannot return
  1550. * prematurely, while zap_huge_pmd() has cleared *pmd,
  1551. * but not yet decremented compound_mapcount().
  1552. */
  1553. spin_unlock(ptl);
  1554. }
  1555. if (pmd_none(*pmd)) {
  1556. addr = next;
  1557. continue;
  1558. }
  1559. addr = zap_pte_range(tlb, vma, pmd, addr, next, details);
  1560. if (addr != next)
  1561. pmd--;
  1562. } while (pmd++, cond_resched(), addr != end);
  1563. return addr;
  1564. }
  1565. static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
  1566. struct vm_area_struct *vma, p4d_t *p4d,
  1567. unsigned long addr, unsigned long end,
  1568. struct zap_details *details)
  1569. {
  1570. pud_t *pud;
  1571. unsigned long next;
  1572. pud = pud_offset(p4d, addr);
  1573. do {
  1574. next = pud_addr_end(addr, end);
  1575. if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
  1576. if (next - addr != HPAGE_PUD_SIZE) {
  1577. mmap_assert_locked(tlb->mm);
  1578. split_huge_pud(vma, pud, addr);
  1579. } else if (zap_huge_pud(tlb, vma, pud, addr))
  1580. goto next;
  1581. /* fall through */
  1582. }
  1583. if (pud_none_or_clear_bad(pud))
  1584. continue;
  1585. next = zap_pmd_range(tlb, vma, pud, addr, next, details);
  1586. next:
  1587. cond_resched();
  1588. } while (pud++, addr = next, addr != end);
  1589. return addr;
  1590. }
  1591. static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
  1592. struct vm_area_struct *vma, pgd_t *pgd,
  1593. unsigned long addr, unsigned long end,
  1594. struct zap_details *details)
  1595. {
  1596. p4d_t *p4d;
  1597. unsigned long next;
  1598. p4d = p4d_offset(pgd, addr);
  1599. do {
  1600. next = p4d_addr_end(addr, end);
  1601. if (p4d_none_or_clear_bad(p4d))
  1602. continue;
  1603. next = zap_pud_range(tlb, vma, p4d, addr, next, details);
  1604. } while (p4d++, addr = next, addr != end);
  1605. return addr;
  1606. }
  1607. void unmap_page_range(struct mmu_gather *tlb,
  1608. struct vm_area_struct *vma,
  1609. unsigned long addr, unsigned long end,
  1610. struct zap_details *details)
  1611. {
  1612. pgd_t *pgd;
  1613. unsigned long next;
  1614. BUG_ON(addr >= end);
  1615. tlb_start_vma(tlb, vma);
  1616. pgd = pgd_offset(vma->vm_mm, addr);
  1617. do {
  1618. next = pgd_addr_end(addr, end);
  1619. if (pgd_none_or_clear_bad(pgd))
  1620. continue;
  1621. next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
  1622. } while (pgd++, addr = next, addr != end);
  1623. tlb_end_vma(tlb, vma);
  1624. }
  1625. static void unmap_single_vma(struct mmu_gather *tlb,
  1626. struct vm_area_struct *vma, unsigned long start_addr,
  1627. unsigned long end_addr,
  1628. struct zap_details *details, bool mm_wr_locked)
  1629. {
  1630. unsigned long start = max(vma->vm_start, start_addr);
  1631. unsigned long end;
  1632. if (start >= vma->vm_end)
  1633. return;
  1634. end = min(vma->vm_end, end_addr);
  1635. if (end <= vma->vm_start)
  1636. return;
  1637. if (vma->vm_file)
  1638. uprobe_munmap(vma, start, end);
  1639. if (unlikely(vma->vm_flags & VM_PFNMAP))
  1640. untrack_pfn(vma, 0, 0, mm_wr_locked);
  1641. if (start != end) {
  1642. if (unlikely(is_vm_hugetlb_page(vma))) {
  1643. /*
  1644. * It is undesirable to test vma->vm_file as it
  1645. * should be non-null for valid hugetlb area.
  1646. * However, vm_file will be NULL in the error
  1647. * cleanup path of mmap_region. When
  1648. * hugetlbfs ->mmap method fails,
  1649. * mmap_region() nullifies vma->vm_file
  1650. * before calling this function to clean up.
  1651. * Since no pte has actually been setup, it is
  1652. * safe to do nothing in this case.
  1653. */
  1654. if (vma->vm_file) {
  1655. zap_flags_t zap_flags = details ?
  1656. details->zap_flags : 0;
  1657. __unmap_hugepage_range(tlb, vma, start, end,
  1658. NULL, zap_flags);
  1659. }
  1660. } else
  1661. unmap_page_range(tlb, vma, start, end, details);
  1662. }
  1663. }
  1664. /**
  1665. * unmap_vmas - unmap a range of memory covered by a list of vma's
  1666. * @tlb: address of the caller's struct mmu_gather
  1667. * @mas: the maple state
  1668. * @vma: the starting vma
  1669. * @start_addr: virtual address at which to start unmapping
  1670. * @end_addr: virtual address at which to end unmapping
  1671. * @tree_end: The maximum index to check
  1672. * @mm_wr_locked: lock flag
  1673. *
  1674. * Unmap all pages in the vma list.
  1675. *
  1676. * Only addresses between `start' and `end' will be unmapped.
  1677. *
  1678. * The VMA list must be sorted in ascending virtual address order.
  1679. *
  1680. * unmap_vmas() assumes that the caller will flush the whole unmapped address
  1681. * range after unmap_vmas() returns. So the only responsibility here is to
  1682. * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
  1683. * drops the lock and schedules.
  1684. */
  1685. void unmap_vmas(struct mmu_gather *tlb, struct ma_state *mas,
  1686. struct vm_area_struct *vma, unsigned long start_addr,
  1687. unsigned long end_addr, unsigned long tree_end,
  1688. bool mm_wr_locked)
  1689. {
  1690. struct mmu_notifier_range range;
  1691. struct zap_details details = {
  1692. .zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP,
  1693. /* Careful - we need to zap private pages too! */
  1694. .even_cows = true,
  1695. };
  1696. mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma->vm_mm,
  1697. start_addr, end_addr);
  1698. mmu_notifier_invalidate_range_start(&range);
  1699. do {
  1700. unsigned long start = start_addr;
  1701. unsigned long end = end_addr;
  1702. hugetlb_zap_begin(vma, &start, &end);
  1703. unmap_single_vma(tlb, vma, start, end, &details,
  1704. mm_wr_locked);
  1705. hugetlb_zap_end(vma, &details);
  1706. vma = mas_find(mas, tree_end - 1);
  1707. } while (vma && likely(!xa_is_zero(vma)));
  1708. mmu_notifier_invalidate_range_end(&range);
  1709. }
  1710. /**
  1711. * zap_page_range_single - remove user pages in a given range
  1712. * @vma: vm_area_struct holding the applicable pages
  1713. * @address: starting address of pages to zap
  1714. * @size: number of bytes to zap
  1715. * @details: details of shared cache invalidation
  1716. *
  1717. * The range must fit into one VMA.
  1718. */
  1719. void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
  1720. unsigned long size, struct zap_details *details)
  1721. {
  1722. const unsigned long end = address + size;
  1723. struct mmu_notifier_range range;
  1724. struct mmu_gather tlb;
  1725. lru_add_drain();
  1726. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
  1727. address, end);
  1728. hugetlb_zap_begin(vma, &range.start, &range.end);
  1729. tlb_gather_mmu(&tlb, vma->vm_mm);
  1730. update_hiwater_rss(vma->vm_mm);
  1731. mmu_notifier_invalidate_range_start(&range);
  1732. /*
  1733. * unmap 'address-end' not 'range.start-range.end' as range
  1734. * could have been expanded for hugetlb pmd sharing.
  1735. */
  1736. unmap_single_vma(&tlb, vma, address, end, details, false);
  1737. mmu_notifier_invalidate_range_end(&range);
  1738. tlb_finish_mmu(&tlb);
  1739. hugetlb_zap_end(vma, details);
  1740. }
  1741. /**
  1742. * zap_vma_ptes - remove ptes mapping the vma
  1743. * @vma: vm_area_struct holding ptes to be zapped
  1744. * @address: starting address of pages to zap
  1745. * @size: number of bytes to zap
  1746. *
  1747. * This function only unmaps ptes assigned to VM_PFNMAP vmas.
  1748. *
  1749. * The entire address range must be fully contained within the vma.
  1750. *
  1751. */
  1752. void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
  1753. unsigned long size)
  1754. {
  1755. if (!range_in_vma(vma, address, address + size) ||
  1756. !(vma->vm_flags & VM_PFNMAP))
  1757. return;
  1758. zap_page_range_single(vma, address, size, NULL);
  1759. }
  1760. EXPORT_SYMBOL_GPL(zap_vma_ptes);
  1761. static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
  1762. {
  1763. pgd_t *pgd;
  1764. p4d_t *p4d;
  1765. pud_t *pud;
  1766. pmd_t *pmd;
  1767. pgd = pgd_offset(mm, addr);
  1768. p4d = p4d_alloc(mm, pgd, addr);
  1769. if (!p4d)
  1770. return NULL;
  1771. pud = pud_alloc(mm, p4d, addr);
  1772. if (!pud)
  1773. return NULL;
  1774. pmd = pmd_alloc(mm, pud, addr);
  1775. if (!pmd)
  1776. return NULL;
  1777. VM_BUG_ON(pmd_trans_huge(*pmd));
  1778. return pmd;
  1779. }
  1780. pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
  1781. spinlock_t **ptl)
  1782. {
  1783. pmd_t *pmd = walk_to_pmd(mm, addr);
  1784. if (!pmd)
  1785. return NULL;
  1786. return pte_alloc_map_lock(mm, pmd, addr, ptl);
  1787. }
  1788. static bool vm_mixed_zeropage_allowed(struct vm_area_struct *vma)
  1789. {
  1790. VM_WARN_ON_ONCE(vma->vm_flags & VM_PFNMAP);
  1791. /*
  1792. * Whoever wants to forbid the zeropage after some zeropages
  1793. * might already have been mapped has to scan the page tables and
  1794. * bail out on any zeropages. Zeropages in COW mappings can
  1795. * be unshared using FAULT_FLAG_UNSHARE faults.
  1796. */
  1797. if (mm_forbids_zeropage(vma->vm_mm))
  1798. return false;
  1799. /* zeropages in COW mappings are common and unproblematic. */
  1800. if (is_cow_mapping(vma->vm_flags))
  1801. return true;
  1802. /* Mappings that do not allow for writable PTEs are unproblematic. */
  1803. if (!(vma->vm_flags & (VM_WRITE | VM_MAYWRITE)))
  1804. return true;
  1805. /*
  1806. * Why not allow any VMA that has vm_ops->pfn_mkwrite? GUP could
  1807. * find the shared zeropage and longterm-pin it, which would
  1808. * be problematic as soon as the zeropage gets replaced by a different
  1809. * page due to vma->vm_ops->pfn_mkwrite, because what's mapped would
  1810. * now differ to what GUP looked up. FSDAX is incompatible to
  1811. * FOLL_LONGTERM and VM_IO is incompatible to GUP completely (see
  1812. * check_vma_flags).
  1813. */
  1814. return vma->vm_ops && vma->vm_ops->pfn_mkwrite &&
  1815. (vma_is_fsdax(vma) || vma->vm_flags & VM_IO);
  1816. }
  1817. static int validate_page_before_insert(struct vm_area_struct *vma,
  1818. struct page *page)
  1819. {
  1820. struct folio *folio = page_folio(page);
  1821. if (!folio_ref_count(folio))
  1822. return -EINVAL;
  1823. if (unlikely(is_zero_folio(folio))) {
  1824. if (!vm_mixed_zeropage_allowed(vma))
  1825. return -EINVAL;
  1826. return 0;
  1827. }
  1828. if (folio_test_anon(folio) || folio_test_slab(folio) ||
  1829. page_has_type(page))
  1830. return -EINVAL;
  1831. flush_dcache_folio(folio);
  1832. return 0;
  1833. }
  1834. static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
  1835. unsigned long addr, struct page *page, pgprot_t prot)
  1836. {
  1837. struct folio *folio = page_folio(page);
  1838. pte_t pteval;
  1839. if (!pte_none(ptep_get(pte)))
  1840. return -EBUSY;
  1841. /* Ok, finally just insert the thing.. */
  1842. pteval = mk_pte(page, prot);
  1843. if (unlikely(is_zero_folio(folio))) {
  1844. pteval = pte_mkspecial(pteval);
  1845. } else {
  1846. folio_get(folio);
  1847. inc_mm_counter(vma->vm_mm, mm_counter_file(folio));
  1848. folio_add_file_rmap_pte(folio, page, vma);
  1849. }
  1850. set_pte_at(vma->vm_mm, addr, pte, pteval);
  1851. return 0;
  1852. }
  1853. static int insert_page(struct vm_area_struct *vma, unsigned long addr,
  1854. struct page *page, pgprot_t prot)
  1855. {
  1856. int retval;
  1857. pte_t *pte;
  1858. spinlock_t *ptl;
  1859. retval = validate_page_before_insert(vma, page);
  1860. if (retval)
  1861. goto out;
  1862. retval = -ENOMEM;
  1863. pte = get_locked_pte(vma->vm_mm, addr, &ptl);
  1864. if (!pte)
  1865. goto out;
  1866. retval = insert_page_into_pte_locked(vma, pte, addr, page, prot);
  1867. pte_unmap_unlock(pte, ptl);
  1868. out:
  1869. return retval;
  1870. }
  1871. static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
  1872. unsigned long addr, struct page *page, pgprot_t prot)
  1873. {
  1874. int err;
  1875. err = validate_page_before_insert(vma, page);
  1876. if (err)
  1877. return err;
  1878. return insert_page_into_pte_locked(vma, pte, addr, page, prot);
  1879. }
  1880. /* insert_pages() amortizes the cost of spinlock operations
  1881. * when inserting pages in a loop.
  1882. */
  1883. static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
  1884. struct page **pages, unsigned long *num, pgprot_t prot)
  1885. {
  1886. pmd_t *pmd = NULL;
  1887. pte_t *start_pte, *pte;
  1888. spinlock_t *pte_lock;
  1889. struct mm_struct *const mm = vma->vm_mm;
  1890. unsigned long curr_page_idx = 0;
  1891. unsigned long remaining_pages_total = *num;
  1892. unsigned long pages_to_write_in_pmd;
  1893. int ret;
  1894. more:
  1895. ret = -EFAULT;
  1896. pmd = walk_to_pmd(mm, addr);
  1897. if (!pmd)
  1898. goto out;
  1899. pages_to_write_in_pmd = min_t(unsigned long,
  1900. remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
  1901. /* Allocate the PTE if necessary; takes PMD lock once only. */
  1902. ret = -ENOMEM;
  1903. if (pte_alloc(mm, pmd))
  1904. goto out;
  1905. while (pages_to_write_in_pmd) {
  1906. int pte_idx = 0;
  1907. const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
  1908. start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
  1909. if (!start_pte) {
  1910. ret = -EFAULT;
  1911. goto out;
  1912. }
  1913. for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
  1914. int err = insert_page_in_batch_locked(vma, pte,
  1915. addr, pages[curr_page_idx], prot);
  1916. if (unlikely(err)) {
  1917. pte_unmap_unlock(start_pte, pte_lock);
  1918. ret = err;
  1919. remaining_pages_total -= pte_idx;
  1920. goto out;
  1921. }
  1922. addr += PAGE_SIZE;
  1923. ++curr_page_idx;
  1924. }
  1925. pte_unmap_unlock(start_pte, pte_lock);
  1926. pages_to_write_in_pmd -= batch_size;
  1927. remaining_pages_total -= batch_size;
  1928. }
  1929. if (remaining_pages_total)
  1930. goto more;
  1931. ret = 0;
  1932. out:
  1933. *num = remaining_pages_total;
  1934. return ret;
  1935. }
  1936. /**
  1937. * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
  1938. * @vma: user vma to map to
  1939. * @addr: target start user address of these pages
  1940. * @pages: source kernel pages
  1941. * @num: in: number of pages to map. out: number of pages that were *not*
  1942. * mapped. (0 means all pages were successfully mapped).
  1943. *
  1944. * Preferred over vm_insert_page() when inserting multiple pages.
  1945. *
  1946. * In case of error, we may have mapped a subset of the provided
  1947. * pages. It is the caller's responsibility to account for this case.
  1948. *
  1949. * The same restrictions apply as in vm_insert_page().
  1950. */
  1951. int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
  1952. struct page **pages, unsigned long *num)
  1953. {
  1954. const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
  1955. if (addr < vma->vm_start || end_addr >= vma->vm_end)
  1956. return -EFAULT;
  1957. if (!(vma->vm_flags & VM_MIXEDMAP)) {
  1958. BUG_ON(mmap_read_trylock(vma->vm_mm));
  1959. BUG_ON(vma->vm_flags & VM_PFNMAP);
  1960. vm_flags_set(vma, VM_MIXEDMAP);
  1961. }
  1962. /* Defer page refcount checking till we're about to map that page. */
  1963. return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
  1964. }
  1965. EXPORT_SYMBOL(vm_insert_pages);
  1966. /**
  1967. * vm_insert_page - insert single page into user vma
  1968. * @vma: user vma to map to
  1969. * @addr: target user address of this page
  1970. * @page: source kernel page
  1971. *
  1972. * This allows drivers to insert individual pages they've allocated
  1973. * into a user vma. The zeropage is supported in some VMAs,
  1974. * see vm_mixed_zeropage_allowed().
  1975. *
  1976. * The page has to be a nice clean _individual_ kernel allocation.
  1977. * If you allocate a compound page, you need to have marked it as
  1978. * such (__GFP_COMP), or manually just split the page up yourself
  1979. * (see split_page()).
  1980. *
  1981. * NOTE! Traditionally this was done with "remap_pfn_range()" which
  1982. * took an arbitrary page protection parameter. This doesn't allow
  1983. * that. Your vma protection will have to be set up correctly, which
  1984. * means that if you want a shared writable mapping, you'd better
  1985. * ask for a shared writable mapping!
  1986. *
  1987. * The page does not need to be reserved.
  1988. *
  1989. * Usually this function is called from f_op->mmap() handler
  1990. * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
  1991. * Caller must set VM_MIXEDMAP on vma if it wants to call this
  1992. * function from other places, for example from page-fault handler.
  1993. *
  1994. * Return: %0 on success, negative error code otherwise.
  1995. */
  1996. int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
  1997. struct page *page)
  1998. {
  1999. if (addr < vma->vm_start || addr >= vma->vm_end)
  2000. return -EFAULT;
  2001. if (!(vma->vm_flags & VM_MIXEDMAP)) {
  2002. BUG_ON(mmap_read_trylock(vma->vm_mm));
  2003. BUG_ON(vma->vm_flags & VM_PFNMAP);
  2004. vm_flags_set(vma, VM_MIXEDMAP);
  2005. }
  2006. return insert_page(vma, addr, page, vma->vm_page_prot);
  2007. }
  2008. EXPORT_SYMBOL(vm_insert_page);
  2009. /*
  2010. * __vm_map_pages - maps range of kernel pages into user vma
  2011. * @vma: user vma to map to
  2012. * @pages: pointer to array of source kernel pages
  2013. * @num: number of pages in page array
  2014. * @offset: user's requested vm_pgoff
  2015. *
  2016. * This allows drivers to map range of kernel pages into a user vma.
  2017. * The zeropage is supported in some VMAs, see
  2018. * vm_mixed_zeropage_allowed().
  2019. *
  2020. * Return: 0 on success and error code otherwise.
  2021. */
  2022. static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
  2023. unsigned long num, unsigned long offset)
  2024. {
  2025. unsigned long count = vma_pages(vma);
  2026. unsigned long uaddr = vma->vm_start;
  2027. int ret, i;
  2028. /* Fail if the user requested offset is beyond the end of the object */
  2029. if (offset >= num)
  2030. return -ENXIO;
  2031. /* Fail if the user requested size exceeds available object size */
  2032. if (count > num - offset)
  2033. return -ENXIO;
  2034. for (i = 0; i < count; i++) {
  2035. ret = vm_insert_page(vma, uaddr, pages[offset + i]);
  2036. if (ret < 0)
  2037. return ret;
  2038. uaddr += PAGE_SIZE;
  2039. }
  2040. return 0;
  2041. }
  2042. /**
  2043. * vm_map_pages - maps range of kernel pages starts with non zero offset
  2044. * @vma: user vma to map to
  2045. * @pages: pointer to array of source kernel pages
  2046. * @num: number of pages in page array
  2047. *
  2048. * Maps an object consisting of @num pages, catering for the user's
  2049. * requested vm_pgoff
  2050. *
  2051. * If we fail to insert any page into the vma, the function will return
  2052. * immediately leaving any previously inserted pages present. Callers
  2053. * from the mmap handler may immediately return the error as their caller
  2054. * will destroy the vma, removing any successfully inserted pages. Other
  2055. * callers should make their own arrangements for calling unmap_region().
  2056. *
  2057. * Context: Process context. Called by mmap handlers.
  2058. * Return: 0 on success and error code otherwise.
  2059. */
  2060. int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
  2061. unsigned long num)
  2062. {
  2063. return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
  2064. }
  2065. EXPORT_SYMBOL(vm_map_pages);
  2066. /**
  2067. * vm_map_pages_zero - map range of kernel pages starts with zero offset
  2068. * @vma: user vma to map to
  2069. * @pages: pointer to array of source kernel pages
  2070. * @num: number of pages in page array
  2071. *
  2072. * Similar to vm_map_pages(), except that it explicitly sets the offset
  2073. * to 0. This function is intended for the drivers that did not consider
  2074. * vm_pgoff.
  2075. *
  2076. * Context: Process context. Called by mmap handlers.
  2077. * Return: 0 on success and error code otherwise.
  2078. */
  2079. int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
  2080. unsigned long num)
  2081. {
  2082. return __vm_map_pages(vma, pages, num, 0);
  2083. }
  2084. EXPORT_SYMBOL(vm_map_pages_zero);
  2085. static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
  2086. pfn_t pfn, pgprot_t prot, bool mkwrite)
  2087. {
  2088. struct mm_struct *mm = vma->vm_mm;
  2089. pte_t *pte, entry;
  2090. spinlock_t *ptl;
  2091. pte = get_locked_pte(mm, addr, &ptl);
  2092. if (!pte)
  2093. return VM_FAULT_OOM;
  2094. entry = ptep_get(pte);
  2095. if (!pte_none(entry)) {
  2096. if (mkwrite) {
  2097. /*
  2098. * For read faults on private mappings the PFN passed
  2099. * in may not match the PFN we have mapped if the
  2100. * mapped PFN is a writeable COW page. In the mkwrite
  2101. * case we are creating a writable PTE for a shared
  2102. * mapping and we expect the PFNs to match. If they
  2103. * don't match, we are likely racing with block
  2104. * allocation and mapping invalidation so just skip the
  2105. * update.
  2106. */
  2107. if (pte_pfn(entry) != pfn_t_to_pfn(pfn)) {
  2108. WARN_ON_ONCE(!is_zero_pfn(pte_pfn(entry)));
  2109. goto out_unlock;
  2110. }
  2111. entry = pte_mkyoung(entry);
  2112. entry = maybe_mkwrite(pte_mkdirty(entry), vma);
  2113. if (ptep_set_access_flags(vma, addr, pte, entry, 1))
  2114. update_mmu_cache(vma, addr, pte);
  2115. }
  2116. goto out_unlock;
  2117. }
  2118. /* Ok, finally just insert the thing.. */
  2119. if (pfn_t_devmap(pfn))
  2120. entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
  2121. else
  2122. entry = pte_mkspecial(pfn_t_pte(pfn, prot));
  2123. if (mkwrite) {
  2124. entry = pte_mkyoung(entry);
  2125. entry = maybe_mkwrite(pte_mkdirty(entry), vma);
  2126. }
  2127. set_pte_at(mm, addr, pte, entry);
  2128. update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
  2129. out_unlock:
  2130. pte_unmap_unlock(pte, ptl);
  2131. return VM_FAULT_NOPAGE;
  2132. }
  2133. /**
  2134. * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
  2135. * @vma: user vma to map to
  2136. * @addr: target user address of this page
  2137. * @pfn: source kernel pfn
  2138. * @pgprot: pgprot flags for the inserted page
  2139. *
  2140. * This is exactly like vmf_insert_pfn(), except that it allows drivers
  2141. * to override pgprot on a per-page basis.
  2142. *
  2143. * This only makes sense for IO mappings, and it makes no sense for
  2144. * COW mappings. In general, using multiple vmas is preferable;
  2145. * vmf_insert_pfn_prot should only be used if using multiple VMAs is
  2146. * impractical.
  2147. *
  2148. * pgprot typically only differs from @vma->vm_page_prot when drivers set
  2149. * caching- and encryption bits different than those of @vma->vm_page_prot,
  2150. * because the caching- or encryption mode may not be known at mmap() time.
  2151. *
  2152. * This is ok as long as @vma->vm_page_prot is not used by the core vm
  2153. * to set caching and encryption bits for those vmas (except for COW pages).
  2154. * This is ensured by core vm only modifying these page table entries using
  2155. * functions that don't touch caching- or encryption bits, using pte_modify()
  2156. * if needed. (See for example mprotect()).
  2157. *
  2158. * Also when new page-table entries are created, this is only done using the
  2159. * fault() callback, and never using the value of vma->vm_page_prot,
  2160. * except for page-table entries that point to anonymous pages as the result
  2161. * of COW.
  2162. *
  2163. * Context: Process context. May allocate using %GFP_KERNEL.
  2164. * Return: vm_fault_t value.
  2165. */
  2166. vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
  2167. unsigned long pfn, pgprot_t pgprot)
  2168. {
  2169. /*
  2170. * Technically, architectures with pte_special can avoid all these
  2171. * restrictions (same for remap_pfn_range). However we would like
  2172. * consistency in testing and feature parity among all, so we should
  2173. * try to keep these invariants in place for everybody.
  2174. */
  2175. BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
  2176. BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
  2177. (VM_PFNMAP|VM_MIXEDMAP));
  2178. BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
  2179. BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
  2180. if (addr < vma->vm_start || addr >= vma->vm_end)
  2181. return VM_FAULT_SIGBUS;
  2182. if (!pfn_modify_allowed(pfn, pgprot))
  2183. return VM_FAULT_SIGBUS;
  2184. track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
  2185. return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
  2186. false);
  2187. }
  2188. EXPORT_SYMBOL(vmf_insert_pfn_prot);
  2189. /**
  2190. * vmf_insert_pfn - insert single pfn into user vma
  2191. * @vma: user vma to map to
  2192. * @addr: target user address of this page
  2193. * @pfn: source kernel pfn
  2194. *
  2195. * Similar to vm_insert_page, this allows drivers to insert individual pages
  2196. * they've allocated into a user vma. Same comments apply.
  2197. *
  2198. * This function should only be called from a vm_ops->fault handler, and
  2199. * in that case the handler should return the result of this function.
  2200. *
  2201. * vma cannot be a COW mapping.
  2202. *
  2203. * As this is called only for pages that do not currently exist, we
  2204. * do not need to flush old virtual caches or the TLB.
  2205. *
  2206. * Context: Process context. May allocate using %GFP_KERNEL.
  2207. * Return: vm_fault_t value.
  2208. */
  2209. vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
  2210. unsigned long pfn)
  2211. {
  2212. return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
  2213. }
  2214. EXPORT_SYMBOL(vmf_insert_pfn);
  2215. static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn, bool mkwrite)
  2216. {
  2217. if (unlikely(is_zero_pfn(pfn_t_to_pfn(pfn))) &&
  2218. (mkwrite || !vm_mixed_zeropage_allowed(vma)))
  2219. return false;
  2220. /* these checks mirror the abort conditions in vm_normal_page */
  2221. if (vma->vm_flags & VM_MIXEDMAP)
  2222. return true;
  2223. if (pfn_t_devmap(pfn))
  2224. return true;
  2225. if (pfn_t_special(pfn))
  2226. return true;
  2227. if (is_zero_pfn(pfn_t_to_pfn(pfn)))
  2228. return true;
  2229. return false;
  2230. }
  2231. static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
  2232. unsigned long addr, pfn_t pfn, bool mkwrite)
  2233. {
  2234. pgprot_t pgprot = vma->vm_page_prot;
  2235. int err;
  2236. if (!vm_mixed_ok(vma, pfn, mkwrite))
  2237. return VM_FAULT_SIGBUS;
  2238. if (addr < vma->vm_start || addr >= vma->vm_end)
  2239. return VM_FAULT_SIGBUS;
  2240. track_pfn_insert(vma, &pgprot, pfn);
  2241. if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
  2242. return VM_FAULT_SIGBUS;
  2243. /*
  2244. * If we don't have pte special, then we have to use the pfn_valid()
  2245. * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
  2246. * refcount the page if pfn_valid is true (hence insert_page rather
  2247. * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
  2248. * without pte special, it would there be refcounted as a normal page.
  2249. */
  2250. if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
  2251. !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
  2252. struct page *page;
  2253. /*
  2254. * At this point we are committed to insert_page()
  2255. * regardless of whether the caller specified flags that
  2256. * result in pfn_t_has_page() == false.
  2257. */
  2258. page = pfn_to_page(pfn_t_to_pfn(pfn));
  2259. err = insert_page(vma, addr, page, pgprot);
  2260. } else {
  2261. return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
  2262. }
  2263. if (err == -ENOMEM)
  2264. return VM_FAULT_OOM;
  2265. if (err < 0 && err != -EBUSY)
  2266. return VM_FAULT_SIGBUS;
  2267. return VM_FAULT_NOPAGE;
  2268. }
  2269. vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
  2270. pfn_t pfn)
  2271. {
  2272. return __vm_insert_mixed(vma, addr, pfn, false);
  2273. }
  2274. EXPORT_SYMBOL(vmf_insert_mixed);
  2275. /*
  2276. * If the insertion of PTE failed because someone else already added a
  2277. * different entry in the mean time, we treat that as success as we assume
  2278. * the same entry was actually inserted.
  2279. */
  2280. vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
  2281. unsigned long addr, pfn_t pfn)
  2282. {
  2283. return __vm_insert_mixed(vma, addr, pfn, true);
  2284. }
  2285. /*
  2286. * maps a range of physical memory into the requested pages. the old
  2287. * mappings are removed. any references to nonexistent pages results
  2288. * in null mappings (currently treated as "copy-on-access")
  2289. */
  2290. static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
  2291. unsigned long addr, unsigned long end,
  2292. unsigned long pfn, pgprot_t prot)
  2293. {
  2294. pte_t *pte, *mapped_pte;
  2295. spinlock_t *ptl;
  2296. int err = 0;
  2297. mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
  2298. if (!pte)
  2299. return -ENOMEM;
  2300. arch_enter_lazy_mmu_mode();
  2301. do {
  2302. BUG_ON(!pte_none(ptep_get(pte)));
  2303. if (!pfn_modify_allowed(pfn, prot)) {
  2304. err = -EACCES;
  2305. break;
  2306. }
  2307. set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
  2308. pfn++;
  2309. } while (pte++, addr += PAGE_SIZE, addr != end);
  2310. arch_leave_lazy_mmu_mode();
  2311. pte_unmap_unlock(mapped_pte, ptl);
  2312. return err;
  2313. }
  2314. static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
  2315. unsigned long addr, unsigned long end,
  2316. unsigned long pfn, pgprot_t prot)
  2317. {
  2318. pmd_t *pmd;
  2319. unsigned long next;
  2320. int err;
  2321. pfn -= addr >> PAGE_SHIFT;
  2322. pmd = pmd_alloc(mm, pud, addr);
  2323. if (!pmd)
  2324. return -ENOMEM;
  2325. VM_BUG_ON(pmd_trans_huge(*pmd));
  2326. do {
  2327. next = pmd_addr_end(addr, end);
  2328. err = remap_pte_range(mm, pmd, addr, next,
  2329. pfn + (addr >> PAGE_SHIFT), prot);
  2330. if (err)
  2331. return err;
  2332. } while (pmd++, addr = next, addr != end);
  2333. return 0;
  2334. }
  2335. static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
  2336. unsigned long addr, unsigned long end,
  2337. unsigned long pfn, pgprot_t prot)
  2338. {
  2339. pud_t *pud;
  2340. unsigned long next;
  2341. int err;
  2342. pfn -= addr >> PAGE_SHIFT;
  2343. pud = pud_alloc(mm, p4d, addr);
  2344. if (!pud)
  2345. return -ENOMEM;
  2346. do {
  2347. next = pud_addr_end(addr, end);
  2348. err = remap_pmd_range(mm, pud, addr, next,
  2349. pfn + (addr >> PAGE_SHIFT), prot);
  2350. if (err)
  2351. return err;
  2352. } while (pud++, addr = next, addr != end);
  2353. return 0;
  2354. }
  2355. static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
  2356. unsigned long addr, unsigned long end,
  2357. unsigned long pfn, pgprot_t prot)
  2358. {
  2359. p4d_t *p4d;
  2360. unsigned long next;
  2361. int err;
  2362. pfn -= addr >> PAGE_SHIFT;
  2363. p4d = p4d_alloc(mm, pgd, addr);
  2364. if (!p4d)
  2365. return -ENOMEM;
  2366. do {
  2367. next = p4d_addr_end(addr, end);
  2368. err = remap_pud_range(mm, p4d, addr, next,
  2369. pfn + (addr >> PAGE_SHIFT), prot);
  2370. if (err)
  2371. return err;
  2372. } while (p4d++, addr = next, addr != end);
  2373. return 0;
  2374. }
  2375. static int remap_pfn_range_internal(struct vm_area_struct *vma, unsigned long addr,
  2376. unsigned long pfn, unsigned long size, pgprot_t prot)
  2377. {
  2378. pgd_t *pgd;
  2379. unsigned long next;
  2380. unsigned long end = addr + PAGE_ALIGN(size);
  2381. struct mm_struct *mm = vma->vm_mm;
  2382. int err;
  2383. if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
  2384. return -EINVAL;
  2385. /*
  2386. * Physically remapped pages are special. Tell the
  2387. * rest of the world about it:
  2388. * VM_IO tells people not to look at these pages
  2389. * (accesses can have side effects).
  2390. * VM_PFNMAP tells the core MM that the base pages are just
  2391. * raw PFN mappings, and do not have a "struct page" associated
  2392. * with them.
  2393. * VM_DONTEXPAND
  2394. * Disable vma merging and expanding with mremap().
  2395. * VM_DONTDUMP
  2396. * Omit vma from core dump, even when VM_IO turned off.
  2397. *
  2398. * There's a horrible special case to handle copy-on-write
  2399. * behaviour that some programs depend on. We mark the "original"
  2400. * un-COW'ed pages by matching them up with "vma->vm_pgoff".
  2401. * See vm_normal_page() for details.
  2402. */
  2403. if (is_cow_mapping(vma->vm_flags)) {
  2404. if (addr != vma->vm_start || end != vma->vm_end)
  2405. return -EINVAL;
  2406. vma->vm_pgoff = pfn;
  2407. }
  2408. vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
  2409. BUG_ON(addr >= end);
  2410. pfn -= addr >> PAGE_SHIFT;
  2411. pgd = pgd_offset(mm, addr);
  2412. flush_cache_range(vma, addr, end);
  2413. do {
  2414. next = pgd_addr_end(addr, end);
  2415. err = remap_p4d_range(mm, pgd, addr, next,
  2416. pfn + (addr >> PAGE_SHIFT), prot);
  2417. if (err)
  2418. return err;
  2419. } while (pgd++, addr = next, addr != end);
  2420. return 0;
  2421. }
  2422. /*
  2423. * Variant of remap_pfn_range that does not call track_pfn_remap. The caller
  2424. * must have pre-validated the caching bits of the pgprot_t.
  2425. */
  2426. int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
  2427. unsigned long pfn, unsigned long size, pgprot_t prot)
  2428. {
  2429. int error = remap_pfn_range_internal(vma, addr, pfn, size, prot);
  2430. if (!error)
  2431. return 0;
  2432. /*
  2433. * A partial pfn range mapping is dangerous: it does not
  2434. * maintain page reference counts, and callers may free
  2435. * pages due to the error. So zap it early.
  2436. */
  2437. zap_page_range_single(vma, addr, size, NULL);
  2438. return error;
  2439. }
  2440. /**
  2441. * remap_pfn_range - remap kernel memory to userspace
  2442. * @vma: user vma to map to
  2443. * @addr: target page aligned user address to start at
  2444. * @pfn: page frame number of kernel physical memory address
  2445. * @size: size of mapping area
  2446. * @prot: page protection flags for this mapping
  2447. *
  2448. * Note: this is only safe if the mm semaphore is held when called.
  2449. *
  2450. * Return: %0 on success, negative error code otherwise.
  2451. */
  2452. int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
  2453. unsigned long pfn, unsigned long size, pgprot_t prot)
  2454. {
  2455. int err;
  2456. err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
  2457. if (err)
  2458. return -EINVAL;
  2459. err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
  2460. if (err)
  2461. untrack_pfn(vma, pfn, PAGE_ALIGN(size), true);
  2462. return err;
  2463. }
  2464. EXPORT_SYMBOL(remap_pfn_range);
  2465. /**
  2466. * vm_iomap_memory - remap memory to userspace
  2467. * @vma: user vma to map to
  2468. * @start: start of the physical memory to be mapped
  2469. * @len: size of area
  2470. *
  2471. * This is a simplified io_remap_pfn_range() for common driver use. The
  2472. * driver just needs to give us the physical memory range to be mapped,
  2473. * we'll figure out the rest from the vma information.
  2474. *
  2475. * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
  2476. * whatever write-combining details or similar.
  2477. *
  2478. * Return: %0 on success, negative error code otherwise.
  2479. */
  2480. int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
  2481. {
  2482. unsigned long vm_len, pfn, pages;
  2483. /* Check that the physical memory area passed in looks valid */
  2484. if (start + len < start)
  2485. return -EINVAL;
  2486. /*
  2487. * You *really* shouldn't map things that aren't page-aligned,
  2488. * but we've historically allowed it because IO memory might
  2489. * just have smaller alignment.
  2490. */
  2491. len += start & ~PAGE_MASK;
  2492. pfn = start >> PAGE_SHIFT;
  2493. pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
  2494. if (pfn + pages < pfn)
  2495. return -EINVAL;
  2496. /* We start the mapping 'vm_pgoff' pages into the area */
  2497. if (vma->vm_pgoff > pages)
  2498. return -EINVAL;
  2499. pfn += vma->vm_pgoff;
  2500. pages -= vma->vm_pgoff;
  2501. /* Can we fit all of the mapping? */
  2502. vm_len = vma->vm_end - vma->vm_start;
  2503. if (vm_len >> PAGE_SHIFT > pages)
  2504. return -EINVAL;
  2505. /* Ok, let it rip */
  2506. return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
  2507. }
  2508. EXPORT_SYMBOL(vm_iomap_memory);
  2509. static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
  2510. unsigned long addr, unsigned long end,
  2511. pte_fn_t fn, void *data, bool create,
  2512. pgtbl_mod_mask *mask)
  2513. {
  2514. pte_t *pte, *mapped_pte;
  2515. int err = 0;
  2516. spinlock_t *ptl;
  2517. if (create) {
  2518. mapped_pte = pte = (mm == &init_mm) ?
  2519. pte_alloc_kernel_track(pmd, addr, mask) :
  2520. pte_alloc_map_lock(mm, pmd, addr, &ptl);
  2521. if (!pte)
  2522. return -ENOMEM;
  2523. } else {
  2524. mapped_pte = pte = (mm == &init_mm) ?
  2525. pte_offset_kernel(pmd, addr) :
  2526. pte_offset_map_lock(mm, pmd, addr, &ptl);
  2527. if (!pte)
  2528. return -EINVAL;
  2529. }
  2530. arch_enter_lazy_mmu_mode();
  2531. if (fn) {
  2532. do {
  2533. if (create || !pte_none(ptep_get(pte))) {
  2534. err = fn(pte, addr, data);
  2535. if (err)
  2536. break;
  2537. }
  2538. } while (pte++, addr += PAGE_SIZE, addr != end);
  2539. }
  2540. *mask |= PGTBL_PTE_MODIFIED;
  2541. arch_leave_lazy_mmu_mode();
  2542. if (mm != &init_mm)
  2543. pte_unmap_unlock(mapped_pte, ptl);
  2544. return err;
  2545. }
  2546. static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
  2547. unsigned long addr, unsigned long end,
  2548. pte_fn_t fn, void *data, bool create,
  2549. pgtbl_mod_mask *mask)
  2550. {
  2551. pmd_t *pmd;
  2552. unsigned long next;
  2553. int err = 0;
  2554. BUG_ON(pud_leaf(*pud));
  2555. if (create) {
  2556. pmd = pmd_alloc_track(mm, pud, addr, mask);
  2557. if (!pmd)
  2558. return -ENOMEM;
  2559. } else {
  2560. pmd = pmd_offset(pud, addr);
  2561. }
  2562. do {
  2563. next = pmd_addr_end(addr, end);
  2564. if (pmd_none(*pmd) && !create)
  2565. continue;
  2566. if (WARN_ON_ONCE(pmd_leaf(*pmd)))
  2567. return -EINVAL;
  2568. if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
  2569. if (!create)
  2570. continue;
  2571. pmd_clear_bad(pmd);
  2572. }
  2573. err = apply_to_pte_range(mm, pmd, addr, next,
  2574. fn, data, create, mask);
  2575. if (err)
  2576. break;
  2577. } while (pmd++, addr = next, addr != end);
  2578. return err;
  2579. }
  2580. static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
  2581. unsigned long addr, unsigned long end,
  2582. pte_fn_t fn, void *data, bool create,
  2583. pgtbl_mod_mask *mask)
  2584. {
  2585. pud_t *pud;
  2586. unsigned long next;
  2587. int err = 0;
  2588. if (create) {
  2589. pud = pud_alloc_track(mm, p4d, addr, mask);
  2590. if (!pud)
  2591. return -ENOMEM;
  2592. } else {
  2593. pud = pud_offset(p4d, addr);
  2594. }
  2595. do {
  2596. next = pud_addr_end(addr, end);
  2597. if (pud_none(*pud) && !create)
  2598. continue;
  2599. if (WARN_ON_ONCE(pud_leaf(*pud)))
  2600. return -EINVAL;
  2601. if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
  2602. if (!create)
  2603. continue;
  2604. pud_clear_bad(pud);
  2605. }
  2606. err = apply_to_pmd_range(mm, pud, addr, next,
  2607. fn, data, create, mask);
  2608. if (err)
  2609. break;
  2610. } while (pud++, addr = next, addr != end);
  2611. return err;
  2612. }
  2613. static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
  2614. unsigned long addr, unsigned long end,
  2615. pte_fn_t fn, void *data, bool create,
  2616. pgtbl_mod_mask *mask)
  2617. {
  2618. p4d_t *p4d;
  2619. unsigned long next;
  2620. int err = 0;
  2621. if (create) {
  2622. p4d = p4d_alloc_track(mm, pgd, addr, mask);
  2623. if (!p4d)
  2624. return -ENOMEM;
  2625. } else {
  2626. p4d = p4d_offset(pgd, addr);
  2627. }
  2628. do {
  2629. next = p4d_addr_end(addr, end);
  2630. if (p4d_none(*p4d) && !create)
  2631. continue;
  2632. if (WARN_ON_ONCE(p4d_leaf(*p4d)))
  2633. return -EINVAL;
  2634. if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
  2635. if (!create)
  2636. continue;
  2637. p4d_clear_bad(p4d);
  2638. }
  2639. err = apply_to_pud_range(mm, p4d, addr, next,
  2640. fn, data, create, mask);
  2641. if (err)
  2642. break;
  2643. } while (p4d++, addr = next, addr != end);
  2644. return err;
  2645. }
  2646. static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
  2647. unsigned long size, pte_fn_t fn,
  2648. void *data, bool create)
  2649. {
  2650. pgd_t *pgd;
  2651. unsigned long start = addr, next;
  2652. unsigned long end = addr + size;
  2653. pgtbl_mod_mask mask = 0;
  2654. int err = 0;
  2655. if (WARN_ON(addr >= end))
  2656. return -EINVAL;
  2657. pgd = pgd_offset(mm, addr);
  2658. do {
  2659. next = pgd_addr_end(addr, end);
  2660. if (pgd_none(*pgd) && !create)
  2661. continue;
  2662. if (WARN_ON_ONCE(pgd_leaf(*pgd))) {
  2663. err = -EINVAL;
  2664. break;
  2665. }
  2666. if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
  2667. if (!create)
  2668. continue;
  2669. pgd_clear_bad(pgd);
  2670. }
  2671. err = apply_to_p4d_range(mm, pgd, addr, next,
  2672. fn, data, create, &mask);
  2673. if (err)
  2674. break;
  2675. } while (pgd++, addr = next, addr != end);
  2676. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  2677. arch_sync_kernel_mappings(start, start + size);
  2678. return err;
  2679. }
  2680. /*
  2681. * Scan a region of virtual memory, filling in page tables as necessary
  2682. * and calling a provided function on each leaf page table.
  2683. */
  2684. int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
  2685. unsigned long size, pte_fn_t fn, void *data)
  2686. {
  2687. return __apply_to_page_range(mm, addr, size, fn, data, true);
  2688. }
  2689. EXPORT_SYMBOL_GPL(apply_to_page_range);
  2690. /*
  2691. * Scan a region of virtual memory, calling a provided function on
  2692. * each leaf page table where it exists.
  2693. *
  2694. * Unlike apply_to_page_range, this does _not_ fill in page tables
  2695. * where they are absent.
  2696. */
  2697. int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
  2698. unsigned long size, pte_fn_t fn, void *data)
  2699. {
  2700. return __apply_to_page_range(mm, addr, size, fn, data, false);
  2701. }
  2702. EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
  2703. /*
  2704. * handle_pte_fault chooses page fault handler according to an entry which was
  2705. * read non-atomically. Before making any commitment, on those architectures
  2706. * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
  2707. * parts, do_swap_page must check under lock before unmapping the pte and
  2708. * proceeding (but do_wp_page is only called after already making such a check;
  2709. * and do_anonymous_page can safely check later on).
  2710. */
  2711. static inline int pte_unmap_same(struct vm_fault *vmf)
  2712. {
  2713. int same = 1;
  2714. #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
  2715. if (sizeof(pte_t) > sizeof(unsigned long)) {
  2716. spin_lock(vmf->ptl);
  2717. same = pte_same(ptep_get(vmf->pte), vmf->orig_pte);
  2718. spin_unlock(vmf->ptl);
  2719. }
  2720. #endif
  2721. pte_unmap(vmf->pte);
  2722. vmf->pte = NULL;
  2723. return same;
  2724. }
  2725. /*
  2726. * Return:
  2727. * 0: copied succeeded
  2728. * -EHWPOISON: copy failed due to hwpoison in source page
  2729. * -EAGAIN: copied failed (some other reason)
  2730. */
  2731. static inline int __wp_page_copy_user(struct page *dst, struct page *src,
  2732. struct vm_fault *vmf)
  2733. {
  2734. int ret;
  2735. void *kaddr;
  2736. void __user *uaddr;
  2737. struct vm_area_struct *vma = vmf->vma;
  2738. struct mm_struct *mm = vma->vm_mm;
  2739. unsigned long addr = vmf->address;
  2740. if (likely(src)) {
  2741. if (copy_mc_user_highpage(dst, src, addr, vma))
  2742. return -EHWPOISON;
  2743. return 0;
  2744. }
  2745. /*
  2746. * If the source page was a PFN mapping, we don't have
  2747. * a "struct page" for it. We do a best-effort copy by
  2748. * just copying from the original user address. If that
  2749. * fails, we just zero-fill it. Live with it.
  2750. */
  2751. kaddr = kmap_local_page(dst);
  2752. pagefault_disable();
  2753. uaddr = (void __user *)(addr & PAGE_MASK);
  2754. /*
  2755. * On architectures with software "accessed" bits, we would
  2756. * take a double page fault, so mark it accessed here.
  2757. */
  2758. vmf->pte = NULL;
  2759. if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) {
  2760. pte_t entry;
  2761. vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
  2762. if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
  2763. /*
  2764. * Other thread has already handled the fault
  2765. * and update local tlb only
  2766. */
  2767. if (vmf->pte)
  2768. update_mmu_tlb(vma, addr, vmf->pte);
  2769. ret = -EAGAIN;
  2770. goto pte_unlock;
  2771. }
  2772. entry = pte_mkyoung(vmf->orig_pte);
  2773. if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
  2774. update_mmu_cache_range(vmf, vma, addr, vmf->pte, 1);
  2775. }
  2776. /*
  2777. * This really shouldn't fail, because the page is there
  2778. * in the page tables. But it might just be unreadable,
  2779. * in which case we just give up and fill the result with
  2780. * zeroes.
  2781. */
  2782. if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
  2783. if (vmf->pte)
  2784. goto warn;
  2785. /* Re-validate under PTL if the page is still mapped */
  2786. vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
  2787. if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
  2788. /* The PTE changed under us, update local tlb */
  2789. if (vmf->pte)
  2790. update_mmu_tlb(vma, addr, vmf->pte);
  2791. ret = -EAGAIN;
  2792. goto pte_unlock;
  2793. }
  2794. /*
  2795. * The same page can be mapped back since last copy attempt.
  2796. * Try to copy again under PTL.
  2797. */
  2798. if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
  2799. /*
  2800. * Give a warn in case there can be some obscure
  2801. * use-case
  2802. */
  2803. warn:
  2804. WARN_ON_ONCE(1);
  2805. clear_page(kaddr);
  2806. }
  2807. }
  2808. ret = 0;
  2809. pte_unlock:
  2810. if (vmf->pte)
  2811. pte_unmap_unlock(vmf->pte, vmf->ptl);
  2812. pagefault_enable();
  2813. kunmap_local(kaddr);
  2814. flush_dcache_page(dst);
  2815. return ret;
  2816. }
  2817. static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
  2818. {
  2819. struct file *vm_file = vma->vm_file;
  2820. if (vm_file)
  2821. return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
  2822. /*
  2823. * Special mappings (e.g. VDSO) do not have any file so fake
  2824. * a default GFP_KERNEL for them.
  2825. */
  2826. return GFP_KERNEL;
  2827. }
  2828. /*
  2829. * Notify the address space that the page is about to become writable so that
  2830. * it can prohibit this or wait for the page to get into an appropriate state.
  2831. *
  2832. * We do this without the lock held, so that it can sleep if it needs to.
  2833. */
  2834. static vm_fault_t do_page_mkwrite(struct vm_fault *vmf, struct folio *folio)
  2835. {
  2836. vm_fault_t ret;
  2837. unsigned int old_flags = vmf->flags;
  2838. vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
  2839. if (vmf->vma->vm_file &&
  2840. IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
  2841. return VM_FAULT_SIGBUS;
  2842. ret = vmf->vma->vm_ops->page_mkwrite(vmf);
  2843. /* Restore original flags so that caller is not surprised */
  2844. vmf->flags = old_flags;
  2845. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
  2846. return ret;
  2847. if (unlikely(!(ret & VM_FAULT_LOCKED))) {
  2848. folio_lock(folio);
  2849. if (!folio->mapping) {
  2850. folio_unlock(folio);
  2851. return 0; /* retry */
  2852. }
  2853. ret |= VM_FAULT_LOCKED;
  2854. } else
  2855. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2856. return ret;
  2857. }
  2858. /*
  2859. * Handle dirtying of a page in shared file mapping on a write fault.
  2860. *
  2861. * The function expects the page to be locked and unlocks it.
  2862. */
  2863. static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
  2864. {
  2865. struct vm_area_struct *vma = vmf->vma;
  2866. struct address_space *mapping;
  2867. struct folio *folio = page_folio(vmf->page);
  2868. bool dirtied;
  2869. bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
  2870. dirtied = folio_mark_dirty(folio);
  2871. VM_BUG_ON_FOLIO(folio_test_anon(folio), folio);
  2872. /*
  2873. * Take a local copy of the address_space - folio.mapping may be zeroed
  2874. * by truncate after folio_unlock(). The address_space itself remains
  2875. * pinned by vma->vm_file's reference. We rely on folio_unlock()'s
  2876. * release semantics to prevent the compiler from undoing this copying.
  2877. */
  2878. mapping = folio_raw_mapping(folio);
  2879. folio_unlock(folio);
  2880. if (!page_mkwrite)
  2881. file_update_time(vma->vm_file);
  2882. /*
  2883. * Throttle page dirtying rate down to writeback speed.
  2884. *
  2885. * mapping may be NULL here because some device drivers do not
  2886. * set page.mapping but still dirty their pages
  2887. *
  2888. * Drop the mmap_lock before waiting on IO, if we can. The file
  2889. * is pinning the mapping, as per above.
  2890. */
  2891. if ((dirtied || page_mkwrite) && mapping) {
  2892. struct file *fpin;
  2893. fpin = maybe_unlock_mmap_for_io(vmf, NULL);
  2894. balance_dirty_pages_ratelimited(mapping);
  2895. if (fpin) {
  2896. fput(fpin);
  2897. return VM_FAULT_COMPLETED;
  2898. }
  2899. }
  2900. return 0;
  2901. }
  2902. /*
  2903. * Handle write page faults for pages that can be reused in the current vma
  2904. *
  2905. * This can happen either due to the mapping being with the VM_SHARED flag,
  2906. * or due to us being the last reference standing to the page. In either
  2907. * case, all we need to do here is to mark the page as writable and update
  2908. * any related book-keeping.
  2909. */
  2910. static inline void wp_page_reuse(struct vm_fault *vmf, struct folio *folio)
  2911. __releases(vmf->ptl)
  2912. {
  2913. struct vm_area_struct *vma = vmf->vma;
  2914. pte_t entry;
  2915. VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
  2916. VM_WARN_ON(is_zero_pfn(pte_pfn(vmf->orig_pte)));
  2917. if (folio) {
  2918. VM_BUG_ON(folio_test_anon(folio) &&
  2919. !PageAnonExclusive(vmf->page));
  2920. /*
  2921. * Clear the folio's cpupid information as the existing
  2922. * information potentially belongs to a now completely
  2923. * unrelated process.
  2924. */
  2925. folio_xchg_last_cpupid(folio, (1 << LAST_CPUPID_SHIFT) - 1);
  2926. }
  2927. flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
  2928. entry = pte_mkyoung(vmf->orig_pte);
  2929. entry = maybe_mkwrite(pte_mkdirty(entry), vma);
  2930. if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
  2931. update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
  2932. pte_unmap_unlock(vmf->pte, vmf->ptl);
  2933. count_vm_event(PGREUSE);
  2934. }
  2935. /*
  2936. * We could add a bitflag somewhere, but for now, we know that all
  2937. * vm_ops that have a ->map_pages have been audited and don't need
  2938. * the mmap_lock to be held.
  2939. */
  2940. static inline vm_fault_t vmf_can_call_fault(const struct vm_fault *vmf)
  2941. {
  2942. struct vm_area_struct *vma = vmf->vma;
  2943. if (vma->vm_ops->map_pages || !(vmf->flags & FAULT_FLAG_VMA_LOCK))
  2944. return 0;
  2945. vma_end_read(vma);
  2946. return VM_FAULT_RETRY;
  2947. }
  2948. /**
  2949. * __vmf_anon_prepare - Prepare to handle an anonymous fault.
  2950. * @vmf: The vm_fault descriptor passed from the fault handler.
  2951. *
  2952. * When preparing to insert an anonymous page into a VMA from a
  2953. * fault handler, call this function rather than anon_vma_prepare().
  2954. * If this vma does not already have an associated anon_vma and we are
  2955. * only protected by the per-VMA lock, the caller must retry with the
  2956. * mmap_lock held. __anon_vma_prepare() will look at adjacent VMAs to
  2957. * determine if this VMA can share its anon_vma, and that's not safe to
  2958. * do with only the per-VMA lock held for this VMA.
  2959. *
  2960. * Return: 0 if fault handling can proceed. Any other value should be
  2961. * returned to the caller.
  2962. */
  2963. vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)
  2964. {
  2965. struct vm_area_struct *vma = vmf->vma;
  2966. vm_fault_t ret = 0;
  2967. if (likely(vma->anon_vma))
  2968. return 0;
  2969. if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
  2970. if (!mmap_read_trylock(vma->vm_mm))
  2971. return VM_FAULT_RETRY;
  2972. }
  2973. if (__anon_vma_prepare(vma))
  2974. ret = VM_FAULT_OOM;
  2975. if (vmf->flags & FAULT_FLAG_VMA_LOCK)
  2976. mmap_read_unlock(vma->vm_mm);
  2977. return ret;
  2978. }
  2979. /*
  2980. * Handle the case of a page which we actually need to copy to a new page,
  2981. * either due to COW or unsharing.
  2982. *
  2983. * Called with mmap_lock locked and the old page referenced, but
  2984. * without the ptl held.
  2985. *
  2986. * High level logic flow:
  2987. *
  2988. * - Allocate a page, copy the content of the old page to the new one.
  2989. * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
  2990. * - Take the PTL. If the pte changed, bail out and release the allocated page
  2991. * - If the pte is still the way we remember it, update the page table and all
  2992. * relevant references. This includes dropping the reference the page-table
  2993. * held to the old page, as well as updating the rmap.
  2994. * - In any case, unlock the PTL and drop the reference we took to the old page.
  2995. */
  2996. static vm_fault_t wp_page_copy(struct vm_fault *vmf)
  2997. {
  2998. const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
  2999. struct vm_area_struct *vma = vmf->vma;
  3000. struct mm_struct *mm = vma->vm_mm;
  3001. struct folio *old_folio = NULL;
  3002. struct folio *new_folio = NULL;
  3003. pte_t entry;
  3004. int page_copied = 0;
  3005. struct mmu_notifier_range range;
  3006. vm_fault_t ret;
  3007. bool pfn_is_zero;
  3008. delayacct_wpcopy_start();
  3009. if (vmf->page)
  3010. old_folio = page_folio(vmf->page);
  3011. ret = vmf_anon_prepare(vmf);
  3012. if (unlikely(ret))
  3013. goto out;
  3014. pfn_is_zero = is_zero_pfn(pte_pfn(vmf->orig_pte));
  3015. new_folio = folio_prealloc(mm, vma, vmf->address, pfn_is_zero);
  3016. if (!new_folio)
  3017. goto oom;
  3018. if (!pfn_is_zero) {
  3019. int err;
  3020. err = __wp_page_copy_user(&new_folio->page, vmf->page, vmf);
  3021. if (err) {
  3022. /*
  3023. * COW failed, if the fault was solved by other,
  3024. * it's fine. If not, userspace would re-fault on
  3025. * the same address and we will handle the fault
  3026. * from the second attempt.
  3027. * The -EHWPOISON case will not be retried.
  3028. */
  3029. folio_put(new_folio);
  3030. if (old_folio)
  3031. folio_put(old_folio);
  3032. delayacct_wpcopy_end();
  3033. return err == -EHWPOISON ? VM_FAULT_HWPOISON : 0;
  3034. }
  3035. kmsan_copy_page_meta(&new_folio->page, vmf->page);
  3036. }
  3037. __folio_mark_uptodate(new_folio);
  3038. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
  3039. vmf->address & PAGE_MASK,
  3040. (vmf->address & PAGE_MASK) + PAGE_SIZE);
  3041. mmu_notifier_invalidate_range_start(&range);
  3042. /*
  3043. * Re-check the pte - we dropped the lock
  3044. */
  3045. vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
  3046. if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
  3047. if (old_folio) {
  3048. if (!folio_test_anon(old_folio)) {
  3049. dec_mm_counter(mm, mm_counter_file(old_folio));
  3050. inc_mm_counter(mm, MM_ANONPAGES);
  3051. }
  3052. } else {
  3053. ksm_might_unmap_zero_page(mm, vmf->orig_pte);
  3054. inc_mm_counter(mm, MM_ANONPAGES);
  3055. }
  3056. flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
  3057. entry = mk_pte(&new_folio->page, vma->vm_page_prot);
  3058. entry = pte_sw_mkyoung(entry);
  3059. if (unlikely(unshare)) {
  3060. if (pte_soft_dirty(vmf->orig_pte))
  3061. entry = pte_mksoft_dirty(entry);
  3062. if (pte_uffd_wp(vmf->orig_pte))
  3063. entry = pte_mkuffd_wp(entry);
  3064. } else {
  3065. entry = maybe_mkwrite(pte_mkdirty(entry), vma);
  3066. }
  3067. /*
  3068. * Clear the pte entry and flush it first, before updating the
  3069. * pte with the new entry, to keep TLBs on different CPUs in
  3070. * sync. This code used to set the new PTE then flush TLBs, but
  3071. * that left a window where the new PTE could be loaded into
  3072. * some TLBs while the old PTE remains in others.
  3073. */
  3074. ptep_clear_flush(vma, vmf->address, vmf->pte);
  3075. folio_add_new_anon_rmap(new_folio, vma, vmf->address, RMAP_EXCLUSIVE);
  3076. folio_add_lru_vma(new_folio, vma);
  3077. BUG_ON(unshare && pte_write(entry));
  3078. set_pte_at(mm, vmf->address, vmf->pte, entry);
  3079. update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
  3080. if (old_folio) {
  3081. /*
  3082. * Only after switching the pte to the new page may
  3083. * we remove the mapcount here. Otherwise another
  3084. * process may come and find the rmap count decremented
  3085. * before the pte is switched to the new page, and
  3086. * "reuse" the old page writing into it while our pte
  3087. * here still points into it and can be read by other
  3088. * threads.
  3089. *
  3090. * The critical issue is to order this
  3091. * folio_remove_rmap_pte() with the ptp_clear_flush
  3092. * above. Those stores are ordered by (if nothing else,)
  3093. * the barrier present in the atomic_add_negative
  3094. * in folio_remove_rmap_pte();
  3095. *
  3096. * Then the TLB flush in ptep_clear_flush ensures that
  3097. * no process can access the old page before the
  3098. * decremented mapcount is visible. And the old page
  3099. * cannot be reused until after the decremented
  3100. * mapcount is visible. So transitively, TLBs to
  3101. * old page will be flushed before it can be reused.
  3102. */
  3103. folio_remove_rmap_pte(old_folio, vmf->page, vma);
  3104. }
  3105. /* Free the old page.. */
  3106. new_folio = old_folio;
  3107. page_copied = 1;
  3108. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3109. } else if (vmf->pte) {
  3110. update_mmu_tlb(vma, vmf->address, vmf->pte);
  3111. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3112. }
  3113. mmu_notifier_invalidate_range_end(&range);
  3114. if (new_folio)
  3115. folio_put(new_folio);
  3116. if (old_folio) {
  3117. if (page_copied)
  3118. free_swap_cache(old_folio);
  3119. folio_put(old_folio);
  3120. }
  3121. delayacct_wpcopy_end();
  3122. return 0;
  3123. oom:
  3124. ret = VM_FAULT_OOM;
  3125. out:
  3126. if (old_folio)
  3127. folio_put(old_folio);
  3128. delayacct_wpcopy_end();
  3129. return ret;
  3130. }
  3131. /**
  3132. * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
  3133. * writeable once the page is prepared
  3134. *
  3135. * @vmf: structure describing the fault
  3136. * @folio: the folio of vmf->page
  3137. *
  3138. * This function handles all that is needed to finish a write page fault in a
  3139. * shared mapping due to PTE being read-only once the mapped page is prepared.
  3140. * It handles locking of PTE and modifying it.
  3141. *
  3142. * The function expects the page to be locked or other protection against
  3143. * concurrent faults / writeback (such as DAX radix tree locks).
  3144. *
  3145. * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
  3146. * we acquired PTE lock.
  3147. */
  3148. static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio)
  3149. {
  3150. WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
  3151. vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
  3152. &vmf->ptl);
  3153. if (!vmf->pte)
  3154. return VM_FAULT_NOPAGE;
  3155. /*
  3156. * We might have raced with another page fault while we released the
  3157. * pte_offset_map_lock.
  3158. */
  3159. if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) {
  3160. update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
  3161. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3162. return VM_FAULT_NOPAGE;
  3163. }
  3164. wp_page_reuse(vmf, folio);
  3165. return 0;
  3166. }
  3167. /*
  3168. * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
  3169. * mapping
  3170. */
  3171. static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
  3172. {
  3173. struct vm_area_struct *vma = vmf->vma;
  3174. if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
  3175. vm_fault_t ret;
  3176. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3177. ret = vmf_can_call_fault(vmf);
  3178. if (ret)
  3179. return ret;
  3180. vmf->flags |= FAULT_FLAG_MKWRITE;
  3181. ret = vma->vm_ops->pfn_mkwrite(vmf);
  3182. if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
  3183. return ret;
  3184. return finish_mkwrite_fault(vmf, NULL);
  3185. }
  3186. wp_page_reuse(vmf, NULL);
  3187. return 0;
  3188. }
  3189. static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio)
  3190. __releases(vmf->ptl)
  3191. {
  3192. struct vm_area_struct *vma = vmf->vma;
  3193. vm_fault_t ret = 0;
  3194. folio_get(folio);
  3195. if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
  3196. vm_fault_t tmp;
  3197. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3198. tmp = vmf_can_call_fault(vmf);
  3199. if (tmp) {
  3200. folio_put(folio);
  3201. return tmp;
  3202. }
  3203. tmp = do_page_mkwrite(vmf, folio);
  3204. if (unlikely(!tmp || (tmp &
  3205. (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
  3206. folio_put(folio);
  3207. return tmp;
  3208. }
  3209. tmp = finish_mkwrite_fault(vmf, folio);
  3210. if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
  3211. folio_unlock(folio);
  3212. folio_put(folio);
  3213. return tmp;
  3214. }
  3215. } else {
  3216. wp_page_reuse(vmf, folio);
  3217. folio_lock(folio);
  3218. }
  3219. ret |= fault_dirty_shared_page(vmf);
  3220. folio_put(folio);
  3221. return ret;
  3222. }
  3223. static bool wp_can_reuse_anon_folio(struct folio *folio,
  3224. struct vm_area_struct *vma)
  3225. {
  3226. /*
  3227. * We could currently only reuse a subpage of a large folio if no
  3228. * other subpages of the large folios are still mapped. However,
  3229. * let's just consistently not reuse subpages even if we could
  3230. * reuse in that scenario, and give back a large folio a bit
  3231. * sooner.
  3232. */
  3233. if (folio_test_large(folio))
  3234. return false;
  3235. /*
  3236. * We have to verify under folio lock: these early checks are
  3237. * just an optimization to avoid locking the folio and freeing
  3238. * the swapcache if there is little hope that we can reuse.
  3239. *
  3240. * KSM doesn't necessarily raise the folio refcount.
  3241. */
  3242. if (folio_test_ksm(folio) || folio_ref_count(folio) > 3)
  3243. return false;
  3244. if (!folio_test_lru(folio))
  3245. /*
  3246. * We cannot easily detect+handle references from
  3247. * remote LRU caches or references to LRU folios.
  3248. */
  3249. lru_add_drain();
  3250. if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio))
  3251. return false;
  3252. if (!folio_trylock(folio))
  3253. return false;
  3254. if (folio_test_swapcache(folio))
  3255. folio_free_swap(folio);
  3256. if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
  3257. folio_unlock(folio);
  3258. return false;
  3259. }
  3260. /*
  3261. * Ok, we've got the only folio reference from our mapping
  3262. * and the folio is locked, it's dark out, and we're wearing
  3263. * sunglasses. Hit it.
  3264. */
  3265. folio_move_anon_rmap(folio, vma);
  3266. folio_unlock(folio);
  3267. return true;
  3268. }
  3269. /*
  3270. * This routine handles present pages, when
  3271. * * users try to write to a shared page (FAULT_FLAG_WRITE)
  3272. * * GUP wants to take a R/O pin on a possibly shared anonymous page
  3273. * (FAULT_FLAG_UNSHARE)
  3274. *
  3275. * It is done by copying the page to a new address and decrementing the
  3276. * shared-page counter for the old page.
  3277. *
  3278. * Note that this routine assumes that the protection checks have been
  3279. * done by the caller (the low-level page fault routine in most cases).
  3280. * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
  3281. * done any necessary COW.
  3282. *
  3283. * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
  3284. * though the page will change only once the write actually happens. This
  3285. * avoids a few races, and potentially makes it more efficient.
  3286. *
  3287. * We enter with non-exclusive mmap_lock (to exclude vma changes,
  3288. * but allow concurrent faults), with pte both mapped and locked.
  3289. * We return with mmap_lock still held, but pte unmapped and unlocked.
  3290. */
  3291. static vm_fault_t do_wp_page(struct vm_fault *vmf)
  3292. __releases(vmf->ptl)
  3293. {
  3294. const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
  3295. struct vm_area_struct *vma = vmf->vma;
  3296. struct folio *folio = NULL;
  3297. pte_t pte;
  3298. if (likely(!unshare)) {
  3299. if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) {
  3300. if (!userfaultfd_wp_async(vma)) {
  3301. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3302. return handle_userfault(vmf, VM_UFFD_WP);
  3303. }
  3304. /*
  3305. * Nothing needed (cache flush, TLB invalidations,
  3306. * etc.) because we're only removing the uffd-wp bit,
  3307. * which is completely invisible to the user.
  3308. */
  3309. pte = pte_clear_uffd_wp(ptep_get(vmf->pte));
  3310. set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
  3311. /*
  3312. * Update this to be prepared for following up CoW
  3313. * handling
  3314. */
  3315. vmf->orig_pte = pte;
  3316. }
  3317. /*
  3318. * Userfaultfd write-protect can defer flushes. Ensure the TLB
  3319. * is flushed in this case before copying.
  3320. */
  3321. if (unlikely(userfaultfd_wp(vmf->vma) &&
  3322. mm_tlb_flush_pending(vmf->vma->vm_mm)))
  3323. flush_tlb_page(vmf->vma, vmf->address);
  3324. }
  3325. vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
  3326. if (vmf->page)
  3327. folio = page_folio(vmf->page);
  3328. /*
  3329. * Shared mapping: we are guaranteed to have VM_WRITE and
  3330. * FAULT_FLAG_WRITE set at this point.
  3331. */
  3332. if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
  3333. /*
  3334. * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
  3335. * VM_PFNMAP VMA.
  3336. *
  3337. * We should not cow pages in a shared writeable mapping.
  3338. * Just mark the pages writable and/or call ops->pfn_mkwrite.
  3339. */
  3340. if (!vmf->page)
  3341. return wp_pfn_shared(vmf);
  3342. return wp_page_shared(vmf, folio);
  3343. }
  3344. /*
  3345. * Private mapping: create an exclusive anonymous page copy if reuse
  3346. * is impossible. We might miss VM_WRITE for FOLL_FORCE handling.
  3347. *
  3348. * If we encounter a page that is marked exclusive, we must reuse
  3349. * the page without further checks.
  3350. */
  3351. if (folio && folio_test_anon(folio) &&
  3352. (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) {
  3353. if (!PageAnonExclusive(vmf->page))
  3354. SetPageAnonExclusive(vmf->page);
  3355. if (unlikely(unshare)) {
  3356. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3357. return 0;
  3358. }
  3359. wp_page_reuse(vmf, folio);
  3360. return 0;
  3361. }
  3362. /*
  3363. * Ok, we need to copy. Oh, well..
  3364. */
  3365. if (folio)
  3366. folio_get(folio);
  3367. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3368. #ifdef CONFIG_KSM
  3369. if (folio && folio_test_ksm(folio))
  3370. count_vm_event(COW_KSM);
  3371. #endif
  3372. return wp_page_copy(vmf);
  3373. }
  3374. static void unmap_mapping_range_vma(struct vm_area_struct *vma,
  3375. unsigned long start_addr, unsigned long end_addr,
  3376. struct zap_details *details)
  3377. {
  3378. zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
  3379. }
  3380. static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
  3381. pgoff_t first_index,
  3382. pgoff_t last_index,
  3383. struct zap_details *details)
  3384. {
  3385. struct vm_area_struct *vma;
  3386. pgoff_t vba, vea, zba, zea;
  3387. vma_interval_tree_foreach(vma, root, first_index, last_index) {
  3388. vba = vma->vm_pgoff;
  3389. vea = vba + vma_pages(vma) - 1;
  3390. zba = max(first_index, vba);
  3391. zea = min(last_index, vea);
  3392. unmap_mapping_range_vma(vma,
  3393. ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
  3394. ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
  3395. details);
  3396. }
  3397. }
  3398. /**
  3399. * unmap_mapping_folio() - Unmap single folio from processes.
  3400. * @folio: The locked folio to be unmapped.
  3401. *
  3402. * Unmap this folio from any userspace process which still has it mmaped.
  3403. * Typically, for efficiency, the range of nearby pages has already been
  3404. * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
  3405. * truncation or invalidation holds the lock on a folio, it may find that
  3406. * the page has been remapped again: and then uses unmap_mapping_folio()
  3407. * to unmap it finally.
  3408. */
  3409. void unmap_mapping_folio(struct folio *folio)
  3410. {
  3411. struct address_space *mapping = folio->mapping;
  3412. struct zap_details details = { };
  3413. pgoff_t first_index;
  3414. pgoff_t last_index;
  3415. VM_BUG_ON(!folio_test_locked(folio));
  3416. first_index = folio->index;
  3417. last_index = folio_next_index(folio) - 1;
  3418. details.even_cows = false;
  3419. details.single_folio = folio;
  3420. details.zap_flags = ZAP_FLAG_DROP_MARKER;
  3421. i_mmap_lock_read(mapping);
  3422. if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
  3423. unmap_mapping_range_tree(&mapping->i_mmap, first_index,
  3424. last_index, &details);
  3425. i_mmap_unlock_read(mapping);
  3426. }
  3427. /**
  3428. * unmap_mapping_pages() - Unmap pages from processes.
  3429. * @mapping: The address space containing pages to be unmapped.
  3430. * @start: Index of first page to be unmapped.
  3431. * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
  3432. * @even_cows: Whether to unmap even private COWed pages.
  3433. *
  3434. * Unmap the pages in this address space from any userspace process which
  3435. * has them mmaped. Generally, you want to remove COWed pages as well when
  3436. * a file is being truncated, but not when invalidating pages from the page
  3437. * cache.
  3438. */
  3439. void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
  3440. pgoff_t nr, bool even_cows)
  3441. {
  3442. struct zap_details details = { };
  3443. pgoff_t first_index = start;
  3444. pgoff_t last_index = start + nr - 1;
  3445. details.even_cows = even_cows;
  3446. if (last_index < first_index)
  3447. last_index = ULONG_MAX;
  3448. i_mmap_lock_read(mapping);
  3449. if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
  3450. unmap_mapping_range_tree(&mapping->i_mmap, first_index,
  3451. last_index, &details);
  3452. i_mmap_unlock_read(mapping);
  3453. }
  3454. EXPORT_SYMBOL_GPL(unmap_mapping_pages);
  3455. /**
  3456. * unmap_mapping_range - unmap the portion of all mmaps in the specified
  3457. * address_space corresponding to the specified byte range in the underlying
  3458. * file.
  3459. *
  3460. * @mapping: the address space containing mmaps to be unmapped.
  3461. * @holebegin: byte in first page to unmap, relative to the start of
  3462. * the underlying file. This will be rounded down to a PAGE_SIZE
  3463. * boundary. Note that this is different from truncate_pagecache(), which
  3464. * must keep the partial page. In contrast, we must get rid of
  3465. * partial pages.
  3466. * @holelen: size of prospective hole in bytes. This will be rounded
  3467. * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
  3468. * end of the file.
  3469. * @even_cows: 1 when truncating a file, unmap even private COWed pages;
  3470. * but 0 when invalidating pagecache, don't throw away private data.
  3471. */
  3472. void unmap_mapping_range(struct address_space *mapping,
  3473. loff_t const holebegin, loff_t const holelen, int even_cows)
  3474. {
  3475. pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT;
  3476. pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT;
  3477. /* Check for overflow. */
  3478. if (sizeof(holelen) > sizeof(hlen)) {
  3479. long long holeend =
  3480. (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
  3481. if (holeend & ~(long long)ULONG_MAX)
  3482. hlen = ULONG_MAX - hba + 1;
  3483. }
  3484. unmap_mapping_pages(mapping, hba, hlen, even_cows);
  3485. }
  3486. EXPORT_SYMBOL(unmap_mapping_range);
  3487. /*
  3488. * Restore a potential device exclusive pte to a working pte entry
  3489. */
  3490. static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
  3491. {
  3492. struct folio *folio = page_folio(vmf->page);
  3493. struct vm_area_struct *vma = vmf->vma;
  3494. struct mmu_notifier_range range;
  3495. vm_fault_t ret;
  3496. /*
  3497. * We need a reference to lock the folio because we don't hold
  3498. * the PTL so a racing thread can remove the device-exclusive
  3499. * entry and unmap it. If the folio is free the entry must
  3500. * have been removed already. If it happens to have already
  3501. * been re-allocated after being freed all we do is lock and
  3502. * unlock it.
  3503. */
  3504. if (!folio_try_get(folio))
  3505. return 0;
  3506. ret = folio_lock_or_retry(folio, vmf);
  3507. if (ret) {
  3508. folio_put(folio);
  3509. return ret;
  3510. }
  3511. mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0,
  3512. vma->vm_mm, vmf->address & PAGE_MASK,
  3513. (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
  3514. mmu_notifier_invalidate_range_start(&range);
  3515. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
  3516. &vmf->ptl);
  3517. if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
  3518. restore_exclusive_pte(vma, vmf->page, vmf->address, vmf->pte);
  3519. if (vmf->pte)
  3520. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3521. folio_unlock(folio);
  3522. folio_put(folio);
  3523. mmu_notifier_invalidate_range_end(&range);
  3524. return 0;
  3525. }
  3526. static inline bool should_try_to_free_swap(struct folio *folio,
  3527. struct vm_area_struct *vma,
  3528. unsigned int fault_flags)
  3529. {
  3530. if (!folio_test_swapcache(folio))
  3531. return false;
  3532. if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
  3533. folio_test_mlocked(folio))
  3534. return true;
  3535. /*
  3536. * If we want to map a page that's in the swapcache writable, we
  3537. * have to detect via the refcount if we're really the exclusive
  3538. * user. Try freeing the swapcache to get rid of the swapcache
  3539. * reference only in case it's likely that we'll be the exlusive user.
  3540. */
  3541. return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) &&
  3542. folio_ref_count(folio) == (1 + folio_nr_pages(folio));
  3543. }
  3544. static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
  3545. {
  3546. vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
  3547. vmf->address, &vmf->ptl);
  3548. if (!vmf->pte)
  3549. return 0;
  3550. /*
  3551. * Be careful so that we will only recover a special uffd-wp pte into a
  3552. * none pte. Otherwise it means the pte could have changed, so retry.
  3553. *
  3554. * This should also cover the case where e.g. the pte changed
  3555. * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED.
  3556. * So is_pte_marker() check is not enough to safely drop the pte.
  3557. */
  3558. if (pte_same(vmf->orig_pte, ptep_get(vmf->pte)))
  3559. pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
  3560. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3561. return 0;
  3562. }
  3563. static vm_fault_t do_pte_missing(struct vm_fault *vmf)
  3564. {
  3565. if (vma_is_anonymous(vmf->vma))
  3566. return do_anonymous_page(vmf);
  3567. else
  3568. return do_fault(vmf);
  3569. }
  3570. /*
  3571. * This is actually a page-missing access, but with uffd-wp special pte
  3572. * installed. It means this pte was wr-protected before being unmapped.
  3573. */
  3574. static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
  3575. {
  3576. /*
  3577. * Just in case there're leftover special ptes even after the region
  3578. * got unregistered - we can simply clear them.
  3579. */
  3580. if (unlikely(!userfaultfd_wp(vmf->vma)))
  3581. return pte_marker_clear(vmf);
  3582. return do_pte_missing(vmf);
  3583. }
  3584. static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
  3585. {
  3586. swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
  3587. unsigned long marker = pte_marker_get(entry);
  3588. /*
  3589. * PTE markers should never be empty. If anything weird happened,
  3590. * the best thing to do is to kill the process along with its mm.
  3591. */
  3592. if (WARN_ON_ONCE(!marker))
  3593. return VM_FAULT_SIGBUS;
  3594. /* Higher priority than uffd-wp when data corrupted */
  3595. if (marker & PTE_MARKER_POISONED)
  3596. return VM_FAULT_HWPOISON;
  3597. if (pte_marker_entry_uffd_wp(entry))
  3598. return pte_marker_handle_uffd_wp(vmf);
  3599. /* This is an unknown pte marker */
  3600. return VM_FAULT_SIGBUS;
  3601. }
  3602. static struct folio *__alloc_swap_folio(struct vm_fault *vmf)
  3603. {
  3604. struct vm_area_struct *vma = vmf->vma;
  3605. struct folio *folio;
  3606. swp_entry_t entry;
  3607. folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma,
  3608. vmf->address, false);
  3609. if (!folio)
  3610. return NULL;
  3611. entry = pte_to_swp_entry(vmf->orig_pte);
  3612. if (mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
  3613. GFP_KERNEL, entry)) {
  3614. folio_put(folio);
  3615. return NULL;
  3616. }
  3617. return folio;
  3618. }
  3619. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3620. static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
  3621. {
  3622. struct swap_info_struct *si = swp_swap_info(entry);
  3623. pgoff_t offset = swp_offset(entry);
  3624. int i;
  3625. /*
  3626. * While allocating a large folio and doing swap_read_folio, which is
  3627. * the case the being faulted pte doesn't have swapcache. We need to
  3628. * ensure all PTEs have no cache as well, otherwise, we might go to
  3629. * swap devices while the content is in swapcache.
  3630. */
  3631. for (i = 0; i < max_nr; i++) {
  3632. if ((si->swap_map[offset + i] & SWAP_HAS_CACHE))
  3633. return i;
  3634. }
  3635. return i;
  3636. }
  3637. /*
  3638. * Check if the PTEs within a range are contiguous swap entries
  3639. * and have consistent swapcache, zeromap.
  3640. */
  3641. static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)
  3642. {
  3643. unsigned long addr;
  3644. swp_entry_t entry;
  3645. int idx;
  3646. pte_t pte;
  3647. addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
  3648. idx = (vmf->address - addr) / PAGE_SIZE;
  3649. pte = ptep_get(ptep);
  3650. if (!pte_same(pte, pte_move_swp_offset(vmf->orig_pte, -idx)))
  3651. return false;
  3652. entry = pte_to_swp_entry(pte);
  3653. if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages)
  3654. return false;
  3655. /*
  3656. * swap_read_folio() can't handle the case a large folio is hybridly
  3657. * from different backends. And they are likely corner cases. Similar
  3658. * things might be added once zswap support large folios.
  3659. */
  3660. if (unlikely(swap_zeromap_batch(entry, nr_pages, NULL) != nr_pages))
  3661. return false;
  3662. if (unlikely(non_swapcache_batch(entry, nr_pages) != nr_pages))
  3663. return false;
  3664. return true;
  3665. }
  3666. static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,
  3667. unsigned long addr,
  3668. unsigned long orders)
  3669. {
  3670. int order, nr;
  3671. order = highest_order(orders);
  3672. /*
  3673. * To swap in a THP with nr pages, we require that its first swap_offset
  3674. * is aligned with that number, as it was when the THP was swapped out.
  3675. * This helps filter out most invalid entries.
  3676. */
  3677. while (orders) {
  3678. nr = 1 << order;
  3679. if ((addr >> PAGE_SHIFT) % nr == swp_offset % nr)
  3680. break;
  3681. order = next_order(&orders, order);
  3682. }
  3683. return orders;
  3684. }
  3685. static struct folio *alloc_swap_folio(struct vm_fault *vmf)
  3686. {
  3687. struct vm_area_struct *vma = vmf->vma;
  3688. unsigned long orders;
  3689. struct folio *folio;
  3690. unsigned long addr;
  3691. swp_entry_t entry;
  3692. spinlock_t *ptl;
  3693. pte_t *pte;
  3694. gfp_t gfp;
  3695. int order;
  3696. /*
  3697. * If uffd is active for the vma we need per-page fault fidelity to
  3698. * maintain the uffd semantics.
  3699. */
  3700. if (unlikely(userfaultfd_armed(vma)))
  3701. goto fallback;
  3702. /*
  3703. * A large swapped out folio could be partially or fully in zswap. We
  3704. * lack handling for such cases, so fallback to swapping in order-0
  3705. * folio.
  3706. */
  3707. if (!zswap_never_enabled())
  3708. goto fallback;
  3709. entry = pte_to_swp_entry(vmf->orig_pte);
  3710. /*
  3711. * Get a list of all the (large) orders below PMD_ORDER that are enabled
  3712. * and suitable for swapping THP.
  3713. */
  3714. orders = thp_vma_allowable_orders(vma, vma->vm_flags,
  3715. TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
  3716. orders = thp_vma_suitable_orders(vma, vmf->address, orders);
  3717. orders = thp_swap_suitable_orders(swp_offset(entry),
  3718. vmf->address, orders);
  3719. if (!orders)
  3720. goto fallback;
  3721. pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
  3722. vmf->address & PMD_MASK, &ptl);
  3723. if (unlikely(!pte))
  3724. goto fallback;
  3725. /*
  3726. * For do_swap_page, find the highest order where the aligned range is
  3727. * completely swap entries with contiguous swap offsets.
  3728. */
  3729. order = highest_order(orders);
  3730. while (orders) {
  3731. addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
  3732. if (can_swapin_thp(vmf, pte + pte_index(addr), 1 << order))
  3733. break;
  3734. order = next_order(&orders, order);
  3735. }
  3736. pte_unmap_unlock(pte, ptl);
  3737. /* Try allocating the highest of the remaining orders. */
  3738. gfp = vma_thp_gfp_mask(vma);
  3739. while (orders) {
  3740. addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
  3741. folio = vma_alloc_folio(gfp, order, vma, addr, true);
  3742. if (folio) {
  3743. if (!mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
  3744. gfp, entry))
  3745. return folio;
  3746. folio_put(folio);
  3747. }
  3748. order = next_order(&orders, order);
  3749. }
  3750. fallback:
  3751. return __alloc_swap_folio(vmf);
  3752. }
  3753. #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
  3754. static struct folio *alloc_swap_folio(struct vm_fault *vmf)
  3755. {
  3756. return __alloc_swap_folio(vmf);
  3757. }
  3758. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  3759. static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);
  3760. /*
  3761. * We enter with non-exclusive mmap_lock (to exclude vma changes,
  3762. * but allow concurrent faults), and pte mapped but not yet locked.
  3763. * We return with pte unmapped and unlocked.
  3764. *
  3765. * We return with the mmap_lock locked or unlocked in the same cases
  3766. * as does filemap_fault().
  3767. */
  3768. vm_fault_t do_swap_page(struct vm_fault *vmf)
  3769. {
  3770. struct vm_area_struct *vma = vmf->vma;
  3771. struct folio *swapcache, *folio = NULL;
  3772. DECLARE_WAITQUEUE(wait, current);
  3773. struct page *page;
  3774. struct swap_info_struct *si = NULL;
  3775. rmap_t rmap_flags = RMAP_NONE;
  3776. bool need_clear_cache = false;
  3777. bool exclusive = false;
  3778. swp_entry_t entry;
  3779. pte_t pte;
  3780. vm_fault_t ret = 0;
  3781. void *shadow = NULL;
  3782. int nr_pages;
  3783. unsigned long page_idx;
  3784. unsigned long address;
  3785. pte_t *ptep;
  3786. if (!pte_unmap_same(vmf))
  3787. goto out;
  3788. entry = pte_to_swp_entry(vmf->orig_pte);
  3789. if (unlikely(non_swap_entry(entry))) {
  3790. if (is_migration_entry(entry)) {
  3791. migration_entry_wait(vma->vm_mm, vmf->pmd,
  3792. vmf->address);
  3793. } else if (is_device_exclusive_entry(entry)) {
  3794. vmf->page = pfn_swap_entry_to_page(entry);
  3795. ret = remove_device_exclusive_entry(vmf);
  3796. } else if (is_device_private_entry(entry)) {
  3797. if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
  3798. /*
  3799. * migrate_to_ram is not yet ready to operate
  3800. * under VMA lock.
  3801. */
  3802. vma_end_read(vma);
  3803. ret = VM_FAULT_RETRY;
  3804. goto out;
  3805. }
  3806. vmf->page = pfn_swap_entry_to_page(entry);
  3807. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
  3808. vmf->address, &vmf->ptl);
  3809. if (unlikely(!vmf->pte ||
  3810. !pte_same(ptep_get(vmf->pte),
  3811. vmf->orig_pte)))
  3812. goto unlock;
  3813. /*
  3814. * Get a page reference while we know the page can't be
  3815. * freed.
  3816. */
  3817. get_page(vmf->page);
  3818. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3819. ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
  3820. put_page(vmf->page);
  3821. } else if (is_hwpoison_entry(entry)) {
  3822. ret = VM_FAULT_HWPOISON;
  3823. } else if (is_pte_marker_entry(entry)) {
  3824. ret = handle_pte_marker(vmf);
  3825. } else {
  3826. print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
  3827. ret = VM_FAULT_SIGBUS;
  3828. }
  3829. goto out;
  3830. }
  3831. /* Prevent swapoff from happening to us. */
  3832. si = get_swap_device(entry);
  3833. if (unlikely(!si))
  3834. goto out;
  3835. folio = swap_cache_get_folio(entry, vma, vmf->address);
  3836. if (folio)
  3837. page = folio_file_page(folio, swp_offset(entry));
  3838. swapcache = folio;
  3839. if (!folio) {
  3840. if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
  3841. __swap_count(entry) == 1) {
  3842. /* skip swapcache */
  3843. folio = alloc_swap_folio(vmf);
  3844. if (folio) {
  3845. __folio_set_locked(folio);
  3846. __folio_set_swapbacked(folio);
  3847. nr_pages = folio_nr_pages(folio);
  3848. if (folio_test_large(folio))
  3849. entry.val = ALIGN_DOWN(entry.val, nr_pages);
  3850. /*
  3851. * Prevent parallel swapin from proceeding with
  3852. * the cache flag. Otherwise, another thread
  3853. * may finish swapin first, free the entry, and
  3854. * swapout reusing the same entry. It's
  3855. * undetectable as pte_same() returns true due
  3856. * to entry reuse.
  3857. */
  3858. if (swapcache_prepare(entry, nr_pages)) {
  3859. /*
  3860. * Relax a bit to prevent rapid
  3861. * repeated page faults.
  3862. */
  3863. add_wait_queue(&swapcache_wq, &wait);
  3864. schedule_timeout_uninterruptible(1);
  3865. remove_wait_queue(&swapcache_wq, &wait);
  3866. goto out_page;
  3867. }
  3868. need_clear_cache = true;
  3869. mem_cgroup_swapin_uncharge_swap(entry, nr_pages);
  3870. shadow = get_shadow_from_swap_cache(entry);
  3871. if (shadow)
  3872. workingset_refault(folio, shadow);
  3873. folio_add_lru(folio);
  3874. /* To provide entry to swap_read_folio() */
  3875. folio->swap = entry;
  3876. swap_read_folio(folio, NULL);
  3877. folio->private = NULL;
  3878. }
  3879. } else {
  3880. folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
  3881. vmf);
  3882. swapcache = folio;
  3883. }
  3884. if (!folio) {
  3885. /*
  3886. * Back out if somebody else faulted in this pte
  3887. * while we released the pte lock.
  3888. */
  3889. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
  3890. vmf->address, &vmf->ptl);
  3891. if (likely(vmf->pte &&
  3892. pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
  3893. ret = VM_FAULT_OOM;
  3894. goto unlock;
  3895. }
  3896. /* Had to read the page from swap area: Major fault */
  3897. ret = VM_FAULT_MAJOR;
  3898. count_vm_event(PGMAJFAULT);
  3899. count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
  3900. page = folio_file_page(folio, swp_offset(entry));
  3901. } else if (PageHWPoison(page)) {
  3902. /*
  3903. * hwpoisoned dirty swapcache pages are kept for killing
  3904. * owner processes (which may be unknown at hwpoison time)
  3905. */
  3906. ret = VM_FAULT_HWPOISON;
  3907. goto out_release;
  3908. }
  3909. ret |= folio_lock_or_retry(folio, vmf);
  3910. if (ret & VM_FAULT_RETRY)
  3911. goto out_release;
  3912. if (swapcache) {
  3913. /*
  3914. * Make sure folio_free_swap() or swapoff did not release the
  3915. * swapcache from under us. The page pin, and pte_same test
  3916. * below, are not enough to exclude that. Even if it is still
  3917. * swapcache, we need to check that the page's swap has not
  3918. * changed.
  3919. */
  3920. if (unlikely(!folio_test_swapcache(folio) ||
  3921. page_swap_entry(page).val != entry.val))
  3922. goto out_page;
  3923. /*
  3924. * KSM sometimes has to copy on read faults, for example, if
  3925. * page->index of !PageKSM() pages would be nonlinear inside the
  3926. * anon VMA -- PageKSM() is lost on actual swapout.
  3927. */
  3928. folio = ksm_might_need_to_copy(folio, vma, vmf->address);
  3929. if (unlikely(!folio)) {
  3930. ret = VM_FAULT_OOM;
  3931. folio = swapcache;
  3932. goto out_page;
  3933. } else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
  3934. ret = VM_FAULT_HWPOISON;
  3935. folio = swapcache;
  3936. goto out_page;
  3937. }
  3938. if (folio != swapcache)
  3939. page = folio_page(folio, 0);
  3940. /*
  3941. * If we want to map a page that's in the swapcache writable, we
  3942. * have to detect via the refcount if we're really the exclusive
  3943. * owner. Try removing the extra reference from the local LRU
  3944. * caches if required.
  3945. */
  3946. if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache &&
  3947. !folio_test_ksm(folio) && !folio_test_lru(folio))
  3948. lru_add_drain();
  3949. }
  3950. folio_throttle_swaprate(folio, GFP_KERNEL);
  3951. /*
  3952. * Back out if somebody else already faulted in this pte.
  3953. */
  3954. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
  3955. &vmf->ptl);
  3956. if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
  3957. goto out_nomap;
  3958. if (unlikely(!folio_test_uptodate(folio))) {
  3959. ret = VM_FAULT_SIGBUS;
  3960. goto out_nomap;
  3961. }
  3962. /* allocated large folios for SWP_SYNCHRONOUS_IO */
  3963. if (folio_test_large(folio) && !folio_test_swapcache(folio)) {
  3964. unsigned long nr = folio_nr_pages(folio);
  3965. unsigned long folio_start = ALIGN_DOWN(vmf->address, nr * PAGE_SIZE);
  3966. unsigned long idx = (vmf->address - folio_start) / PAGE_SIZE;
  3967. pte_t *folio_ptep = vmf->pte - idx;
  3968. pte_t folio_pte = ptep_get(folio_ptep);
  3969. if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
  3970. swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
  3971. goto out_nomap;
  3972. page_idx = idx;
  3973. address = folio_start;
  3974. ptep = folio_ptep;
  3975. goto check_folio;
  3976. }
  3977. nr_pages = 1;
  3978. page_idx = 0;
  3979. address = vmf->address;
  3980. ptep = vmf->pte;
  3981. if (folio_test_large(folio) && folio_test_swapcache(folio)) {
  3982. int nr = folio_nr_pages(folio);
  3983. unsigned long idx = folio_page_idx(folio, page);
  3984. unsigned long folio_start = address - idx * PAGE_SIZE;
  3985. unsigned long folio_end = folio_start + nr * PAGE_SIZE;
  3986. pte_t *folio_ptep;
  3987. pte_t folio_pte;
  3988. if (unlikely(folio_start < max(address & PMD_MASK, vma->vm_start)))
  3989. goto check_folio;
  3990. if (unlikely(folio_end > pmd_addr_end(address, vma->vm_end)))
  3991. goto check_folio;
  3992. folio_ptep = vmf->pte - idx;
  3993. folio_pte = ptep_get(folio_ptep);
  3994. if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
  3995. swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
  3996. goto check_folio;
  3997. page_idx = idx;
  3998. address = folio_start;
  3999. ptep = folio_ptep;
  4000. nr_pages = nr;
  4001. entry = folio->swap;
  4002. page = &folio->page;
  4003. }
  4004. check_folio:
  4005. /*
  4006. * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
  4007. * must never point at an anonymous page in the swapcache that is
  4008. * PG_anon_exclusive. Sanity check that this holds and especially, that
  4009. * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
  4010. * check after taking the PT lock and making sure that nobody
  4011. * concurrently faulted in this page and set PG_anon_exclusive.
  4012. */
  4013. BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
  4014. BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
  4015. /*
  4016. * Check under PT lock (to protect against concurrent fork() sharing
  4017. * the swap entry concurrently) for certainly exclusive pages.
  4018. */
  4019. if (!folio_test_ksm(folio)) {
  4020. exclusive = pte_swp_exclusive(vmf->orig_pte);
  4021. if (folio != swapcache) {
  4022. /*
  4023. * We have a fresh page that is not exposed to the
  4024. * swapcache -> certainly exclusive.
  4025. */
  4026. exclusive = true;
  4027. } else if (exclusive && folio_test_writeback(folio) &&
  4028. data_race(si->flags & SWP_STABLE_WRITES)) {
  4029. /*
  4030. * This is tricky: not all swap backends support
  4031. * concurrent page modifications while under writeback.
  4032. *
  4033. * So if we stumble over such a page in the swapcache
  4034. * we must not set the page exclusive, otherwise we can
  4035. * map it writable without further checks and modify it
  4036. * while still under writeback.
  4037. *
  4038. * For these problematic swap backends, simply drop the
  4039. * exclusive marker: this is perfectly fine as we start
  4040. * writeback only if we fully unmapped the page and
  4041. * there are no unexpected references on the page after
  4042. * unmapping succeeded. After fully unmapped, no
  4043. * further GUP references (FOLL_GET and FOLL_PIN) can
  4044. * appear, so dropping the exclusive marker and mapping
  4045. * it only R/O is fine.
  4046. */
  4047. exclusive = false;
  4048. }
  4049. }
  4050. /*
  4051. * Some architectures may have to restore extra metadata to the page
  4052. * when reading from swap. This metadata may be indexed by swap entry
  4053. * so this must be called before swap_free().
  4054. */
  4055. arch_swap_restore(folio_swap(entry, folio), folio);
  4056. /*
  4057. * Remove the swap entry and conditionally try to free up the swapcache.
  4058. * We're already holding a reference on the page but haven't mapped it
  4059. * yet.
  4060. */
  4061. swap_free_nr(entry, nr_pages);
  4062. if (should_try_to_free_swap(folio, vma, vmf->flags))
  4063. folio_free_swap(folio);
  4064. add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
  4065. add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages);
  4066. pte = mk_pte(page, vma->vm_page_prot);
  4067. if (pte_swp_soft_dirty(vmf->orig_pte))
  4068. pte = pte_mksoft_dirty(pte);
  4069. if (pte_swp_uffd_wp(vmf->orig_pte))
  4070. pte = pte_mkuffd_wp(pte);
  4071. /*
  4072. * Same logic as in do_wp_page(); however, optimize for pages that are
  4073. * certainly not shared either because we just allocated them without
  4074. * exposing them to the swapcache or because the swap entry indicates
  4075. * exclusivity.
  4076. */
  4077. if (!folio_test_ksm(folio) &&
  4078. (exclusive || folio_ref_count(folio) == 1)) {
  4079. if ((vma->vm_flags & VM_WRITE) && !userfaultfd_pte_wp(vma, pte) &&
  4080. !pte_needs_soft_dirty_wp(vma, pte)) {
  4081. pte = pte_mkwrite(pte, vma);
  4082. if (vmf->flags & FAULT_FLAG_WRITE) {
  4083. pte = pte_mkdirty(pte);
  4084. vmf->flags &= ~FAULT_FLAG_WRITE;
  4085. }
  4086. }
  4087. rmap_flags |= RMAP_EXCLUSIVE;
  4088. }
  4089. folio_ref_add(folio, nr_pages - 1);
  4090. flush_icache_pages(vma, page, nr_pages);
  4091. vmf->orig_pte = pte_advance_pfn(pte, page_idx);
  4092. /* ksm created a completely new copy */
  4093. if (unlikely(folio != swapcache && swapcache)) {
  4094. folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
  4095. folio_add_lru_vma(folio, vma);
  4096. } else if (!folio_test_anon(folio)) {
  4097. /*
  4098. * We currently only expect small !anon folios which are either
  4099. * fully exclusive or fully shared, or new allocated large
  4100. * folios which are fully exclusive. If we ever get large
  4101. * folios within swapcache here, we have to be careful.
  4102. */
  4103. VM_WARN_ON_ONCE(folio_test_large(folio) && folio_test_swapcache(folio));
  4104. VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
  4105. folio_add_new_anon_rmap(folio, vma, address, rmap_flags);
  4106. } else {
  4107. folio_add_anon_rmap_ptes(folio, page, nr_pages, vma, address,
  4108. rmap_flags);
  4109. }
  4110. VM_BUG_ON(!folio_test_anon(folio) ||
  4111. (pte_write(pte) && !PageAnonExclusive(page)));
  4112. set_ptes(vma->vm_mm, address, ptep, pte, nr_pages);
  4113. arch_do_swap_page_nr(vma->vm_mm, vma, address,
  4114. pte, pte, nr_pages);
  4115. folio_unlock(folio);
  4116. if (folio != swapcache && swapcache) {
  4117. /*
  4118. * Hold the lock to avoid the swap entry to be reused
  4119. * until we take the PT lock for the pte_same() check
  4120. * (to avoid false positives from pte_same). For
  4121. * further safety release the lock after the swap_free
  4122. * so that the swap count won't change under a
  4123. * parallel locked swapcache.
  4124. */
  4125. folio_unlock(swapcache);
  4126. folio_put(swapcache);
  4127. }
  4128. if (vmf->flags & FAULT_FLAG_WRITE) {
  4129. ret |= do_wp_page(vmf);
  4130. if (ret & VM_FAULT_ERROR)
  4131. ret &= VM_FAULT_ERROR;
  4132. goto out;
  4133. }
  4134. /* No need to invalidate - it was non-present before */
  4135. update_mmu_cache_range(vmf, vma, address, ptep, nr_pages);
  4136. unlock:
  4137. if (vmf->pte)
  4138. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4139. out:
  4140. /* Clear the swap cache pin for direct swapin after PTL unlock */
  4141. if (need_clear_cache) {
  4142. swapcache_clear(si, entry, nr_pages);
  4143. if (waitqueue_active(&swapcache_wq))
  4144. wake_up(&swapcache_wq);
  4145. }
  4146. if (si)
  4147. put_swap_device(si);
  4148. return ret;
  4149. out_nomap:
  4150. if (vmf->pte)
  4151. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4152. out_page:
  4153. folio_unlock(folio);
  4154. out_release:
  4155. folio_put(folio);
  4156. if (folio != swapcache && swapcache) {
  4157. folio_unlock(swapcache);
  4158. folio_put(swapcache);
  4159. }
  4160. if (need_clear_cache) {
  4161. swapcache_clear(si, entry, nr_pages);
  4162. if (waitqueue_active(&swapcache_wq))
  4163. wake_up(&swapcache_wq);
  4164. }
  4165. if (si)
  4166. put_swap_device(si);
  4167. return ret;
  4168. }
  4169. static bool pte_range_none(pte_t *pte, int nr_pages)
  4170. {
  4171. int i;
  4172. for (i = 0; i < nr_pages; i++) {
  4173. if (!pte_none(ptep_get_lockless(pte + i)))
  4174. return false;
  4175. }
  4176. return true;
  4177. }
  4178. static struct folio *alloc_anon_folio(struct vm_fault *vmf)
  4179. {
  4180. struct vm_area_struct *vma = vmf->vma;
  4181. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4182. unsigned long orders;
  4183. struct folio *folio;
  4184. unsigned long addr;
  4185. pte_t *pte;
  4186. gfp_t gfp;
  4187. int order;
  4188. /*
  4189. * If uffd is active for the vma we need per-page fault fidelity to
  4190. * maintain the uffd semantics.
  4191. */
  4192. if (unlikely(userfaultfd_armed(vma)))
  4193. goto fallback;
  4194. /*
  4195. * Get a list of all the (large) orders below PMD_ORDER that are enabled
  4196. * for this vma. Then filter out the orders that can't be allocated over
  4197. * the faulting address and still be fully contained in the vma.
  4198. */
  4199. orders = thp_vma_allowable_orders(vma, vma->vm_flags,
  4200. TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
  4201. orders = thp_vma_suitable_orders(vma, vmf->address, orders);
  4202. if (!orders)
  4203. goto fallback;
  4204. pte = pte_offset_map(vmf->pmd, vmf->address & PMD_MASK);
  4205. if (!pte)
  4206. return ERR_PTR(-EAGAIN);
  4207. /*
  4208. * Find the highest order where the aligned range is completely
  4209. * pte_none(). Note that all remaining orders will be completely
  4210. * pte_none().
  4211. */
  4212. order = highest_order(orders);
  4213. while (orders) {
  4214. addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
  4215. if (pte_range_none(pte + pte_index(addr), 1 << order))
  4216. break;
  4217. order = next_order(&orders, order);
  4218. }
  4219. pte_unmap(pte);
  4220. if (!orders)
  4221. goto fallback;
  4222. /* Try allocating the highest of the remaining orders. */
  4223. gfp = vma_thp_gfp_mask(vma);
  4224. while (orders) {
  4225. addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
  4226. folio = vma_alloc_folio(gfp, order, vma, addr, true);
  4227. if (folio) {
  4228. if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
  4229. count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
  4230. folio_put(folio);
  4231. goto next;
  4232. }
  4233. folio_throttle_swaprate(folio, gfp);
  4234. folio_zero_user(folio, vmf->address);
  4235. return folio;
  4236. }
  4237. next:
  4238. count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
  4239. order = next_order(&orders, order);
  4240. }
  4241. fallback:
  4242. #endif
  4243. return folio_prealloc(vma->vm_mm, vma, vmf->address, true);
  4244. }
  4245. /*
  4246. * We enter with non-exclusive mmap_lock (to exclude vma changes,
  4247. * but allow concurrent faults), and pte mapped but not yet locked.
  4248. * We return with mmap_lock still held, but pte unmapped and unlocked.
  4249. */
  4250. static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
  4251. {
  4252. struct vm_area_struct *vma = vmf->vma;
  4253. unsigned long addr = vmf->address;
  4254. struct folio *folio;
  4255. vm_fault_t ret = 0;
  4256. int nr_pages = 1;
  4257. pte_t entry;
  4258. /* File mapping without ->vm_ops ? */
  4259. if (vma->vm_flags & VM_SHARED)
  4260. return VM_FAULT_SIGBUS;
  4261. /*
  4262. * Use pte_alloc() instead of pte_alloc_map(), so that OOM can
  4263. * be distinguished from a transient failure of pte_offset_map().
  4264. */
  4265. if (pte_alloc(vma->vm_mm, vmf->pmd))
  4266. return VM_FAULT_OOM;
  4267. /* Use the zero-page for reads */
  4268. if (!(vmf->flags & FAULT_FLAG_WRITE) &&
  4269. !mm_forbids_zeropage(vma->vm_mm)) {
  4270. entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
  4271. vma->vm_page_prot));
  4272. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
  4273. vmf->address, &vmf->ptl);
  4274. if (!vmf->pte)
  4275. goto unlock;
  4276. if (vmf_pte_changed(vmf)) {
  4277. update_mmu_tlb(vma, vmf->address, vmf->pte);
  4278. goto unlock;
  4279. }
  4280. ret = check_stable_address_space(vma->vm_mm);
  4281. if (ret)
  4282. goto unlock;
  4283. /* Deliver the page fault to userland, check inside PT lock */
  4284. if (userfaultfd_missing(vma)) {
  4285. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4286. return handle_userfault(vmf, VM_UFFD_MISSING);
  4287. }
  4288. goto setpte;
  4289. }
  4290. /* Allocate our own private page. */
  4291. ret = vmf_anon_prepare(vmf);
  4292. if (ret)
  4293. return ret;
  4294. /* Returns NULL on OOM or ERR_PTR(-EAGAIN) if we must retry the fault */
  4295. folio = alloc_anon_folio(vmf);
  4296. if (IS_ERR(folio))
  4297. return 0;
  4298. if (!folio)
  4299. goto oom;
  4300. nr_pages = folio_nr_pages(folio);
  4301. addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
  4302. /*
  4303. * The memory barrier inside __folio_mark_uptodate makes sure that
  4304. * preceding stores to the page contents become visible before
  4305. * the set_pte_at() write.
  4306. */
  4307. __folio_mark_uptodate(folio);
  4308. entry = mk_pte(&folio->page, vma->vm_page_prot);
  4309. entry = pte_sw_mkyoung(entry);
  4310. if (vma->vm_flags & VM_WRITE)
  4311. entry = pte_mkwrite(pte_mkdirty(entry), vma);
  4312. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
  4313. if (!vmf->pte)
  4314. goto release;
  4315. if (nr_pages == 1 && vmf_pte_changed(vmf)) {
  4316. update_mmu_tlb(vma, addr, vmf->pte);
  4317. goto release;
  4318. } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
  4319. update_mmu_tlb_range(vma, addr, vmf->pte, nr_pages);
  4320. goto release;
  4321. }
  4322. ret = check_stable_address_space(vma->vm_mm);
  4323. if (ret)
  4324. goto release;
  4325. /* Deliver the page fault to userland, check inside PT lock */
  4326. if (userfaultfd_missing(vma)) {
  4327. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4328. folio_put(folio);
  4329. return handle_userfault(vmf, VM_UFFD_MISSING);
  4330. }
  4331. folio_ref_add(folio, nr_pages - 1);
  4332. add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
  4333. count_mthp_stat(folio_order(folio), MTHP_STAT_ANON_FAULT_ALLOC);
  4334. folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
  4335. folio_add_lru_vma(folio, vma);
  4336. setpte:
  4337. if (vmf_orig_pte_uffd_wp(vmf))
  4338. entry = pte_mkuffd_wp(entry);
  4339. set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr_pages);
  4340. /* No need to invalidate - it was non-present before */
  4341. update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr_pages);
  4342. unlock:
  4343. if (vmf->pte)
  4344. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4345. return ret;
  4346. release:
  4347. folio_put(folio);
  4348. goto unlock;
  4349. oom:
  4350. return VM_FAULT_OOM;
  4351. }
  4352. /*
  4353. * The mmap_lock must have been held on entry, and may have been
  4354. * released depending on flags and vma->vm_ops->fault() return value.
  4355. * See filemap_fault() and __lock_page_retry().
  4356. */
  4357. static vm_fault_t __do_fault(struct vm_fault *vmf)
  4358. {
  4359. struct vm_area_struct *vma = vmf->vma;
  4360. struct folio *folio;
  4361. vm_fault_t ret;
  4362. /*
  4363. * Preallocate pte before we take page_lock because this might lead to
  4364. * deadlocks for memcg reclaim which waits for pages under writeback:
  4365. * lock_page(A)
  4366. * SetPageWriteback(A)
  4367. * unlock_page(A)
  4368. * lock_page(B)
  4369. * lock_page(B)
  4370. * pte_alloc_one
  4371. * shrink_folio_list
  4372. * wait_on_page_writeback(A)
  4373. * SetPageWriteback(B)
  4374. * unlock_page(B)
  4375. * # flush A, B to clear the writeback
  4376. */
  4377. if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
  4378. vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
  4379. if (!vmf->prealloc_pte)
  4380. return VM_FAULT_OOM;
  4381. }
  4382. ret = vma->vm_ops->fault(vmf);
  4383. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
  4384. VM_FAULT_DONE_COW)))
  4385. return ret;
  4386. folio = page_folio(vmf->page);
  4387. if (unlikely(PageHWPoison(vmf->page))) {
  4388. vm_fault_t poisonret = VM_FAULT_HWPOISON;
  4389. if (ret & VM_FAULT_LOCKED) {
  4390. if (page_mapped(vmf->page))
  4391. unmap_mapping_folio(folio);
  4392. /* Retry if a clean folio was removed from the cache. */
  4393. if (mapping_evict_folio(folio->mapping, folio))
  4394. poisonret = VM_FAULT_NOPAGE;
  4395. folio_unlock(folio);
  4396. }
  4397. folio_put(folio);
  4398. vmf->page = NULL;
  4399. return poisonret;
  4400. }
  4401. if (unlikely(!(ret & VM_FAULT_LOCKED)))
  4402. folio_lock(folio);
  4403. else
  4404. VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page);
  4405. return ret;
  4406. }
  4407. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4408. static void deposit_prealloc_pte(struct vm_fault *vmf)
  4409. {
  4410. struct vm_area_struct *vma = vmf->vma;
  4411. pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
  4412. /*
  4413. * We are going to consume the prealloc table,
  4414. * count that as nr_ptes.
  4415. */
  4416. mm_inc_nr_ptes(vma->vm_mm);
  4417. vmf->prealloc_pte = NULL;
  4418. }
  4419. vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
  4420. {
  4421. struct folio *folio = page_folio(page);
  4422. struct vm_area_struct *vma = vmf->vma;
  4423. bool write = vmf->flags & FAULT_FLAG_WRITE;
  4424. unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
  4425. pmd_t entry;
  4426. vm_fault_t ret = VM_FAULT_FALLBACK;
  4427. /*
  4428. * It is too late to allocate a small folio, we already have a large
  4429. * folio in the pagecache: especially s390 KVM cannot tolerate any
  4430. * PMD mappings, but PTE-mapped THP are fine. So let's simply refuse any
  4431. * PMD mappings if THPs are disabled.
  4432. */
  4433. if (thp_disabled_by_hw() || vma_thp_disabled(vma, vma->vm_flags))
  4434. return ret;
  4435. if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
  4436. return ret;
  4437. if (folio_order(folio) != HPAGE_PMD_ORDER)
  4438. return ret;
  4439. page = &folio->page;
  4440. /*
  4441. * Just backoff if any subpage of a THP is corrupted otherwise
  4442. * the corrupted page may mapped by PMD silently to escape the
  4443. * check. This kind of THP just can be PTE mapped. Access to
  4444. * the corrupted subpage should trigger SIGBUS as expected.
  4445. */
  4446. if (unlikely(folio_test_has_hwpoisoned(folio)))
  4447. return ret;
  4448. /*
  4449. * Archs like ppc64 need additional space to store information
  4450. * related to pte entry. Use the preallocated table for that.
  4451. */
  4452. if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
  4453. vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
  4454. if (!vmf->prealloc_pte)
  4455. return VM_FAULT_OOM;
  4456. }
  4457. vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
  4458. if (unlikely(!pmd_none(*vmf->pmd)))
  4459. goto out;
  4460. flush_icache_pages(vma, page, HPAGE_PMD_NR);
  4461. entry = mk_huge_pmd(page, vma->vm_page_prot);
  4462. if (write)
  4463. entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
  4464. add_mm_counter(vma->vm_mm, mm_counter_file(folio), HPAGE_PMD_NR);
  4465. folio_add_file_rmap_pmd(folio, page, vma);
  4466. /*
  4467. * deposit and withdraw with pmd lock held
  4468. */
  4469. if (arch_needs_pgtable_deposit())
  4470. deposit_prealloc_pte(vmf);
  4471. set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
  4472. update_mmu_cache_pmd(vma, haddr, vmf->pmd);
  4473. /* fault is handled */
  4474. ret = 0;
  4475. count_vm_event(THP_FILE_MAPPED);
  4476. out:
  4477. spin_unlock(vmf->ptl);
  4478. return ret;
  4479. }
  4480. #else
  4481. vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
  4482. {
  4483. return VM_FAULT_FALLBACK;
  4484. }
  4485. #endif
  4486. /**
  4487. * set_pte_range - Set a range of PTEs to point to pages in a folio.
  4488. * @vmf: Fault decription.
  4489. * @folio: The folio that contains @page.
  4490. * @page: The first page to create a PTE for.
  4491. * @nr: The number of PTEs to create.
  4492. * @addr: The first address to create a PTE for.
  4493. */
  4494. void set_pte_range(struct vm_fault *vmf, struct folio *folio,
  4495. struct page *page, unsigned int nr, unsigned long addr)
  4496. {
  4497. struct vm_area_struct *vma = vmf->vma;
  4498. bool write = vmf->flags & FAULT_FLAG_WRITE;
  4499. bool prefault = !in_range(vmf->address, addr, nr * PAGE_SIZE);
  4500. pte_t entry;
  4501. flush_icache_pages(vma, page, nr);
  4502. entry = mk_pte(page, vma->vm_page_prot);
  4503. if (prefault && arch_wants_old_prefaulted_pte())
  4504. entry = pte_mkold(entry);
  4505. else
  4506. entry = pte_sw_mkyoung(entry);
  4507. if (write)
  4508. entry = maybe_mkwrite(pte_mkdirty(entry), vma);
  4509. if (unlikely(vmf_orig_pte_uffd_wp(vmf)))
  4510. entry = pte_mkuffd_wp(entry);
  4511. /* copy-on-write page */
  4512. if (write && !(vma->vm_flags & VM_SHARED)) {
  4513. VM_BUG_ON_FOLIO(nr != 1, folio);
  4514. folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
  4515. folio_add_lru_vma(folio, vma);
  4516. } else {
  4517. folio_add_file_rmap_ptes(folio, page, nr, vma);
  4518. }
  4519. set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr);
  4520. /* no need to invalidate: a not-present page won't be cached */
  4521. update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr);
  4522. }
  4523. static bool vmf_pte_changed(struct vm_fault *vmf)
  4524. {
  4525. if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
  4526. return !pte_same(ptep_get(vmf->pte), vmf->orig_pte);
  4527. return !pte_none(ptep_get(vmf->pte));
  4528. }
  4529. /**
  4530. * finish_fault - finish page fault once we have prepared the page to fault
  4531. *
  4532. * @vmf: structure describing the fault
  4533. *
  4534. * This function handles all that is needed to finish a page fault once the
  4535. * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
  4536. * given page, adds reverse page mapping, handles memcg charges and LRU
  4537. * addition.
  4538. *
  4539. * The function expects the page to be locked and on success it consumes a
  4540. * reference of a page being mapped (for the PTE which maps it).
  4541. *
  4542. * Return: %0 on success, %VM_FAULT_ code in case of error.
  4543. */
  4544. vm_fault_t finish_fault(struct vm_fault *vmf)
  4545. {
  4546. struct vm_area_struct *vma = vmf->vma;
  4547. struct page *page;
  4548. struct folio *folio;
  4549. vm_fault_t ret;
  4550. bool is_cow = (vmf->flags & FAULT_FLAG_WRITE) &&
  4551. !(vma->vm_flags & VM_SHARED);
  4552. int type, nr_pages;
  4553. unsigned long addr;
  4554. bool needs_fallback = false;
  4555. fallback:
  4556. addr = vmf->address;
  4557. /* Did we COW the page? */
  4558. if (is_cow)
  4559. page = vmf->cow_page;
  4560. else
  4561. page = vmf->page;
  4562. /*
  4563. * check even for read faults because we might have lost our CoWed
  4564. * page
  4565. */
  4566. if (!(vma->vm_flags & VM_SHARED)) {
  4567. ret = check_stable_address_space(vma->vm_mm);
  4568. if (ret)
  4569. return ret;
  4570. }
  4571. if (pmd_none(*vmf->pmd)) {
  4572. if (PageTransCompound(page)) {
  4573. ret = do_set_pmd(vmf, page);
  4574. if (ret != VM_FAULT_FALLBACK)
  4575. return ret;
  4576. }
  4577. if (vmf->prealloc_pte)
  4578. pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
  4579. else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
  4580. return VM_FAULT_OOM;
  4581. }
  4582. folio = page_folio(page);
  4583. nr_pages = folio_nr_pages(folio);
  4584. /*
  4585. * Using per-page fault to maintain the uffd semantics, and same
  4586. * approach also applies to non-anonymous-shmem faults to avoid
  4587. * inflating the RSS of the process.
  4588. */
  4589. if (!vma_is_anon_shmem(vma) || unlikely(userfaultfd_armed(vma)) ||
  4590. unlikely(needs_fallback)) {
  4591. nr_pages = 1;
  4592. } else if (nr_pages > 1) {
  4593. pgoff_t idx = folio_page_idx(folio, page);
  4594. /* The page offset of vmf->address within the VMA. */
  4595. pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
  4596. /* The index of the entry in the pagetable for fault page. */
  4597. pgoff_t pte_off = pte_index(vmf->address);
  4598. /*
  4599. * Fallback to per-page fault in case the folio size in page
  4600. * cache beyond the VMA limits and PMD pagetable limits.
  4601. */
  4602. if (unlikely(vma_off < idx ||
  4603. vma_off + (nr_pages - idx) > vma_pages(vma) ||
  4604. pte_off < idx ||
  4605. pte_off + (nr_pages - idx) > PTRS_PER_PTE)) {
  4606. nr_pages = 1;
  4607. } else {
  4608. /* Now we can set mappings for the whole large folio. */
  4609. addr = vmf->address - idx * PAGE_SIZE;
  4610. page = &folio->page;
  4611. }
  4612. }
  4613. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
  4614. addr, &vmf->ptl);
  4615. if (!vmf->pte)
  4616. return VM_FAULT_NOPAGE;
  4617. /* Re-check under ptl */
  4618. if (nr_pages == 1 && unlikely(vmf_pte_changed(vmf))) {
  4619. update_mmu_tlb(vma, addr, vmf->pte);
  4620. ret = VM_FAULT_NOPAGE;
  4621. goto unlock;
  4622. } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
  4623. needs_fallback = true;
  4624. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4625. goto fallback;
  4626. }
  4627. folio_ref_add(folio, nr_pages - 1);
  4628. set_pte_range(vmf, folio, page, nr_pages, addr);
  4629. type = is_cow ? MM_ANONPAGES : mm_counter_file(folio);
  4630. add_mm_counter(vma->vm_mm, type, nr_pages);
  4631. ret = 0;
  4632. unlock:
  4633. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4634. return ret;
  4635. }
  4636. static unsigned long fault_around_pages __read_mostly =
  4637. 65536 >> PAGE_SHIFT;
  4638. #ifdef CONFIG_DEBUG_FS
  4639. static int fault_around_bytes_get(void *data, u64 *val)
  4640. {
  4641. *val = fault_around_pages << PAGE_SHIFT;
  4642. return 0;
  4643. }
  4644. /*
  4645. * fault_around_bytes must be rounded down to the nearest page order as it's
  4646. * what do_fault_around() expects to see.
  4647. */
  4648. static int fault_around_bytes_set(void *data, u64 val)
  4649. {
  4650. if (val / PAGE_SIZE > PTRS_PER_PTE)
  4651. return -EINVAL;
  4652. /*
  4653. * The minimum value is 1 page, however this results in no fault-around
  4654. * at all. See should_fault_around().
  4655. */
  4656. val = max(val, PAGE_SIZE);
  4657. fault_around_pages = rounddown_pow_of_two(val) >> PAGE_SHIFT;
  4658. return 0;
  4659. }
  4660. DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
  4661. fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
  4662. static int __init fault_around_debugfs(void)
  4663. {
  4664. debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
  4665. &fault_around_bytes_fops);
  4666. return 0;
  4667. }
  4668. late_initcall(fault_around_debugfs);
  4669. #endif
  4670. /*
  4671. * do_fault_around() tries to map few pages around the fault address. The hope
  4672. * is that the pages will be needed soon and this will lower the number of
  4673. * faults to handle.
  4674. *
  4675. * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
  4676. * not ready to be mapped: not up-to-date, locked, etc.
  4677. *
  4678. * This function doesn't cross VMA or page table boundaries, in order to call
  4679. * map_pages() and acquire a PTE lock only once.
  4680. *
  4681. * fault_around_pages defines how many pages we'll try to map.
  4682. * do_fault_around() expects it to be set to a power of two less than or equal
  4683. * to PTRS_PER_PTE.
  4684. *
  4685. * The virtual address of the area that we map is naturally aligned to
  4686. * fault_around_pages * PAGE_SIZE rounded down to the machine page size
  4687. * (and therefore to page order). This way it's easier to guarantee
  4688. * that we don't cross page table boundaries.
  4689. */
  4690. static vm_fault_t do_fault_around(struct vm_fault *vmf)
  4691. {
  4692. pgoff_t nr_pages = READ_ONCE(fault_around_pages);
  4693. pgoff_t pte_off = pte_index(vmf->address);
  4694. /* The page offset of vmf->address within the VMA. */
  4695. pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
  4696. pgoff_t from_pte, to_pte;
  4697. vm_fault_t ret;
  4698. /* The PTE offset of the start address, clamped to the VMA. */
  4699. from_pte = max(ALIGN_DOWN(pte_off, nr_pages),
  4700. pte_off - min(pte_off, vma_off));
  4701. /* The PTE offset of the end address, clamped to the VMA and PTE. */
  4702. to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE,
  4703. pte_off + vma_pages(vmf->vma) - vma_off) - 1;
  4704. if (pmd_none(*vmf->pmd)) {
  4705. vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
  4706. if (!vmf->prealloc_pte)
  4707. return VM_FAULT_OOM;
  4708. }
  4709. rcu_read_lock();
  4710. ret = vmf->vma->vm_ops->map_pages(vmf,
  4711. vmf->pgoff + from_pte - pte_off,
  4712. vmf->pgoff + to_pte - pte_off);
  4713. rcu_read_unlock();
  4714. return ret;
  4715. }
  4716. /* Return true if we should do read fault-around, false otherwise */
  4717. static inline bool should_fault_around(struct vm_fault *vmf)
  4718. {
  4719. /* No ->map_pages? No way to fault around... */
  4720. if (!vmf->vma->vm_ops->map_pages)
  4721. return false;
  4722. if (uffd_disable_fault_around(vmf->vma))
  4723. return false;
  4724. /* A single page implies no faulting 'around' at all. */
  4725. return fault_around_pages > 1;
  4726. }
  4727. static vm_fault_t do_read_fault(struct vm_fault *vmf)
  4728. {
  4729. vm_fault_t ret = 0;
  4730. struct folio *folio;
  4731. /*
  4732. * Let's call ->map_pages() first and use ->fault() as fallback
  4733. * if page by the offset is not ready to be mapped (cold cache or
  4734. * something).
  4735. */
  4736. if (should_fault_around(vmf)) {
  4737. ret = do_fault_around(vmf);
  4738. if (ret)
  4739. return ret;
  4740. }
  4741. ret = vmf_can_call_fault(vmf);
  4742. if (ret)
  4743. return ret;
  4744. ret = __do_fault(vmf);
  4745. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
  4746. return ret;
  4747. ret |= finish_fault(vmf);
  4748. folio = page_folio(vmf->page);
  4749. folio_unlock(folio);
  4750. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
  4751. folio_put(folio);
  4752. return ret;
  4753. }
  4754. static vm_fault_t do_cow_fault(struct vm_fault *vmf)
  4755. {
  4756. struct vm_area_struct *vma = vmf->vma;
  4757. struct folio *folio;
  4758. vm_fault_t ret;
  4759. ret = vmf_can_call_fault(vmf);
  4760. if (!ret)
  4761. ret = vmf_anon_prepare(vmf);
  4762. if (ret)
  4763. return ret;
  4764. folio = folio_prealloc(vma->vm_mm, vma, vmf->address, false);
  4765. if (!folio)
  4766. return VM_FAULT_OOM;
  4767. vmf->cow_page = &folio->page;
  4768. ret = __do_fault(vmf);
  4769. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
  4770. goto uncharge_out;
  4771. if (ret & VM_FAULT_DONE_COW)
  4772. return ret;
  4773. if (copy_mc_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma)) {
  4774. ret = VM_FAULT_HWPOISON;
  4775. goto unlock;
  4776. }
  4777. __folio_mark_uptodate(folio);
  4778. ret |= finish_fault(vmf);
  4779. unlock:
  4780. unlock_page(vmf->page);
  4781. put_page(vmf->page);
  4782. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
  4783. goto uncharge_out;
  4784. return ret;
  4785. uncharge_out:
  4786. folio_put(folio);
  4787. return ret;
  4788. }
  4789. static vm_fault_t do_shared_fault(struct vm_fault *vmf)
  4790. {
  4791. struct vm_area_struct *vma = vmf->vma;
  4792. vm_fault_t ret, tmp;
  4793. struct folio *folio;
  4794. ret = vmf_can_call_fault(vmf);
  4795. if (ret)
  4796. return ret;
  4797. ret = __do_fault(vmf);
  4798. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
  4799. return ret;
  4800. folio = page_folio(vmf->page);
  4801. /*
  4802. * Check if the backing address space wants to know that the page is
  4803. * about to become writable
  4804. */
  4805. if (vma->vm_ops->page_mkwrite) {
  4806. folio_unlock(folio);
  4807. tmp = do_page_mkwrite(vmf, folio);
  4808. if (unlikely(!tmp ||
  4809. (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
  4810. folio_put(folio);
  4811. return tmp;
  4812. }
  4813. }
  4814. ret |= finish_fault(vmf);
  4815. if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
  4816. VM_FAULT_RETRY))) {
  4817. folio_unlock(folio);
  4818. folio_put(folio);
  4819. return ret;
  4820. }
  4821. ret |= fault_dirty_shared_page(vmf);
  4822. return ret;
  4823. }
  4824. /*
  4825. * We enter with non-exclusive mmap_lock (to exclude vma changes,
  4826. * but allow concurrent faults).
  4827. * The mmap_lock may have been released depending on flags and our
  4828. * return value. See filemap_fault() and __folio_lock_or_retry().
  4829. * If mmap_lock is released, vma may become invalid (for example
  4830. * by other thread calling munmap()).
  4831. */
  4832. static vm_fault_t do_fault(struct vm_fault *vmf)
  4833. {
  4834. struct vm_area_struct *vma = vmf->vma;
  4835. struct mm_struct *vm_mm = vma->vm_mm;
  4836. vm_fault_t ret;
  4837. /*
  4838. * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
  4839. */
  4840. if (!vma->vm_ops->fault) {
  4841. vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
  4842. vmf->address, &vmf->ptl);
  4843. if (unlikely(!vmf->pte))
  4844. ret = VM_FAULT_SIGBUS;
  4845. else {
  4846. /*
  4847. * Make sure this is not a temporary clearing of pte
  4848. * by holding ptl and checking again. A R/M/W update
  4849. * of pte involves: take ptl, clearing the pte so that
  4850. * we don't have concurrent modification by hardware
  4851. * followed by an update.
  4852. */
  4853. if (unlikely(pte_none(ptep_get(vmf->pte))))
  4854. ret = VM_FAULT_SIGBUS;
  4855. else
  4856. ret = VM_FAULT_NOPAGE;
  4857. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4858. }
  4859. } else if (!(vmf->flags & FAULT_FLAG_WRITE))
  4860. ret = do_read_fault(vmf);
  4861. else if (!(vma->vm_flags & VM_SHARED))
  4862. ret = do_cow_fault(vmf);
  4863. else
  4864. ret = do_shared_fault(vmf);
  4865. /* preallocated pagetable is unused: free it */
  4866. if (vmf->prealloc_pte) {
  4867. pte_free(vm_mm, vmf->prealloc_pte);
  4868. vmf->prealloc_pte = NULL;
  4869. }
  4870. return ret;
  4871. }
  4872. int numa_migrate_check(struct folio *folio, struct vm_fault *vmf,
  4873. unsigned long addr, int *flags,
  4874. bool writable, int *last_cpupid)
  4875. {
  4876. struct vm_area_struct *vma = vmf->vma;
  4877. /*
  4878. * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
  4879. * much anyway since they can be in shared cache state. This misses
  4880. * the case where a mapping is writable but the process never writes
  4881. * to it but pte_write gets cleared during protection updates and
  4882. * pte_dirty has unpredictable behaviour between PTE scan updates,
  4883. * background writeback, dirty balancing and application behaviour.
  4884. */
  4885. if (!writable)
  4886. *flags |= TNF_NO_GROUP;
  4887. /*
  4888. * Flag if the folio is shared between multiple address spaces. This
  4889. * is later used when determining whether to group tasks together
  4890. */
  4891. if (folio_likely_mapped_shared(folio) && (vma->vm_flags & VM_SHARED))
  4892. *flags |= TNF_SHARED;
  4893. /*
  4894. * For memory tiering mode, cpupid of slow memory page is used
  4895. * to record page access time. So use default value.
  4896. */
  4897. if (folio_use_access_time(folio))
  4898. *last_cpupid = (-1 & LAST_CPUPID_MASK);
  4899. else
  4900. *last_cpupid = folio_last_cpupid(folio);
  4901. /* Record the current PID acceesing VMA */
  4902. vma_set_access_pid_bit(vma);
  4903. count_vm_numa_event(NUMA_HINT_FAULTS);
  4904. #ifdef CONFIG_NUMA_BALANCING
  4905. count_memcg_folio_events(folio, NUMA_HINT_FAULTS, 1);
  4906. #endif
  4907. if (folio_nid(folio) == numa_node_id()) {
  4908. count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
  4909. *flags |= TNF_FAULT_LOCAL;
  4910. }
  4911. return mpol_misplaced(folio, vmf, addr);
  4912. }
  4913. static void numa_rebuild_single_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
  4914. unsigned long fault_addr, pte_t *fault_pte,
  4915. bool writable)
  4916. {
  4917. pte_t pte, old_pte;
  4918. old_pte = ptep_modify_prot_start(vma, fault_addr, fault_pte);
  4919. pte = pte_modify(old_pte, vma->vm_page_prot);
  4920. pte = pte_mkyoung(pte);
  4921. if (writable)
  4922. pte = pte_mkwrite(pte, vma);
  4923. ptep_modify_prot_commit(vma, fault_addr, fault_pte, old_pte, pte);
  4924. update_mmu_cache_range(vmf, vma, fault_addr, fault_pte, 1);
  4925. }
  4926. static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
  4927. struct folio *folio, pte_t fault_pte,
  4928. bool ignore_writable, bool pte_write_upgrade)
  4929. {
  4930. int nr = pte_pfn(fault_pte) - folio_pfn(folio);
  4931. unsigned long start, end, addr = vmf->address;
  4932. unsigned long addr_start = addr - (nr << PAGE_SHIFT);
  4933. unsigned long pt_start = ALIGN_DOWN(addr, PMD_SIZE);
  4934. pte_t *start_ptep;
  4935. /* Stay within the VMA and within the page table. */
  4936. start = max3(addr_start, pt_start, vma->vm_start);
  4937. end = min3(addr_start + folio_size(folio), pt_start + PMD_SIZE,
  4938. vma->vm_end);
  4939. start_ptep = vmf->pte - ((addr - start) >> PAGE_SHIFT);
  4940. /* Restore all PTEs' mapping of the large folio */
  4941. for (addr = start; addr != end; start_ptep++, addr += PAGE_SIZE) {
  4942. pte_t ptent = ptep_get(start_ptep);
  4943. bool writable = false;
  4944. if (!pte_present(ptent) || !pte_protnone(ptent))
  4945. continue;
  4946. if (pfn_folio(pte_pfn(ptent)) != folio)
  4947. continue;
  4948. if (!ignore_writable) {
  4949. ptent = pte_modify(ptent, vma->vm_page_prot);
  4950. writable = pte_write(ptent);
  4951. if (!writable && pte_write_upgrade &&
  4952. can_change_pte_writable(vma, addr, ptent))
  4953. writable = true;
  4954. }
  4955. numa_rebuild_single_mapping(vmf, vma, addr, start_ptep, writable);
  4956. }
  4957. }
  4958. static vm_fault_t do_numa_page(struct vm_fault *vmf)
  4959. {
  4960. struct vm_area_struct *vma = vmf->vma;
  4961. struct folio *folio = NULL;
  4962. int nid = NUMA_NO_NODE;
  4963. bool writable = false, ignore_writable = false;
  4964. bool pte_write_upgrade = vma_wants_manual_pte_write_upgrade(vma);
  4965. int last_cpupid;
  4966. int target_nid;
  4967. pte_t pte, old_pte;
  4968. int flags = 0, nr_pages;
  4969. /*
  4970. * The pte cannot be used safely until we verify, while holding the page
  4971. * table lock, that its contents have not changed during fault handling.
  4972. */
  4973. spin_lock(vmf->ptl);
  4974. /* Read the live PTE from the page tables: */
  4975. old_pte = ptep_get(vmf->pte);
  4976. if (unlikely(!pte_same(old_pte, vmf->orig_pte))) {
  4977. pte_unmap_unlock(vmf->pte, vmf->ptl);
  4978. return 0;
  4979. }
  4980. pte = pte_modify(old_pte, vma->vm_page_prot);
  4981. /*
  4982. * Detect now whether the PTE could be writable; this information
  4983. * is only valid while holding the PT lock.
  4984. */
  4985. writable = pte_write(pte);
  4986. if (!writable && pte_write_upgrade &&
  4987. can_change_pte_writable(vma, vmf->address, pte))
  4988. writable = true;
  4989. folio = vm_normal_folio(vma, vmf->address, pte);
  4990. if (!folio || folio_is_zone_device(folio))
  4991. goto out_map;
  4992. nid = folio_nid(folio);
  4993. nr_pages = folio_nr_pages(folio);
  4994. target_nid = numa_migrate_check(folio, vmf, vmf->address, &flags,
  4995. writable, &last_cpupid);
  4996. if (target_nid == NUMA_NO_NODE)
  4997. goto out_map;
  4998. if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) {
  4999. flags |= TNF_MIGRATE_FAIL;
  5000. goto out_map;
  5001. }
  5002. /* The folio is isolated and isolation code holds a folio reference. */
  5003. pte_unmap_unlock(vmf->pte, vmf->ptl);
  5004. writable = false;
  5005. ignore_writable = true;
  5006. /* Migrate to the requested node */
  5007. if (!migrate_misplaced_folio(folio, vma, target_nid)) {
  5008. nid = target_nid;
  5009. flags |= TNF_MIGRATED;
  5010. task_numa_fault(last_cpupid, nid, nr_pages, flags);
  5011. return 0;
  5012. }
  5013. flags |= TNF_MIGRATE_FAIL;
  5014. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
  5015. vmf->address, &vmf->ptl);
  5016. if (unlikely(!vmf->pte))
  5017. return 0;
  5018. if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
  5019. pte_unmap_unlock(vmf->pte, vmf->ptl);
  5020. return 0;
  5021. }
  5022. out_map:
  5023. /*
  5024. * Make it present again, depending on how arch implements
  5025. * non-accessible ptes, some can allow access by kernel mode.
  5026. */
  5027. if (folio && folio_test_large(folio))
  5028. numa_rebuild_large_mapping(vmf, vma, folio, pte, ignore_writable,
  5029. pte_write_upgrade);
  5030. else
  5031. numa_rebuild_single_mapping(vmf, vma, vmf->address, vmf->pte,
  5032. writable);
  5033. pte_unmap_unlock(vmf->pte, vmf->ptl);
  5034. if (nid != NUMA_NO_NODE)
  5035. task_numa_fault(last_cpupid, nid, nr_pages, flags);
  5036. return 0;
  5037. }
  5038. static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
  5039. {
  5040. struct vm_area_struct *vma = vmf->vma;
  5041. if (vma_is_anonymous(vma))
  5042. return do_huge_pmd_anonymous_page(vmf);
  5043. if (vma->vm_ops->huge_fault)
  5044. return vma->vm_ops->huge_fault(vmf, PMD_ORDER);
  5045. return VM_FAULT_FALLBACK;
  5046. }
  5047. /* `inline' is required to avoid gcc 4.1.2 build error */
  5048. static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
  5049. {
  5050. struct vm_area_struct *vma = vmf->vma;
  5051. const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
  5052. vm_fault_t ret;
  5053. if (vma_is_anonymous(vma)) {
  5054. if (likely(!unshare) &&
  5055. userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) {
  5056. if (userfaultfd_wp_async(vmf->vma))
  5057. goto split;
  5058. return handle_userfault(vmf, VM_UFFD_WP);
  5059. }
  5060. return do_huge_pmd_wp_page(vmf);
  5061. }
  5062. if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
  5063. if (vma->vm_ops->huge_fault) {
  5064. ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER);
  5065. if (!(ret & VM_FAULT_FALLBACK))
  5066. return ret;
  5067. }
  5068. }
  5069. split:
  5070. /* COW or write-notify handled on pte level: split pmd. */
  5071. __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
  5072. return VM_FAULT_FALLBACK;
  5073. }
  5074. static vm_fault_t create_huge_pud(struct vm_fault *vmf)
  5075. {
  5076. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
  5077. defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
  5078. struct vm_area_struct *vma = vmf->vma;
  5079. /* No support for anonymous transparent PUD pages yet */
  5080. if (vma_is_anonymous(vma))
  5081. return VM_FAULT_FALLBACK;
  5082. if (vma->vm_ops->huge_fault)
  5083. return vma->vm_ops->huge_fault(vmf, PUD_ORDER);
  5084. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  5085. return VM_FAULT_FALLBACK;
  5086. }
  5087. static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
  5088. {
  5089. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
  5090. defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
  5091. struct vm_area_struct *vma = vmf->vma;
  5092. vm_fault_t ret;
  5093. /* No support for anonymous transparent PUD pages yet */
  5094. if (vma_is_anonymous(vma))
  5095. goto split;
  5096. if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
  5097. if (vma->vm_ops->huge_fault) {
  5098. ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER);
  5099. if (!(ret & VM_FAULT_FALLBACK))
  5100. return ret;
  5101. }
  5102. }
  5103. split:
  5104. /* COW or write-notify not handled on PUD level: split pud.*/
  5105. __split_huge_pud(vma, vmf->pud, vmf->address);
  5106. #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
  5107. return VM_FAULT_FALLBACK;
  5108. }
  5109. /*
  5110. * These routines also need to handle stuff like marking pages dirty
  5111. * and/or accessed for architectures that don't do it in hardware (most
  5112. * RISC architectures). The early dirtying is also good on the i386.
  5113. *
  5114. * There is also a hook called "update_mmu_cache()" that architectures
  5115. * with external mmu caches can use to update those (ie the Sparc or
  5116. * PowerPC hashed page tables that act as extended TLBs).
  5117. *
  5118. * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
  5119. * concurrent faults).
  5120. *
  5121. * The mmap_lock may have been released depending on flags and our return value.
  5122. * See filemap_fault() and __folio_lock_or_retry().
  5123. */
  5124. static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
  5125. {
  5126. pte_t entry;
  5127. if (unlikely(pmd_none(*vmf->pmd))) {
  5128. /*
  5129. * Leave __pte_alloc() until later: because vm_ops->fault may
  5130. * want to allocate huge page, and if we expose page table
  5131. * for an instant, it will be difficult to retract from
  5132. * concurrent faults and from rmap lookups.
  5133. */
  5134. vmf->pte = NULL;
  5135. vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
  5136. } else {
  5137. /*
  5138. * A regular pmd is established and it can't morph into a huge
  5139. * pmd by anon khugepaged, since that takes mmap_lock in write
  5140. * mode; but shmem or file collapse to THP could still morph
  5141. * it into a huge pmd: just retry later if so.
  5142. */
  5143. vmf->pte = pte_offset_map_nolock(vmf->vma->vm_mm, vmf->pmd,
  5144. vmf->address, &vmf->ptl);
  5145. if (unlikely(!vmf->pte))
  5146. return 0;
  5147. vmf->orig_pte = ptep_get_lockless(vmf->pte);
  5148. vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
  5149. if (pte_none(vmf->orig_pte)) {
  5150. pte_unmap(vmf->pte);
  5151. vmf->pte = NULL;
  5152. }
  5153. }
  5154. if (!vmf->pte)
  5155. return do_pte_missing(vmf);
  5156. if (!pte_present(vmf->orig_pte))
  5157. return do_swap_page(vmf);
  5158. if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
  5159. return do_numa_page(vmf);
  5160. spin_lock(vmf->ptl);
  5161. entry = vmf->orig_pte;
  5162. if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) {
  5163. update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
  5164. goto unlock;
  5165. }
  5166. if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
  5167. if (!pte_write(entry))
  5168. return do_wp_page(vmf);
  5169. else if (likely(vmf->flags & FAULT_FLAG_WRITE))
  5170. entry = pte_mkdirty(entry);
  5171. }
  5172. entry = pte_mkyoung(entry);
  5173. if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
  5174. vmf->flags & FAULT_FLAG_WRITE)) {
  5175. update_mmu_cache_range(vmf, vmf->vma, vmf->address,
  5176. vmf->pte, 1);
  5177. } else {
  5178. /* Skip spurious TLB flush for retried page fault */
  5179. if (vmf->flags & FAULT_FLAG_TRIED)
  5180. goto unlock;
  5181. /*
  5182. * This is needed only for protection faults but the arch code
  5183. * is not yet telling us if this is a protection fault or not.
  5184. * This still avoids useless tlb flushes for .text page faults
  5185. * with threads.
  5186. */
  5187. if (vmf->flags & FAULT_FLAG_WRITE)
  5188. flush_tlb_fix_spurious_fault(vmf->vma, vmf->address,
  5189. vmf->pte);
  5190. }
  5191. unlock:
  5192. pte_unmap_unlock(vmf->pte, vmf->ptl);
  5193. return 0;
  5194. }
  5195. /*
  5196. * On entry, we hold either the VMA lock or the mmap_lock
  5197. * (FAULT_FLAG_VMA_LOCK tells you which). If VM_FAULT_RETRY is set in
  5198. * the result, the mmap_lock is not held on exit. See filemap_fault()
  5199. * and __folio_lock_or_retry().
  5200. */
  5201. static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
  5202. unsigned long address, unsigned int flags)
  5203. {
  5204. struct vm_fault vmf = {
  5205. .vma = vma,
  5206. .address = address & PAGE_MASK,
  5207. .real_address = address,
  5208. .flags = flags,
  5209. .pgoff = linear_page_index(vma, address),
  5210. .gfp_mask = __get_fault_gfp_mask(vma),
  5211. };
  5212. struct mm_struct *mm = vma->vm_mm;
  5213. unsigned long vm_flags = vma->vm_flags;
  5214. pgd_t *pgd;
  5215. p4d_t *p4d;
  5216. vm_fault_t ret;
  5217. pgd = pgd_offset(mm, address);
  5218. p4d = p4d_alloc(mm, pgd, address);
  5219. if (!p4d)
  5220. return VM_FAULT_OOM;
  5221. vmf.pud = pud_alloc(mm, p4d, address);
  5222. if (!vmf.pud)
  5223. return VM_FAULT_OOM;
  5224. retry_pud:
  5225. if (pud_none(*vmf.pud) &&
  5226. thp_vma_allowable_order(vma, vm_flags,
  5227. TVA_IN_PF | TVA_ENFORCE_SYSFS, PUD_ORDER)) {
  5228. ret = create_huge_pud(&vmf);
  5229. if (!(ret & VM_FAULT_FALLBACK))
  5230. return ret;
  5231. } else {
  5232. pud_t orig_pud = *vmf.pud;
  5233. barrier();
  5234. if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
  5235. /*
  5236. * TODO once we support anonymous PUDs: NUMA case and
  5237. * FAULT_FLAG_UNSHARE handling.
  5238. */
  5239. if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
  5240. ret = wp_huge_pud(&vmf, orig_pud);
  5241. if (!(ret & VM_FAULT_FALLBACK))
  5242. return ret;
  5243. } else {
  5244. huge_pud_set_accessed(&vmf, orig_pud);
  5245. return 0;
  5246. }
  5247. }
  5248. }
  5249. vmf.pmd = pmd_alloc(mm, vmf.pud, address);
  5250. if (!vmf.pmd)
  5251. return VM_FAULT_OOM;
  5252. /* Huge pud page fault raced with pmd_alloc? */
  5253. if (pud_trans_unstable(vmf.pud))
  5254. goto retry_pud;
  5255. if (pmd_none(*vmf.pmd) &&
  5256. thp_vma_allowable_order(vma, vm_flags,
  5257. TVA_IN_PF | TVA_ENFORCE_SYSFS, PMD_ORDER)) {
  5258. ret = create_huge_pmd(&vmf);
  5259. if (!(ret & VM_FAULT_FALLBACK))
  5260. return ret;
  5261. } else {
  5262. vmf.orig_pmd = pmdp_get_lockless(vmf.pmd);
  5263. if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
  5264. VM_BUG_ON(thp_migration_supported() &&
  5265. !is_pmd_migration_entry(vmf.orig_pmd));
  5266. if (is_pmd_migration_entry(vmf.orig_pmd))
  5267. pmd_migration_entry_wait(mm, vmf.pmd);
  5268. return 0;
  5269. }
  5270. if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
  5271. if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
  5272. return do_huge_pmd_numa_page(&vmf);
  5273. if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
  5274. !pmd_write(vmf.orig_pmd)) {
  5275. ret = wp_huge_pmd(&vmf);
  5276. if (!(ret & VM_FAULT_FALLBACK))
  5277. return ret;
  5278. } else {
  5279. huge_pmd_set_accessed(&vmf);
  5280. return 0;
  5281. }
  5282. }
  5283. }
  5284. return handle_pte_fault(&vmf);
  5285. }
  5286. /**
  5287. * mm_account_fault - Do page fault accounting
  5288. * @mm: mm from which memcg should be extracted. It can be NULL.
  5289. * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
  5290. * of perf event counters, but we'll still do the per-task accounting to
  5291. * the task who triggered this page fault.
  5292. * @address: the faulted address.
  5293. * @flags: the fault flags.
  5294. * @ret: the fault retcode.
  5295. *
  5296. * This will take care of most of the page fault accounting. Meanwhile, it
  5297. * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
  5298. * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
  5299. * still be in per-arch page fault handlers at the entry of page fault.
  5300. */
  5301. static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs,
  5302. unsigned long address, unsigned int flags,
  5303. vm_fault_t ret)
  5304. {
  5305. bool major;
  5306. /* Incomplete faults will be accounted upon completion. */
  5307. if (ret & VM_FAULT_RETRY)
  5308. return;
  5309. /*
  5310. * To preserve the behavior of older kernels, PGFAULT counters record
  5311. * both successful and failed faults, as opposed to perf counters,
  5312. * which ignore failed cases.
  5313. */
  5314. count_vm_event(PGFAULT);
  5315. count_memcg_event_mm(mm, PGFAULT);
  5316. /*
  5317. * Do not account for unsuccessful faults (e.g. when the address wasn't
  5318. * valid). That includes arch_vma_access_permitted() failing before
  5319. * reaching here. So this is not a "this many hardware page faults"
  5320. * counter. We should use the hw profiling for that.
  5321. */
  5322. if (ret & VM_FAULT_ERROR)
  5323. return;
  5324. /*
  5325. * We define the fault as a major fault when the final successful fault
  5326. * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
  5327. * handle it immediately previously).
  5328. */
  5329. major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
  5330. if (major)
  5331. current->maj_flt++;
  5332. else
  5333. current->min_flt++;
  5334. /*
  5335. * If the fault is done for GUP, regs will be NULL. We only do the
  5336. * accounting for the per thread fault counters who triggered the
  5337. * fault, and we skip the perf event updates.
  5338. */
  5339. if (!regs)
  5340. return;
  5341. if (major)
  5342. perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
  5343. else
  5344. perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
  5345. }
  5346. #ifdef CONFIG_LRU_GEN
  5347. static void lru_gen_enter_fault(struct vm_area_struct *vma)
  5348. {
  5349. /* the LRU algorithm only applies to accesses with recency */
  5350. current->in_lru_fault = vma_has_recency(vma);
  5351. }
  5352. static void lru_gen_exit_fault(void)
  5353. {
  5354. current->in_lru_fault = false;
  5355. }
  5356. #else
  5357. static void lru_gen_enter_fault(struct vm_area_struct *vma)
  5358. {
  5359. }
  5360. static void lru_gen_exit_fault(void)
  5361. {
  5362. }
  5363. #endif /* CONFIG_LRU_GEN */
  5364. static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma,
  5365. unsigned int *flags)
  5366. {
  5367. if (unlikely(*flags & FAULT_FLAG_UNSHARE)) {
  5368. if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE))
  5369. return VM_FAULT_SIGSEGV;
  5370. /*
  5371. * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's
  5372. * just treat it like an ordinary read-fault otherwise.
  5373. */
  5374. if (!is_cow_mapping(vma->vm_flags))
  5375. *flags &= ~FAULT_FLAG_UNSHARE;
  5376. } else if (*flags & FAULT_FLAG_WRITE) {
  5377. /* Write faults on read-only mappings are impossible ... */
  5378. if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE)))
  5379. return VM_FAULT_SIGSEGV;
  5380. /* ... and FOLL_FORCE only applies to COW mappings. */
  5381. if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) &&
  5382. !is_cow_mapping(vma->vm_flags)))
  5383. return VM_FAULT_SIGSEGV;
  5384. }
  5385. #ifdef CONFIG_PER_VMA_LOCK
  5386. /*
  5387. * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of
  5388. * the assumption that lock is dropped on VM_FAULT_RETRY.
  5389. */
  5390. if (WARN_ON_ONCE((*flags &
  5391. (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) ==
  5392. (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))
  5393. return VM_FAULT_SIGSEGV;
  5394. #endif
  5395. return 0;
  5396. }
  5397. /*
  5398. * By the time we get here, we already hold the mm semaphore
  5399. *
  5400. * The mmap_lock may have been released depending on flags and our
  5401. * return value. See filemap_fault() and __folio_lock_or_retry().
  5402. */
  5403. vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
  5404. unsigned int flags, struct pt_regs *regs)
  5405. {
  5406. /* If the fault handler drops the mmap_lock, vma may be freed */
  5407. struct mm_struct *mm = vma->vm_mm;
  5408. vm_fault_t ret;
  5409. bool is_droppable;
  5410. __set_current_state(TASK_RUNNING);
  5411. ret = sanitize_fault_flags(vma, &flags);
  5412. if (ret)
  5413. goto out;
  5414. if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
  5415. flags & FAULT_FLAG_INSTRUCTION,
  5416. flags & FAULT_FLAG_REMOTE)) {
  5417. ret = VM_FAULT_SIGSEGV;
  5418. goto out;
  5419. }
  5420. is_droppable = !!(vma->vm_flags & VM_DROPPABLE);
  5421. /*
  5422. * Enable the memcg OOM handling for faults triggered in user
  5423. * space. Kernel faults are handled more gracefully.
  5424. */
  5425. if (flags & FAULT_FLAG_USER)
  5426. mem_cgroup_enter_user_fault();
  5427. lru_gen_enter_fault(vma);
  5428. if (unlikely(is_vm_hugetlb_page(vma)))
  5429. ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
  5430. else
  5431. ret = __handle_mm_fault(vma, address, flags);
  5432. /*
  5433. * Warning: It is no longer safe to dereference vma-> after this point,
  5434. * because mmap_lock might have been dropped by __handle_mm_fault(), so
  5435. * vma might be destroyed from underneath us.
  5436. */
  5437. lru_gen_exit_fault();
  5438. /* If the mapping is droppable, then errors due to OOM aren't fatal. */
  5439. if (is_droppable)
  5440. ret &= ~VM_FAULT_OOM;
  5441. if (flags & FAULT_FLAG_USER) {
  5442. mem_cgroup_exit_user_fault();
  5443. /*
  5444. * The task may have entered a memcg OOM situation but
  5445. * if the allocation error was handled gracefully (no
  5446. * VM_FAULT_OOM), there is no need to kill anything.
  5447. * Just clean up the OOM state peacefully.
  5448. */
  5449. if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
  5450. mem_cgroup_oom_synchronize(false);
  5451. }
  5452. out:
  5453. mm_account_fault(mm, regs, address, flags, ret);
  5454. return ret;
  5455. }
  5456. EXPORT_SYMBOL_GPL(handle_mm_fault);
  5457. #ifdef CONFIG_LOCK_MM_AND_FIND_VMA
  5458. #include <linux/extable.h>
  5459. static inline bool get_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
  5460. {
  5461. if (likely(mmap_read_trylock(mm)))
  5462. return true;
  5463. if (regs && !user_mode(regs)) {
  5464. unsigned long ip = exception_ip(regs);
  5465. if (!search_exception_tables(ip))
  5466. return false;
  5467. }
  5468. return !mmap_read_lock_killable(mm);
  5469. }
  5470. static inline bool mmap_upgrade_trylock(struct mm_struct *mm)
  5471. {
  5472. /*
  5473. * We don't have this operation yet.
  5474. *
  5475. * It should be easy enough to do: it's basically a
  5476. * atomic_long_try_cmpxchg_acquire()
  5477. * from RWSEM_READER_BIAS -> RWSEM_WRITER_LOCKED, but
  5478. * it also needs the proper lockdep magic etc.
  5479. */
  5480. return false;
  5481. }
  5482. static inline bool upgrade_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
  5483. {
  5484. mmap_read_unlock(mm);
  5485. if (regs && !user_mode(regs)) {
  5486. unsigned long ip = exception_ip(regs);
  5487. if (!search_exception_tables(ip))
  5488. return false;
  5489. }
  5490. return !mmap_write_lock_killable(mm);
  5491. }
  5492. /*
  5493. * Helper for page fault handling.
  5494. *
  5495. * This is kind of equivalend to "mmap_read_lock()" followed
  5496. * by "find_extend_vma()", except it's a lot more careful about
  5497. * the locking (and will drop the lock on failure).
  5498. *
  5499. * For example, if we have a kernel bug that causes a page
  5500. * fault, we don't want to just use mmap_read_lock() to get
  5501. * the mm lock, because that would deadlock if the bug were
  5502. * to happen while we're holding the mm lock for writing.
  5503. *
  5504. * So this checks the exception tables on kernel faults in
  5505. * order to only do this all for instructions that are actually
  5506. * expected to fault.
  5507. *
  5508. * We can also actually take the mm lock for writing if we
  5509. * need to extend the vma, which helps the VM layer a lot.
  5510. */
  5511. struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm,
  5512. unsigned long addr, struct pt_regs *regs)
  5513. {
  5514. struct vm_area_struct *vma;
  5515. if (!get_mmap_lock_carefully(mm, regs))
  5516. return NULL;
  5517. vma = find_vma(mm, addr);
  5518. if (likely(vma && (vma->vm_start <= addr)))
  5519. return vma;
  5520. /*
  5521. * Well, dang. We might still be successful, but only
  5522. * if we can extend a vma to do so.
  5523. */
  5524. if (!vma || !(vma->vm_flags & VM_GROWSDOWN)) {
  5525. mmap_read_unlock(mm);
  5526. return NULL;
  5527. }
  5528. /*
  5529. * We can try to upgrade the mmap lock atomically,
  5530. * in which case we can continue to use the vma
  5531. * we already looked up.
  5532. *
  5533. * Otherwise we'll have to drop the mmap lock and
  5534. * re-take it, and also look up the vma again,
  5535. * re-checking it.
  5536. */
  5537. if (!mmap_upgrade_trylock(mm)) {
  5538. if (!upgrade_mmap_lock_carefully(mm, regs))
  5539. return NULL;
  5540. vma = find_vma(mm, addr);
  5541. if (!vma)
  5542. goto fail;
  5543. if (vma->vm_start <= addr)
  5544. goto success;
  5545. if (!(vma->vm_flags & VM_GROWSDOWN))
  5546. goto fail;
  5547. }
  5548. if (expand_stack_locked(vma, addr))
  5549. goto fail;
  5550. success:
  5551. mmap_write_downgrade(mm);
  5552. return vma;
  5553. fail:
  5554. mmap_write_unlock(mm);
  5555. return NULL;
  5556. }
  5557. #endif
  5558. #ifdef CONFIG_PER_VMA_LOCK
  5559. /*
  5560. * Lookup and lock a VMA under RCU protection. Returned VMA is guaranteed to be
  5561. * stable and not isolated. If the VMA is not found or is being modified the
  5562. * function returns NULL.
  5563. */
  5564. struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,
  5565. unsigned long address)
  5566. {
  5567. MA_STATE(mas, &mm->mm_mt, address, address);
  5568. struct vm_area_struct *vma;
  5569. rcu_read_lock();
  5570. retry:
  5571. vma = mas_walk(&mas);
  5572. if (!vma)
  5573. goto inval;
  5574. if (!vma_start_read(vma))
  5575. goto inval;
  5576. /* Check if the VMA got isolated after we found it */
  5577. if (vma->detached) {
  5578. vma_end_read(vma);
  5579. count_vm_vma_lock_event(VMA_LOCK_MISS);
  5580. /* The area was replaced with another one */
  5581. goto retry;
  5582. }
  5583. /*
  5584. * At this point, we have a stable reference to a VMA: The VMA is
  5585. * locked and we know it hasn't already been isolated.
  5586. * From here on, we can access the VMA without worrying about which
  5587. * fields are accessible for RCU readers.
  5588. */
  5589. /* Check since vm_start/vm_end might change before we lock the VMA */
  5590. if (unlikely(address < vma->vm_start || address >= vma->vm_end))
  5591. goto inval_end_read;
  5592. rcu_read_unlock();
  5593. return vma;
  5594. inval_end_read:
  5595. vma_end_read(vma);
  5596. inval:
  5597. rcu_read_unlock();
  5598. count_vm_vma_lock_event(VMA_LOCK_ABORT);
  5599. return NULL;
  5600. }
  5601. #endif /* CONFIG_PER_VMA_LOCK */
  5602. #ifndef __PAGETABLE_P4D_FOLDED
  5603. /*
  5604. * Allocate p4d page table.
  5605. * We've already handled the fast-path in-line.
  5606. */
  5607. int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
  5608. {
  5609. p4d_t *new = p4d_alloc_one(mm, address);
  5610. if (!new)
  5611. return -ENOMEM;
  5612. spin_lock(&mm->page_table_lock);
  5613. if (pgd_present(*pgd)) { /* Another has populated it */
  5614. p4d_free(mm, new);
  5615. } else {
  5616. smp_wmb(); /* See comment in pmd_install() */
  5617. pgd_populate(mm, pgd, new);
  5618. }
  5619. spin_unlock(&mm->page_table_lock);
  5620. return 0;
  5621. }
  5622. #endif /* __PAGETABLE_P4D_FOLDED */
  5623. #ifndef __PAGETABLE_PUD_FOLDED
  5624. /*
  5625. * Allocate page upper directory.
  5626. * We've already handled the fast-path in-line.
  5627. */
  5628. int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
  5629. {
  5630. pud_t *new = pud_alloc_one(mm, address);
  5631. if (!new)
  5632. return -ENOMEM;
  5633. spin_lock(&mm->page_table_lock);
  5634. if (!p4d_present(*p4d)) {
  5635. mm_inc_nr_puds(mm);
  5636. smp_wmb(); /* See comment in pmd_install() */
  5637. p4d_populate(mm, p4d, new);
  5638. } else /* Another has populated it */
  5639. pud_free(mm, new);
  5640. spin_unlock(&mm->page_table_lock);
  5641. return 0;
  5642. }
  5643. #endif /* __PAGETABLE_PUD_FOLDED */
  5644. #ifndef __PAGETABLE_PMD_FOLDED
  5645. /*
  5646. * Allocate page middle directory.
  5647. * We've already handled the fast-path in-line.
  5648. */
  5649. int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
  5650. {
  5651. spinlock_t *ptl;
  5652. pmd_t *new = pmd_alloc_one(mm, address);
  5653. if (!new)
  5654. return -ENOMEM;
  5655. ptl = pud_lock(mm, pud);
  5656. if (!pud_present(*pud)) {
  5657. mm_inc_nr_pmds(mm);
  5658. smp_wmb(); /* See comment in pmd_install() */
  5659. pud_populate(mm, pud, new);
  5660. } else { /* Another has populated it */
  5661. pmd_free(mm, new);
  5662. }
  5663. spin_unlock(ptl);
  5664. return 0;
  5665. }
  5666. #endif /* __PAGETABLE_PMD_FOLDED */
  5667. static inline void pfnmap_args_setup(struct follow_pfnmap_args *args,
  5668. spinlock_t *lock, pte_t *ptep,
  5669. pgprot_t pgprot, unsigned long pfn_base,
  5670. unsigned long addr_mask, bool writable,
  5671. bool special)
  5672. {
  5673. args->lock = lock;
  5674. args->ptep = ptep;
  5675. args->pfn = pfn_base + ((args->address & ~addr_mask) >> PAGE_SHIFT);
  5676. args->pgprot = pgprot;
  5677. args->writable = writable;
  5678. args->special = special;
  5679. }
  5680. static inline void pfnmap_lockdep_assert(struct vm_area_struct *vma)
  5681. {
  5682. #ifdef CONFIG_LOCKDEP
  5683. struct file *file = vma->vm_file;
  5684. struct address_space *mapping = file ? file->f_mapping : NULL;
  5685. if (mapping)
  5686. lockdep_assert(lockdep_is_held(&vma->vm_file->f_mapping->i_mmap_rwsem) ||
  5687. lockdep_is_held(&vma->vm_mm->mmap_lock));
  5688. else
  5689. lockdep_assert(lockdep_is_held(&vma->vm_mm->mmap_lock));
  5690. #endif
  5691. }
  5692. /**
  5693. * follow_pfnmap_start() - Look up a pfn mapping at a user virtual address
  5694. * @args: Pointer to struct @follow_pfnmap_args
  5695. *
  5696. * The caller needs to setup args->vma and args->address to point to the
  5697. * virtual address as the target of such lookup. On a successful return,
  5698. * the results will be put into other output fields.
  5699. *
  5700. * After the caller finished using the fields, the caller must invoke
  5701. * another follow_pfnmap_end() to proper releases the locks and resources
  5702. * of such look up request.
  5703. *
  5704. * During the start() and end() calls, the results in @args will be valid
  5705. * as proper locks will be held. After the end() is called, all the fields
  5706. * in @follow_pfnmap_args will be invalid to be further accessed. Further
  5707. * use of such information after end() may require proper synchronizations
  5708. * by the caller with page table updates, otherwise it can create a
  5709. * security bug.
  5710. *
  5711. * If the PTE maps a refcounted page, callers are responsible to protect
  5712. * against invalidation with MMU notifiers; otherwise access to the PFN at
  5713. * a later point in time can trigger use-after-free.
  5714. *
  5715. * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
  5716. * should be taken for read, and the mmap semaphore cannot be released
  5717. * before the end() is invoked.
  5718. *
  5719. * This function must not be used to modify PTE content.
  5720. *
  5721. * Return: zero on success, negative otherwise.
  5722. */
  5723. int follow_pfnmap_start(struct follow_pfnmap_args *args)
  5724. {
  5725. struct vm_area_struct *vma = args->vma;
  5726. unsigned long address = args->address;
  5727. struct mm_struct *mm = vma->vm_mm;
  5728. spinlock_t *lock;
  5729. pgd_t *pgdp;
  5730. p4d_t *p4dp, p4d;
  5731. pud_t *pudp, pud;
  5732. pmd_t *pmdp, pmd;
  5733. pte_t *ptep, pte;
  5734. pfnmap_lockdep_assert(vma);
  5735. if (unlikely(address < vma->vm_start || address >= vma->vm_end))
  5736. goto out;
  5737. if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
  5738. goto out;
  5739. retry:
  5740. pgdp = pgd_offset(mm, address);
  5741. if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp)))
  5742. goto out;
  5743. p4dp = p4d_offset(pgdp, address);
  5744. p4d = READ_ONCE(*p4dp);
  5745. if (p4d_none(p4d) || unlikely(p4d_bad(p4d)))
  5746. goto out;
  5747. pudp = pud_offset(p4dp, address);
  5748. pud = READ_ONCE(*pudp);
  5749. if (pud_none(pud))
  5750. goto out;
  5751. if (pud_leaf(pud)) {
  5752. lock = pud_lock(mm, pudp);
  5753. if (!unlikely(pud_leaf(pud))) {
  5754. spin_unlock(lock);
  5755. goto retry;
  5756. }
  5757. pfnmap_args_setup(args, lock, NULL, pud_pgprot(pud),
  5758. pud_pfn(pud), PUD_MASK, pud_write(pud),
  5759. pud_special(pud));
  5760. return 0;
  5761. }
  5762. pmdp = pmd_offset(pudp, address);
  5763. pmd = pmdp_get_lockless(pmdp);
  5764. if (pmd_leaf(pmd)) {
  5765. lock = pmd_lock(mm, pmdp);
  5766. if (!unlikely(pmd_leaf(pmd))) {
  5767. spin_unlock(lock);
  5768. goto retry;
  5769. }
  5770. pfnmap_args_setup(args, lock, NULL, pmd_pgprot(pmd),
  5771. pmd_pfn(pmd), PMD_MASK, pmd_write(pmd),
  5772. pmd_special(pmd));
  5773. return 0;
  5774. }
  5775. ptep = pte_offset_map_lock(mm, pmdp, address, &lock);
  5776. if (!ptep)
  5777. goto out;
  5778. pte = ptep_get(ptep);
  5779. if (!pte_present(pte))
  5780. goto unlock;
  5781. pfnmap_args_setup(args, lock, ptep, pte_pgprot(pte),
  5782. pte_pfn(pte), PAGE_MASK, pte_write(pte),
  5783. pte_special(pte));
  5784. return 0;
  5785. unlock:
  5786. pte_unmap_unlock(ptep, lock);
  5787. out:
  5788. return -EINVAL;
  5789. }
  5790. EXPORT_SYMBOL_GPL(follow_pfnmap_start);
  5791. /**
  5792. * follow_pfnmap_end(): End a follow_pfnmap_start() process
  5793. * @args: Pointer to struct @follow_pfnmap_args
  5794. *
  5795. * Must be used in pair of follow_pfnmap_start(). See the start() function
  5796. * above for more information.
  5797. */
  5798. void follow_pfnmap_end(struct follow_pfnmap_args *args)
  5799. {
  5800. if (args->lock)
  5801. spin_unlock(args->lock);
  5802. if (args->ptep)
  5803. pte_unmap(args->ptep);
  5804. }
  5805. EXPORT_SYMBOL_GPL(follow_pfnmap_end);
  5806. #ifdef CONFIG_HAVE_IOREMAP_PROT
  5807. /**
  5808. * generic_access_phys - generic implementation for iomem mmap access
  5809. * @vma: the vma to access
  5810. * @addr: userspace address, not relative offset within @vma
  5811. * @buf: buffer to read/write
  5812. * @len: length of transfer
  5813. * @write: set to FOLL_WRITE when writing, otherwise reading
  5814. *
  5815. * This is a generic implementation for &vm_operations_struct.access for an
  5816. * iomem mapping. This callback is used by access_process_vm() when the @vma is
  5817. * not page based.
  5818. */
  5819. int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
  5820. void *buf, int len, int write)
  5821. {
  5822. resource_size_t phys_addr;
  5823. unsigned long prot = 0;
  5824. void __iomem *maddr;
  5825. int offset = offset_in_page(addr);
  5826. int ret = -EINVAL;
  5827. bool writable;
  5828. struct follow_pfnmap_args args = { .vma = vma, .address = addr };
  5829. retry:
  5830. if (follow_pfnmap_start(&args))
  5831. return -EINVAL;
  5832. prot = pgprot_val(args.pgprot);
  5833. phys_addr = (resource_size_t)args.pfn << PAGE_SHIFT;
  5834. writable = args.writable;
  5835. follow_pfnmap_end(&args);
  5836. if ((write & FOLL_WRITE) && !writable)
  5837. return -EINVAL;
  5838. maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
  5839. if (!maddr)
  5840. return -ENOMEM;
  5841. if (follow_pfnmap_start(&args))
  5842. goto out_unmap;
  5843. if ((prot != pgprot_val(args.pgprot)) ||
  5844. (phys_addr != (args.pfn << PAGE_SHIFT)) ||
  5845. (writable != args.writable)) {
  5846. follow_pfnmap_end(&args);
  5847. iounmap(maddr);
  5848. goto retry;
  5849. }
  5850. if (write)
  5851. memcpy_toio(maddr + offset, buf, len);
  5852. else
  5853. memcpy_fromio(buf, maddr + offset, len);
  5854. ret = len;
  5855. follow_pfnmap_end(&args);
  5856. out_unmap:
  5857. iounmap(maddr);
  5858. return ret;
  5859. }
  5860. EXPORT_SYMBOL_GPL(generic_access_phys);
  5861. #endif
  5862. /*
  5863. * Access another process' address space as given in mm.
  5864. */
  5865. static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
  5866. void *buf, int len, unsigned int gup_flags)
  5867. {
  5868. void *old_buf = buf;
  5869. int write = gup_flags & FOLL_WRITE;
  5870. if (mmap_read_lock_killable(mm))
  5871. return 0;
  5872. /* Untag the address before looking up the VMA */
  5873. addr = untagged_addr_remote(mm, addr);
  5874. /* Avoid triggering the temporary warning in __get_user_pages */
  5875. if (!vma_lookup(mm, addr) && !expand_stack(mm, addr))
  5876. return 0;
  5877. /* ignore errors, just check how much was successfully transferred */
  5878. while (len) {
  5879. int bytes, offset;
  5880. void *maddr;
  5881. struct vm_area_struct *vma = NULL;
  5882. struct page *page = get_user_page_vma_remote(mm, addr,
  5883. gup_flags, &vma);
  5884. if (IS_ERR(page)) {
  5885. /* We might need to expand the stack to access it */
  5886. vma = vma_lookup(mm, addr);
  5887. if (!vma) {
  5888. vma = expand_stack(mm, addr);
  5889. /* mmap_lock was dropped on failure */
  5890. if (!vma)
  5891. return buf - old_buf;
  5892. /* Try again if stack expansion worked */
  5893. continue;
  5894. }
  5895. /*
  5896. * Check if this is a VM_IO | VM_PFNMAP VMA, which
  5897. * we can access using slightly different code.
  5898. */
  5899. bytes = 0;
  5900. #ifdef CONFIG_HAVE_IOREMAP_PROT
  5901. if (vma->vm_ops && vma->vm_ops->access)
  5902. bytes = vma->vm_ops->access(vma, addr, buf,
  5903. len, write);
  5904. #endif
  5905. if (bytes <= 0)
  5906. break;
  5907. } else {
  5908. bytes = len;
  5909. offset = addr & (PAGE_SIZE-1);
  5910. if (bytes > PAGE_SIZE-offset)
  5911. bytes = PAGE_SIZE-offset;
  5912. maddr = kmap_local_page(page);
  5913. if (write) {
  5914. copy_to_user_page(vma, page, addr,
  5915. maddr + offset, buf, bytes);
  5916. set_page_dirty_lock(page);
  5917. } else {
  5918. copy_from_user_page(vma, page, addr,
  5919. buf, maddr + offset, bytes);
  5920. }
  5921. unmap_and_put_page(page, maddr);
  5922. }
  5923. len -= bytes;
  5924. buf += bytes;
  5925. addr += bytes;
  5926. }
  5927. mmap_read_unlock(mm);
  5928. return buf - old_buf;
  5929. }
  5930. /**
  5931. * access_remote_vm - access another process' address space
  5932. * @mm: the mm_struct of the target address space
  5933. * @addr: start address to access
  5934. * @buf: source or destination buffer
  5935. * @len: number of bytes to transfer
  5936. * @gup_flags: flags modifying lookup behaviour
  5937. *
  5938. * The caller must hold a reference on @mm.
  5939. *
  5940. * Return: number of bytes copied from source to destination.
  5941. */
  5942. int access_remote_vm(struct mm_struct *mm, unsigned long addr,
  5943. void *buf, int len, unsigned int gup_flags)
  5944. {
  5945. return __access_remote_vm(mm, addr, buf, len, gup_flags);
  5946. }
  5947. /*
  5948. * Access another process' address space.
  5949. * Source/target buffer must be kernel space,
  5950. * Do not walk the page table directly, use get_user_pages
  5951. */
  5952. int access_process_vm(struct task_struct *tsk, unsigned long addr,
  5953. void *buf, int len, unsigned int gup_flags)
  5954. {
  5955. struct mm_struct *mm;
  5956. int ret;
  5957. mm = get_task_mm(tsk);
  5958. if (!mm)
  5959. return 0;
  5960. ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
  5961. mmput(mm);
  5962. return ret;
  5963. }
  5964. EXPORT_SYMBOL_GPL(access_process_vm);
  5965. /*
  5966. * Print the name of a VMA.
  5967. */
  5968. void print_vma_addr(char *prefix, unsigned long ip)
  5969. {
  5970. struct mm_struct *mm = current->mm;
  5971. struct vm_area_struct *vma;
  5972. /*
  5973. * we might be running from an atomic context so we cannot sleep
  5974. */
  5975. if (!mmap_read_trylock(mm))
  5976. return;
  5977. vma = vma_lookup(mm, ip);
  5978. if (vma && vma->vm_file) {
  5979. struct file *f = vma->vm_file;
  5980. ip -= vma->vm_start;
  5981. ip += vma->vm_pgoff << PAGE_SHIFT;
  5982. printk("%s%pD[%lx,%lx+%lx]", prefix, f, ip,
  5983. vma->vm_start,
  5984. vma->vm_end - vma->vm_start);
  5985. }
  5986. mmap_read_unlock(mm);
  5987. }
  5988. #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
  5989. void __might_fault(const char *file, int line)
  5990. {
  5991. if (pagefault_disabled())
  5992. return;
  5993. __might_sleep(file, line);
  5994. if (current->mm)
  5995. might_lock_read(&current->mm->mmap_lock);
  5996. }
  5997. EXPORT_SYMBOL(__might_fault);
  5998. #endif
  5999. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
  6000. /*
  6001. * Process all subpages of the specified huge page with the specified
  6002. * operation. The target subpage will be processed last to keep its
  6003. * cache lines hot.
  6004. */
  6005. static inline int process_huge_page(
  6006. unsigned long addr_hint, unsigned int nr_pages,
  6007. int (*process_subpage)(unsigned long addr, int idx, void *arg),
  6008. void *arg)
  6009. {
  6010. int i, n, base, l, ret;
  6011. unsigned long addr = addr_hint &
  6012. ~(((unsigned long)nr_pages << PAGE_SHIFT) - 1);
  6013. /* Process target subpage last to keep its cache lines hot */
  6014. might_sleep();
  6015. n = (addr_hint - addr) / PAGE_SIZE;
  6016. if (2 * n <= nr_pages) {
  6017. /* If target subpage in first half of huge page */
  6018. base = 0;
  6019. l = n;
  6020. /* Process subpages at the end of huge page */
  6021. for (i = nr_pages - 1; i >= 2 * n; i--) {
  6022. cond_resched();
  6023. ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
  6024. if (ret)
  6025. return ret;
  6026. }
  6027. } else {
  6028. /* If target subpage in second half of huge page */
  6029. base = nr_pages - 2 * (nr_pages - n);
  6030. l = nr_pages - n;
  6031. /* Process subpages at the begin of huge page */
  6032. for (i = 0; i < base; i++) {
  6033. cond_resched();
  6034. ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
  6035. if (ret)
  6036. return ret;
  6037. }
  6038. }
  6039. /*
  6040. * Process remaining subpages in left-right-left-right pattern
  6041. * towards the target subpage
  6042. */
  6043. for (i = 0; i < l; i++) {
  6044. int left_idx = base + i;
  6045. int right_idx = base + 2 * l - 1 - i;
  6046. cond_resched();
  6047. ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
  6048. if (ret)
  6049. return ret;
  6050. cond_resched();
  6051. ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
  6052. if (ret)
  6053. return ret;
  6054. }
  6055. return 0;
  6056. }
  6057. static void clear_gigantic_page(struct folio *folio, unsigned long addr_hint,
  6058. unsigned int nr_pages)
  6059. {
  6060. unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(folio));
  6061. int i;
  6062. might_sleep();
  6063. for (i = 0; i < nr_pages; i++) {
  6064. cond_resched();
  6065. clear_user_highpage(folio_page(folio, i), addr + i * PAGE_SIZE);
  6066. }
  6067. }
  6068. static int clear_subpage(unsigned long addr, int idx, void *arg)
  6069. {
  6070. struct folio *folio = arg;
  6071. clear_user_highpage(folio_page(folio, idx), addr);
  6072. return 0;
  6073. }
  6074. /**
  6075. * folio_zero_user - Zero a folio which will be mapped to userspace.
  6076. * @folio: The folio to zero.
  6077. * @addr_hint: The address will be accessed or the base address if uncelar.
  6078. */
  6079. void folio_zero_user(struct folio *folio, unsigned long addr_hint)
  6080. {
  6081. unsigned int nr_pages = folio_nr_pages(folio);
  6082. if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
  6083. clear_gigantic_page(folio, addr_hint, nr_pages);
  6084. else
  6085. process_huge_page(addr_hint, nr_pages, clear_subpage, folio);
  6086. }
  6087. static int copy_user_gigantic_page(struct folio *dst, struct folio *src,
  6088. unsigned long addr_hint,
  6089. struct vm_area_struct *vma,
  6090. unsigned int nr_pages)
  6091. {
  6092. unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(dst));
  6093. struct page *dst_page;
  6094. struct page *src_page;
  6095. int i;
  6096. for (i = 0; i < nr_pages; i++) {
  6097. dst_page = folio_page(dst, i);
  6098. src_page = folio_page(src, i);
  6099. cond_resched();
  6100. if (copy_mc_user_highpage(dst_page, src_page,
  6101. addr + i*PAGE_SIZE, vma))
  6102. return -EHWPOISON;
  6103. }
  6104. return 0;
  6105. }
  6106. struct copy_subpage_arg {
  6107. struct folio *dst;
  6108. struct folio *src;
  6109. struct vm_area_struct *vma;
  6110. };
  6111. static int copy_subpage(unsigned long addr, int idx, void *arg)
  6112. {
  6113. struct copy_subpage_arg *copy_arg = arg;
  6114. struct page *dst = folio_page(copy_arg->dst, idx);
  6115. struct page *src = folio_page(copy_arg->src, idx);
  6116. if (copy_mc_user_highpage(dst, src, addr, copy_arg->vma))
  6117. return -EHWPOISON;
  6118. return 0;
  6119. }
  6120. int copy_user_large_folio(struct folio *dst, struct folio *src,
  6121. unsigned long addr_hint, struct vm_area_struct *vma)
  6122. {
  6123. unsigned int nr_pages = folio_nr_pages(dst);
  6124. struct copy_subpage_arg arg = {
  6125. .dst = dst,
  6126. .src = src,
  6127. .vma = vma,
  6128. };
  6129. if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
  6130. return copy_user_gigantic_page(dst, src, addr_hint, vma, nr_pages);
  6131. return process_huge_page(addr_hint, nr_pages, copy_subpage, &arg);
  6132. }
  6133. long copy_folio_from_user(struct folio *dst_folio,
  6134. const void __user *usr_src,
  6135. bool allow_pagefault)
  6136. {
  6137. void *kaddr;
  6138. unsigned long i, rc = 0;
  6139. unsigned int nr_pages = folio_nr_pages(dst_folio);
  6140. unsigned long ret_val = nr_pages * PAGE_SIZE;
  6141. struct page *subpage;
  6142. for (i = 0; i < nr_pages; i++) {
  6143. subpage = folio_page(dst_folio, i);
  6144. kaddr = kmap_local_page(subpage);
  6145. if (!allow_pagefault)
  6146. pagefault_disable();
  6147. rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE);
  6148. if (!allow_pagefault)
  6149. pagefault_enable();
  6150. kunmap_local(kaddr);
  6151. ret_val -= (PAGE_SIZE - rc);
  6152. if (rc)
  6153. break;
  6154. flush_dcache_page(subpage);
  6155. cond_resched();
  6156. }
  6157. return ret_val;
  6158. }
  6159. #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
  6160. #if defined(CONFIG_SPLIT_PTE_PTLOCKS) && ALLOC_SPLIT_PTLOCKS
  6161. static struct kmem_cache *page_ptl_cachep;
  6162. void __init ptlock_cache_init(void)
  6163. {
  6164. page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
  6165. SLAB_PANIC, NULL);
  6166. }
  6167. bool ptlock_alloc(struct ptdesc *ptdesc)
  6168. {
  6169. spinlock_t *ptl;
  6170. ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
  6171. if (!ptl)
  6172. return false;
  6173. ptdesc->ptl = ptl;
  6174. return true;
  6175. }
  6176. void ptlock_free(struct ptdesc *ptdesc)
  6177. {
  6178. kmem_cache_free(page_ptl_cachep, ptdesc->ptl);
  6179. }
  6180. #endif
  6181. void vma_pgtable_walk_begin(struct vm_area_struct *vma)
  6182. {
  6183. if (is_vm_hugetlb_page(vma))
  6184. hugetlb_vma_lock_read(vma);
  6185. }
  6186. void vma_pgtable_walk_end(struct vm_area_struct *vma)
  6187. {
  6188. if (is_vm_hugetlb_page(vma))
  6189. hugetlb_vma_unlock_read(vma);
  6190. }