memory.c 169 KB

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