memory.c 191 KB

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