memory.c 210 KB

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