mmu.c 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905
  1. /*
  2. * Kernel-based Virtual Machine driver for Linux
  3. *
  4. * This module enables machines with Intel VT-x extensions to run virtual
  5. * machines without emulation or binary translation.
  6. *
  7. * MMU support
  8. *
  9. * Copyright (C) 2006 Qumranet, Inc.
  10. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  11. *
  12. * Authors:
  13. * Yaniv Kamay <yaniv@qumranet.com>
  14. * Avi Kivity <avi@qumranet.com>
  15. *
  16. * This work is licensed under the terms of the GNU GPL, version 2. See
  17. * the COPYING file in the top-level directory.
  18. *
  19. */
  20. #include "irq.h"
  21. #include "mmu.h"
  22. #include "x86.h"
  23. #include "kvm_cache_regs.h"
  24. #include "cpuid.h"
  25. #include <linux/kvm_host.h>
  26. #include <linux/types.h>
  27. #include <linux/string.h>
  28. #include <linux/mm.h>
  29. #include <linux/highmem.h>
  30. #include <linux/moduleparam.h>
  31. #include <linux/export.h>
  32. #include <linux/swap.h>
  33. #include <linux/hugetlb.h>
  34. #include <linux/compiler.h>
  35. #include <linux/srcu.h>
  36. #include <linux/slab.h>
  37. #include <linux/sched/signal.h>
  38. #include <linux/uaccess.h>
  39. #include <linux/hash.h>
  40. #include <linux/kern_levels.h>
  41. #include <linux/kthread.h>
  42. #include <asm/page.h>
  43. #include <asm/cmpxchg.h>
  44. #include <asm/io.h>
  45. #include <asm/vmx.h>
  46. #include <asm/kvm_page_track.h>
  47. #include "trace.h"
  48. extern bool itlb_multihit_kvm_mitigation;
  49. static int __read_mostly nx_huge_pages = -1;
  50. static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
  51. static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
  52. static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
  53. static struct kernel_param_ops nx_huge_pages_ops = {
  54. .set = set_nx_huge_pages,
  55. .get = param_get_bool,
  56. };
  57. static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
  58. .set = set_nx_huge_pages_recovery_ratio,
  59. .get = param_get_uint,
  60. };
  61. module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
  62. __MODULE_PARM_TYPE(nx_huge_pages, "bool");
  63. module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
  64. &nx_huge_pages_recovery_ratio, 0644);
  65. __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
  66. /*
  67. * When setting this variable to true it enables Two-Dimensional-Paging
  68. * where the hardware walks 2 page tables:
  69. * 1. the guest-virtual to guest-physical
  70. * 2. while doing 1. it walks guest-physical to host-physical
  71. * If the hardware supports that we don't need to do shadow paging.
  72. */
  73. bool tdp_enabled = false;
  74. enum {
  75. AUDIT_PRE_PAGE_FAULT,
  76. AUDIT_POST_PAGE_FAULT,
  77. AUDIT_PRE_PTE_WRITE,
  78. AUDIT_POST_PTE_WRITE,
  79. AUDIT_PRE_SYNC,
  80. AUDIT_POST_SYNC
  81. };
  82. #undef MMU_DEBUG
  83. #ifdef MMU_DEBUG
  84. static bool dbg = 0;
  85. module_param(dbg, bool, 0644);
  86. #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
  87. #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
  88. #define MMU_WARN_ON(x) WARN_ON(x)
  89. #else
  90. #define pgprintk(x...) do { } while (0)
  91. #define rmap_printk(x...) do { } while (0)
  92. #define MMU_WARN_ON(x) do { } while (0)
  93. #endif
  94. #define PTE_PREFETCH_NUM 8
  95. #define PT_FIRST_AVAIL_BITS_SHIFT 10
  96. #define PT64_SECOND_AVAIL_BITS_SHIFT 52
  97. #define PT64_LEVEL_BITS 9
  98. #define PT64_LEVEL_SHIFT(level) \
  99. (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
  100. #define PT64_INDEX(address, level)\
  101. (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
  102. #define PT32_LEVEL_BITS 10
  103. #define PT32_LEVEL_SHIFT(level) \
  104. (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
  105. #define PT32_LVL_OFFSET_MASK(level) \
  106. (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
  107. * PT32_LEVEL_BITS))) - 1))
  108. #define PT32_INDEX(address, level)\
  109. (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
  110. #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
  111. #define PT64_DIR_BASE_ADDR_MASK \
  112. (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
  113. #define PT64_LVL_ADDR_MASK(level) \
  114. (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
  115. * PT64_LEVEL_BITS))) - 1))
  116. #define PT64_LVL_OFFSET_MASK(level) \
  117. (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
  118. * PT64_LEVEL_BITS))) - 1))
  119. #define PT32_BASE_ADDR_MASK PAGE_MASK
  120. #define PT32_DIR_BASE_ADDR_MASK \
  121. (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
  122. #define PT32_LVL_ADDR_MASK(level) \
  123. (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
  124. * PT32_LEVEL_BITS))) - 1))
  125. #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
  126. | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
  127. #define ACC_EXEC_MASK 1
  128. #define ACC_WRITE_MASK PT_WRITABLE_MASK
  129. #define ACC_USER_MASK PT_USER_MASK
  130. #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
  131. /* The mask for the R/X bits in EPT PTEs */
  132. #define PT64_EPT_READABLE_MASK 0x1ull
  133. #define PT64_EPT_EXECUTABLE_MASK 0x4ull
  134. #include <trace/events/kvm.h>
  135. #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
  136. #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
  137. #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
  138. /* make pte_list_desc fit well in cache line */
  139. #define PTE_LIST_EXT 3
  140. /*
  141. * Return values of handle_mmio_page_fault and mmu.page_fault:
  142. * RET_PF_RETRY: let CPU fault again on the address.
  143. * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
  144. *
  145. * For handle_mmio_page_fault only:
  146. * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
  147. */
  148. enum {
  149. RET_PF_RETRY = 0,
  150. RET_PF_EMULATE = 1,
  151. RET_PF_INVALID = 2,
  152. };
  153. struct pte_list_desc {
  154. u64 *sptes[PTE_LIST_EXT];
  155. struct pte_list_desc *more;
  156. };
  157. struct kvm_shadow_walk_iterator {
  158. u64 addr;
  159. hpa_t shadow_addr;
  160. u64 *sptep;
  161. int level;
  162. unsigned index;
  163. };
  164. #define for_each_shadow_entry(_vcpu, _addr, _walker) \
  165. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  166. shadow_walk_okay(&(_walker)); \
  167. shadow_walk_next(&(_walker)))
  168. #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
  169. for (shadow_walk_init(&(_walker), _vcpu, _addr); \
  170. shadow_walk_okay(&(_walker)) && \
  171. ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
  172. __shadow_walk_next(&(_walker), spte))
  173. static struct kmem_cache *pte_list_desc_cache;
  174. static struct kmem_cache *mmu_page_header_cache;
  175. static struct percpu_counter kvm_total_used_mmu_pages;
  176. static u64 __read_mostly shadow_nx_mask;
  177. static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
  178. static u64 __read_mostly shadow_user_mask;
  179. static u64 __read_mostly shadow_accessed_mask;
  180. static u64 __read_mostly shadow_dirty_mask;
  181. static u64 __read_mostly shadow_mmio_mask;
  182. static u64 __read_mostly shadow_mmio_value;
  183. static u64 __read_mostly shadow_present_mask;
  184. static u64 __read_mostly shadow_me_mask;
  185. /*
  186. * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
  187. * Non-present SPTEs with shadow_acc_track_value set are in place for access
  188. * tracking.
  189. */
  190. static u64 __read_mostly shadow_acc_track_mask;
  191. static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
  192. /*
  193. * The mask/shift to use for saving the original R/X bits when marking the PTE
  194. * as not-present for access tracking purposes. We do not save the W bit as the
  195. * PTEs being access tracked also need to be dirty tracked, so the W bit will be
  196. * restored only when a write is attempted to the page.
  197. */
  198. static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
  199. PT64_EPT_EXECUTABLE_MASK;
  200. static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
  201. /*
  202. * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
  203. * to guard against L1TF attacks.
  204. */
  205. static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  206. /*
  207. * The number of high-order 1 bits to use in the mask above.
  208. */
  209. static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
  210. /*
  211. * In some cases, we need to preserve the GFN of a non-present or reserved
  212. * SPTE when we usurp the upper five bits of the physical address space to
  213. * defend against L1TF, e.g. for MMIO SPTEs. To preserve the GFN, we'll
  214. * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
  215. * left into the reserved bits, i.e. the GFN in the SPTE will be split into
  216. * high and low parts. This mask covers the lower bits of the GFN.
  217. */
  218. static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
  219. /*
  220. * The number of non-reserved physical address bits irrespective of features
  221. * that repurpose legal bits, e.g. MKTME.
  222. */
  223. static u8 __read_mostly shadow_phys_bits;
  224. static void mmu_spte_set(u64 *sptep, u64 spte);
  225. static void mmu_free_roots(struct kvm_vcpu *vcpu);
  226. static bool is_executable_pte(u64 spte);
  227. #define CREATE_TRACE_POINTS
  228. #include "mmutrace.h"
  229. void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
  230. {
  231. BUG_ON((mmio_mask & mmio_value) != mmio_value);
  232. WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
  233. WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
  234. shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
  235. shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
  236. }
  237. EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
  238. static bool is_mmio_spte(u64 spte)
  239. {
  240. return (spte & shadow_mmio_mask) == shadow_mmio_value;
  241. }
  242. static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
  243. {
  244. return sp->role.ad_disabled;
  245. }
  246. static inline bool spte_ad_enabled(u64 spte)
  247. {
  248. MMU_WARN_ON(is_mmio_spte(spte));
  249. return !(spte & shadow_acc_track_value);
  250. }
  251. static bool is_nx_huge_page_enabled(void)
  252. {
  253. return READ_ONCE(nx_huge_pages);
  254. }
  255. static inline u64 spte_shadow_accessed_mask(u64 spte)
  256. {
  257. MMU_WARN_ON(is_mmio_spte(spte));
  258. return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
  259. }
  260. static inline u64 spte_shadow_dirty_mask(u64 spte)
  261. {
  262. MMU_WARN_ON(is_mmio_spte(spte));
  263. return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
  264. }
  265. static inline bool is_access_track_spte(u64 spte)
  266. {
  267. return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
  268. }
  269. /*
  270. * the low bit of the generation number is always presumed to be zero.
  271. * This disables mmio caching during memslot updates. The concept is
  272. * similar to a seqcount but instead of retrying the access we just punt
  273. * and ignore the cache.
  274. *
  275. * spte bits 3-11 are used as bits 1-9 of the generation number,
  276. * the bits 52-61 are used as bits 10-19 of the generation number.
  277. */
  278. #define MMIO_SPTE_GEN_LOW_SHIFT 2
  279. #define MMIO_SPTE_GEN_HIGH_SHIFT 52
  280. #define MMIO_GEN_SHIFT 20
  281. #define MMIO_GEN_LOW_SHIFT 10
  282. #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
  283. #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
  284. static u64 generation_mmio_spte_mask(unsigned int gen)
  285. {
  286. u64 mask;
  287. WARN_ON(gen & ~MMIO_GEN_MASK);
  288. mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
  289. mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
  290. return mask;
  291. }
  292. static unsigned int get_mmio_spte_generation(u64 spte)
  293. {
  294. unsigned int gen;
  295. spte &= ~shadow_mmio_mask;
  296. gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
  297. gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
  298. return gen;
  299. }
  300. static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
  301. {
  302. return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
  303. }
  304. static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
  305. unsigned access)
  306. {
  307. unsigned int gen = kvm_current_mmio_generation(vcpu);
  308. u64 mask = generation_mmio_spte_mask(gen);
  309. u64 gpa = gfn << PAGE_SHIFT;
  310. access &= ACC_WRITE_MASK | ACC_USER_MASK;
  311. mask |= shadow_mmio_value | access;
  312. mask |= gpa | shadow_nonpresent_or_rsvd_mask;
  313. mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
  314. << shadow_nonpresent_or_rsvd_mask_len;
  315. trace_mark_mmio_spte(sptep, gfn, access, gen);
  316. mmu_spte_set(sptep, mask);
  317. }
  318. static gfn_t get_mmio_spte_gfn(u64 spte)
  319. {
  320. u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
  321. gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
  322. & shadow_nonpresent_or_rsvd_mask;
  323. return gpa >> PAGE_SHIFT;
  324. }
  325. static unsigned get_mmio_spte_access(u64 spte)
  326. {
  327. u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
  328. return (spte & ~mask) & ~PAGE_MASK;
  329. }
  330. static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
  331. kvm_pfn_t pfn, unsigned access)
  332. {
  333. if (unlikely(is_noslot_pfn(pfn))) {
  334. mark_mmio_spte(vcpu, sptep, gfn, access);
  335. return true;
  336. }
  337. return false;
  338. }
  339. static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
  340. {
  341. unsigned int kvm_gen, spte_gen;
  342. kvm_gen = kvm_current_mmio_generation(vcpu);
  343. spte_gen = get_mmio_spte_generation(spte);
  344. trace_check_mmio_spte(spte, kvm_gen, spte_gen);
  345. return likely(kvm_gen == spte_gen);
  346. }
  347. /*
  348. * Sets the shadow PTE masks used by the MMU.
  349. *
  350. * Assumptions:
  351. * - Setting either @accessed_mask or @dirty_mask requires setting both
  352. * - At least one of @accessed_mask or @acc_track_mask must be set
  353. */
  354. void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
  355. u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
  356. u64 acc_track_mask, u64 me_mask)
  357. {
  358. BUG_ON(!dirty_mask != !accessed_mask);
  359. BUG_ON(!accessed_mask && !acc_track_mask);
  360. BUG_ON(acc_track_mask & shadow_acc_track_value);
  361. shadow_user_mask = user_mask;
  362. shadow_accessed_mask = accessed_mask;
  363. shadow_dirty_mask = dirty_mask;
  364. shadow_nx_mask = nx_mask;
  365. shadow_x_mask = x_mask;
  366. shadow_present_mask = p_mask;
  367. shadow_acc_track_mask = acc_track_mask;
  368. shadow_me_mask = me_mask;
  369. }
  370. EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
  371. static u8 kvm_get_shadow_phys_bits(void)
  372. {
  373. /*
  374. * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
  375. * in CPU detection code, but MKTME treats those reduced bits as
  376. * 'keyID' thus they are not reserved bits. Therefore for MKTME
  377. * we should still return physical address bits reported by CPUID.
  378. */
  379. if (!boot_cpu_has(X86_FEATURE_TME) ||
  380. WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
  381. return boot_cpu_data.x86_phys_bits;
  382. return cpuid_eax(0x80000008) & 0xff;
  383. }
  384. static void kvm_mmu_reset_all_pte_masks(void)
  385. {
  386. u8 low_phys_bits;
  387. shadow_user_mask = 0;
  388. shadow_accessed_mask = 0;
  389. shadow_dirty_mask = 0;
  390. shadow_nx_mask = 0;
  391. shadow_x_mask = 0;
  392. shadow_mmio_mask = 0;
  393. shadow_present_mask = 0;
  394. shadow_acc_track_mask = 0;
  395. shadow_phys_bits = kvm_get_shadow_phys_bits();
  396. /*
  397. * If the CPU has 46 or less physical address bits, then set an
  398. * appropriate mask to guard against L1TF attacks. Otherwise, it is
  399. * assumed that the CPU is not vulnerable to L1TF.
  400. *
  401. * Some Intel CPUs address the L1 cache using more PA bits than are
  402. * reported by CPUID. Use the PA width of the L1 cache when possible
  403. * to achieve more effective mitigation, e.g. if system RAM overlaps
  404. * the most significant bits of legal physical address space.
  405. */
  406. shadow_nonpresent_or_rsvd_mask = 0;
  407. low_phys_bits = boot_cpu_data.x86_phys_bits;
  408. if (boot_cpu_has_bug(X86_BUG_L1TF) &&
  409. !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
  410. 52 - shadow_nonpresent_or_rsvd_mask_len)) {
  411. low_phys_bits = boot_cpu_data.x86_cache_bits
  412. - shadow_nonpresent_or_rsvd_mask_len;
  413. shadow_nonpresent_or_rsvd_mask =
  414. rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
  415. }
  416. shadow_nonpresent_or_rsvd_lower_gfn_mask =
  417. GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
  418. }
  419. static int is_cpuid_PSE36(void)
  420. {
  421. return 1;
  422. }
  423. static int is_nx(struct kvm_vcpu *vcpu)
  424. {
  425. return vcpu->arch.efer & EFER_NX;
  426. }
  427. static int is_shadow_present_pte(u64 pte)
  428. {
  429. return (pte != 0) && !is_mmio_spte(pte);
  430. }
  431. static int is_large_pte(u64 pte)
  432. {
  433. return pte & PT_PAGE_SIZE_MASK;
  434. }
  435. static int is_last_spte(u64 pte, int level)
  436. {
  437. if (level == PT_PAGE_TABLE_LEVEL)
  438. return 1;
  439. if (is_large_pte(pte))
  440. return 1;
  441. return 0;
  442. }
  443. static bool is_executable_pte(u64 spte)
  444. {
  445. return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
  446. }
  447. static kvm_pfn_t spte_to_pfn(u64 pte)
  448. {
  449. return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
  450. }
  451. static gfn_t pse36_gfn_delta(u32 gpte)
  452. {
  453. int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
  454. return (gpte & PT32_DIR_PSE36_MASK) << shift;
  455. }
  456. #ifdef CONFIG_X86_64
  457. static void __set_spte(u64 *sptep, u64 spte)
  458. {
  459. WRITE_ONCE(*sptep, spte);
  460. }
  461. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  462. {
  463. WRITE_ONCE(*sptep, spte);
  464. }
  465. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  466. {
  467. return xchg(sptep, spte);
  468. }
  469. static u64 __get_spte_lockless(u64 *sptep)
  470. {
  471. return ACCESS_ONCE(*sptep);
  472. }
  473. #else
  474. union split_spte {
  475. struct {
  476. u32 spte_low;
  477. u32 spte_high;
  478. };
  479. u64 spte;
  480. };
  481. static void count_spte_clear(u64 *sptep, u64 spte)
  482. {
  483. struct kvm_mmu_page *sp = page_header(__pa(sptep));
  484. if (is_shadow_present_pte(spte))
  485. return;
  486. /* Ensure the spte is completely set before we increase the count */
  487. smp_wmb();
  488. sp->clear_spte_count++;
  489. }
  490. static void __set_spte(u64 *sptep, u64 spte)
  491. {
  492. union split_spte *ssptep, sspte;
  493. ssptep = (union split_spte *)sptep;
  494. sspte = (union split_spte)spte;
  495. ssptep->spte_high = sspte.spte_high;
  496. /*
  497. * If we map the spte from nonpresent to present, We should store
  498. * the high bits firstly, then set present bit, so cpu can not
  499. * fetch this spte while we are setting the spte.
  500. */
  501. smp_wmb();
  502. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  503. }
  504. static void __update_clear_spte_fast(u64 *sptep, u64 spte)
  505. {
  506. union split_spte *ssptep, sspte;
  507. ssptep = (union split_spte *)sptep;
  508. sspte = (union split_spte)spte;
  509. WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
  510. /*
  511. * If we map the spte from present to nonpresent, we should clear
  512. * present bit firstly to avoid vcpu fetch the old high bits.
  513. */
  514. smp_wmb();
  515. ssptep->spte_high = sspte.spte_high;
  516. count_spte_clear(sptep, spte);
  517. }
  518. static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
  519. {
  520. union split_spte *ssptep, sspte, orig;
  521. ssptep = (union split_spte *)sptep;
  522. sspte = (union split_spte)spte;
  523. /* xchg acts as a barrier before the setting of the high bits */
  524. orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
  525. orig.spte_high = ssptep->spte_high;
  526. ssptep->spte_high = sspte.spte_high;
  527. count_spte_clear(sptep, spte);
  528. return orig.spte;
  529. }
  530. /*
  531. * The idea using the light way get the spte on x86_32 guest is from
  532. * gup_get_pte(arch/x86/mm/gup.c).
  533. *
  534. * An spte tlb flush may be pending, because kvm_set_pte_rmapp
  535. * coalesces them and we are running out of the MMU lock. Therefore
  536. * we need to protect against in-progress updates of the spte.
  537. *
  538. * Reading the spte while an update is in progress may get the old value
  539. * for the high part of the spte. The race is fine for a present->non-present
  540. * change (because the high part of the spte is ignored for non-present spte),
  541. * but for a present->present change we must reread the spte.
  542. *
  543. * All such changes are done in two steps (present->non-present and
  544. * non-present->present), hence it is enough to count the number of
  545. * present->non-present updates: if it changed while reading the spte,
  546. * we might have hit the race. This is done using clear_spte_count.
  547. */
  548. static u64 __get_spte_lockless(u64 *sptep)
  549. {
  550. struct kvm_mmu_page *sp = page_header(__pa(sptep));
  551. union split_spte spte, *orig = (union split_spte *)sptep;
  552. int count;
  553. retry:
  554. count = sp->clear_spte_count;
  555. smp_rmb();
  556. spte.spte_low = orig->spte_low;
  557. smp_rmb();
  558. spte.spte_high = orig->spte_high;
  559. smp_rmb();
  560. if (unlikely(spte.spte_low != orig->spte_low ||
  561. count != sp->clear_spte_count))
  562. goto retry;
  563. return spte.spte;
  564. }
  565. #endif
  566. static bool spte_can_locklessly_be_made_writable(u64 spte)
  567. {
  568. return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
  569. (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
  570. }
  571. static bool spte_has_volatile_bits(u64 spte)
  572. {
  573. if (!is_shadow_present_pte(spte))
  574. return false;
  575. /*
  576. * Always atomically update spte if it can be updated
  577. * out of mmu-lock, it can ensure dirty bit is not lost,
  578. * also, it can help us to get a stable is_writable_pte()
  579. * to ensure tlb flush is not missed.
  580. */
  581. if (spte_can_locklessly_be_made_writable(spte) ||
  582. is_access_track_spte(spte))
  583. return true;
  584. if (spte_ad_enabled(spte)) {
  585. if ((spte & shadow_accessed_mask) == 0 ||
  586. (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
  587. return true;
  588. }
  589. return false;
  590. }
  591. static bool is_accessed_spte(u64 spte)
  592. {
  593. u64 accessed_mask = spte_shadow_accessed_mask(spte);
  594. return accessed_mask ? spte & accessed_mask
  595. : !is_access_track_spte(spte);
  596. }
  597. static bool is_dirty_spte(u64 spte)
  598. {
  599. u64 dirty_mask = spte_shadow_dirty_mask(spte);
  600. return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
  601. }
  602. /* Rules for using mmu_spte_set:
  603. * Set the sptep from nonpresent to present.
  604. * Note: the sptep being assigned *must* be either not present
  605. * or in a state where the hardware will not attempt to update
  606. * the spte.
  607. */
  608. static void mmu_spte_set(u64 *sptep, u64 new_spte)
  609. {
  610. WARN_ON(is_shadow_present_pte(*sptep));
  611. __set_spte(sptep, new_spte);
  612. }
  613. /*
  614. * Update the SPTE (excluding the PFN), but do not track changes in its
  615. * accessed/dirty status.
  616. */
  617. static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
  618. {
  619. u64 old_spte = *sptep;
  620. WARN_ON(!is_shadow_present_pte(new_spte));
  621. if (!is_shadow_present_pte(old_spte)) {
  622. mmu_spte_set(sptep, new_spte);
  623. return old_spte;
  624. }
  625. if (!spte_has_volatile_bits(old_spte))
  626. __update_clear_spte_fast(sptep, new_spte);
  627. else
  628. old_spte = __update_clear_spte_slow(sptep, new_spte);
  629. WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
  630. return old_spte;
  631. }
  632. /* Rules for using mmu_spte_update:
  633. * Update the state bits, it means the mapped pfn is not changed.
  634. *
  635. * Whenever we overwrite a writable spte with a read-only one we
  636. * should flush remote TLBs. Otherwise rmap_write_protect
  637. * will find a read-only spte, even though the writable spte
  638. * might be cached on a CPU's TLB, the return value indicates this
  639. * case.
  640. *
  641. * Returns true if the TLB needs to be flushed
  642. */
  643. static bool mmu_spte_update(u64 *sptep, u64 new_spte)
  644. {
  645. bool flush = false;
  646. u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
  647. if (!is_shadow_present_pte(old_spte))
  648. return false;
  649. /*
  650. * For the spte updated out of mmu-lock is safe, since
  651. * we always atomically update it, see the comments in
  652. * spte_has_volatile_bits().
  653. */
  654. if (spte_can_locklessly_be_made_writable(old_spte) &&
  655. !is_writable_pte(new_spte))
  656. flush = true;
  657. /*
  658. * Flush TLB when accessed/dirty states are changed in the page tables,
  659. * to guarantee consistency between TLB and page tables.
  660. */
  661. if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
  662. flush = true;
  663. kvm_set_pfn_accessed(spte_to_pfn(old_spte));
  664. }
  665. if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
  666. flush = true;
  667. kvm_set_pfn_dirty(spte_to_pfn(old_spte));
  668. }
  669. return flush;
  670. }
  671. /*
  672. * Rules for using mmu_spte_clear_track_bits:
  673. * It sets the sptep from present to nonpresent, and track the
  674. * state bits, it is used to clear the last level sptep.
  675. * Returns non-zero if the PTE was previously valid.
  676. */
  677. static int mmu_spte_clear_track_bits(u64 *sptep)
  678. {
  679. kvm_pfn_t pfn;
  680. u64 old_spte = *sptep;
  681. if (!spte_has_volatile_bits(old_spte))
  682. __update_clear_spte_fast(sptep, 0ull);
  683. else
  684. old_spte = __update_clear_spte_slow(sptep, 0ull);
  685. if (!is_shadow_present_pte(old_spte))
  686. return 0;
  687. pfn = spte_to_pfn(old_spte);
  688. /*
  689. * KVM does not hold the refcount of the page used by
  690. * kvm mmu, before reclaiming the page, we should
  691. * unmap it from mmu first.
  692. */
  693. WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
  694. if (is_accessed_spte(old_spte))
  695. kvm_set_pfn_accessed(pfn);
  696. if (is_dirty_spte(old_spte))
  697. kvm_set_pfn_dirty(pfn);
  698. return 1;
  699. }
  700. /*
  701. * Rules for using mmu_spte_clear_no_track:
  702. * Directly clear spte without caring the state bits of sptep,
  703. * it is used to set the upper level spte.
  704. */
  705. static void mmu_spte_clear_no_track(u64 *sptep)
  706. {
  707. __update_clear_spte_fast(sptep, 0ull);
  708. }
  709. static u64 mmu_spte_get_lockless(u64 *sptep)
  710. {
  711. return __get_spte_lockless(sptep);
  712. }
  713. static u64 mark_spte_for_access_track(u64 spte)
  714. {
  715. if (spte_ad_enabled(spte))
  716. return spte & ~shadow_accessed_mask;
  717. if (is_access_track_spte(spte))
  718. return spte;
  719. /*
  720. * Making an Access Tracking PTE will result in removal of write access
  721. * from the PTE. So, verify that we will be able to restore the write
  722. * access in the fast page fault path later on.
  723. */
  724. WARN_ONCE((spte & PT_WRITABLE_MASK) &&
  725. !spte_can_locklessly_be_made_writable(spte),
  726. "kvm: Writable SPTE is not locklessly dirty-trackable\n");
  727. WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
  728. shadow_acc_track_saved_bits_shift),
  729. "kvm: Access Tracking saved bit locations are not zero\n");
  730. spte |= (spte & shadow_acc_track_saved_bits_mask) <<
  731. shadow_acc_track_saved_bits_shift;
  732. spte &= ~shadow_acc_track_mask;
  733. return spte;
  734. }
  735. /* Restore an acc-track PTE back to a regular PTE */
  736. static u64 restore_acc_track_spte(u64 spte)
  737. {
  738. u64 new_spte = spte;
  739. u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
  740. & shadow_acc_track_saved_bits_mask;
  741. WARN_ON_ONCE(spte_ad_enabled(spte));
  742. WARN_ON_ONCE(!is_access_track_spte(spte));
  743. new_spte &= ~shadow_acc_track_mask;
  744. new_spte &= ~(shadow_acc_track_saved_bits_mask <<
  745. shadow_acc_track_saved_bits_shift);
  746. new_spte |= saved_bits;
  747. return new_spte;
  748. }
  749. /* Returns the Accessed status of the PTE and resets it at the same time. */
  750. static bool mmu_spte_age(u64 *sptep)
  751. {
  752. u64 spte = mmu_spte_get_lockless(sptep);
  753. if (!is_accessed_spte(spte))
  754. return false;
  755. if (spte_ad_enabled(spte)) {
  756. clear_bit((ffs(shadow_accessed_mask) - 1),
  757. (unsigned long *)sptep);
  758. } else {
  759. /*
  760. * Capture the dirty status of the page, so that it doesn't get
  761. * lost when the SPTE is marked for access tracking.
  762. */
  763. if (is_writable_pte(spte))
  764. kvm_set_pfn_dirty(spte_to_pfn(spte));
  765. spte = mark_spte_for_access_track(spte);
  766. mmu_spte_update_no_track(sptep, spte);
  767. }
  768. return true;
  769. }
  770. static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
  771. {
  772. /*
  773. * Prevent page table teardown by making any free-er wait during
  774. * kvm_flush_remote_tlbs() IPI to all active vcpus.
  775. */
  776. local_irq_disable();
  777. /*
  778. * Make sure a following spte read is not reordered ahead of the write
  779. * to vcpu->mode.
  780. */
  781. smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
  782. }
  783. static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
  784. {
  785. /*
  786. * Make sure the write to vcpu->mode is not reordered in front of
  787. * reads to sptes. If it does, kvm_commit_zap_page() can see us
  788. * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
  789. */
  790. smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
  791. local_irq_enable();
  792. }
  793. static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
  794. struct kmem_cache *base_cache, int min)
  795. {
  796. void *obj;
  797. if (cache->nobjs >= min)
  798. return 0;
  799. while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
  800. obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
  801. if (!obj)
  802. return -ENOMEM;
  803. cache->objects[cache->nobjs++] = obj;
  804. }
  805. return 0;
  806. }
  807. static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
  808. {
  809. return cache->nobjs;
  810. }
  811. static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
  812. struct kmem_cache *cache)
  813. {
  814. while (mc->nobjs)
  815. kmem_cache_free(cache, mc->objects[--mc->nobjs]);
  816. }
  817. static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
  818. int min)
  819. {
  820. void *page;
  821. if (cache->nobjs >= min)
  822. return 0;
  823. while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
  824. page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
  825. if (!page)
  826. return -ENOMEM;
  827. cache->objects[cache->nobjs++] = page;
  828. }
  829. return 0;
  830. }
  831. static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
  832. {
  833. while (mc->nobjs)
  834. free_page((unsigned long)mc->objects[--mc->nobjs]);
  835. }
  836. static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
  837. {
  838. int r;
  839. r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
  840. pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
  841. if (r)
  842. goto out;
  843. r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
  844. if (r)
  845. goto out;
  846. r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
  847. mmu_page_header_cache, 4);
  848. out:
  849. return r;
  850. }
  851. static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
  852. {
  853. mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
  854. pte_list_desc_cache);
  855. mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
  856. mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
  857. mmu_page_header_cache);
  858. }
  859. static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
  860. {
  861. void *p;
  862. BUG_ON(!mc->nobjs);
  863. p = mc->objects[--mc->nobjs];
  864. return p;
  865. }
  866. static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
  867. {
  868. return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
  869. }
  870. static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
  871. {
  872. kmem_cache_free(pte_list_desc_cache, pte_list_desc);
  873. }
  874. static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
  875. {
  876. if (!sp->role.direct)
  877. return sp->gfns[index];
  878. return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
  879. }
  880. static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
  881. {
  882. if (!sp->role.direct) {
  883. sp->gfns[index] = gfn;
  884. return;
  885. }
  886. if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
  887. pr_err_ratelimited("gfn mismatch under direct page %llx "
  888. "(expected %llx, got %llx)\n",
  889. sp->gfn,
  890. kvm_mmu_page_get_gfn(sp, index), gfn);
  891. }
  892. /*
  893. * Return the pointer to the large page information for a given gfn,
  894. * handling slots that are not large page aligned.
  895. */
  896. static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
  897. struct kvm_memory_slot *slot,
  898. int level)
  899. {
  900. unsigned long idx;
  901. idx = gfn_to_index(gfn, slot->base_gfn, level);
  902. return &slot->arch.lpage_info[level - 2][idx];
  903. }
  904. static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
  905. gfn_t gfn, int count)
  906. {
  907. struct kvm_lpage_info *linfo;
  908. int i;
  909. for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  910. linfo = lpage_info_slot(gfn, slot, i);
  911. linfo->disallow_lpage += count;
  912. WARN_ON(linfo->disallow_lpage < 0);
  913. }
  914. }
  915. void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
  916. {
  917. update_gfn_disallow_lpage_count(slot, gfn, 1);
  918. }
  919. void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
  920. {
  921. update_gfn_disallow_lpage_count(slot, gfn, -1);
  922. }
  923. static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  924. {
  925. struct kvm_memslots *slots;
  926. struct kvm_memory_slot *slot;
  927. gfn_t gfn;
  928. kvm->arch.indirect_shadow_pages++;
  929. gfn = sp->gfn;
  930. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  931. slot = __gfn_to_memslot(slots, gfn);
  932. /* the non-leaf shadow pages are keeping readonly. */
  933. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  934. return kvm_slot_page_track_add_page(kvm, slot, gfn,
  935. KVM_PAGE_TRACK_WRITE);
  936. kvm_mmu_gfn_disallow_lpage(slot, gfn);
  937. }
  938. static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  939. {
  940. if (sp->lpage_disallowed)
  941. return;
  942. ++kvm->stat.nx_lpage_splits;
  943. list_add_tail(&sp->lpage_disallowed_link,
  944. &kvm->arch.lpage_disallowed_mmu_pages);
  945. sp->lpage_disallowed = true;
  946. }
  947. static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
  948. {
  949. struct kvm_memslots *slots;
  950. struct kvm_memory_slot *slot;
  951. gfn_t gfn;
  952. kvm->arch.indirect_shadow_pages--;
  953. gfn = sp->gfn;
  954. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  955. slot = __gfn_to_memslot(slots, gfn);
  956. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  957. return kvm_slot_page_track_remove_page(kvm, slot, gfn,
  958. KVM_PAGE_TRACK_WRITE);
  959. kvm_mmu_gfn_allow_lpage(slot, gfn);
  960. }
  961. static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  962. {
  963. --kvm->stat.nx_lpage_splits;
  964. sp->lpage_disallowed = false;
  965. list_del(&sp->lpage_disallowed_link);
  966. }
  967. static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
  968. struct kvm_memory_slot *slot)
  969. {
  970. struct kvm_lpage_info *linfo;
  971. if (slot) {
  972. linfo = lpage_info_slot(gfn, slot, level);
  973. return !!linfo->disallow_lpage;
  974. }
  975. return true;
  976. }
  977. static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
  978. int level)
  979. {
  980. struct kvm_memory_slot *slot;
  981. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  982. return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
  983. }
  984. static int host_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn)
  985. {
  986. unsigned long page_size;
  987. int i, ret = 0;
  988. page_size = kvm_host_page_size(vcpu, gfn);
  989. for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  990. if (page_size >= KVM_HPAGE_SIZE(i))
  991. ret = i;
  992. else
  993. break;
  994. }
  995. return ret;
  996. }
  997. static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
  998. bool no_dirty_log)
  999. {
  1000. if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
  1001. return false;
  1002. if (no_dirty_log && slot->dirty_bitmap)
  1003. return false;
  1004. return true;
  1005. }
  1006. static struct kvm_memory_slot *
  1007. gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
  1008. bool no_dirty_log)
  1009. {
  1010. struct kvm_memory_slot *slot;
  1011. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1012. if (!memslot_valid_for_gpte(slot, no_dirty_log))
  1013. slot = NULL;
  1014. return slot;
  1015. }
  1016. static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
  1017. bool *force_pt_level)
  1018. {
  1019. int host_level, level, max_level;
  1020. struct kvm_memory_slot *slot;
  1021. if (unlikely(*force_pt_level))
  1022. return PT_PAGE_TABLE_LEVEL;
  1023. slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
  1024. *force_pt_level = !memslot_valid_for_gpte(slot, true);
  1025. if (unlikely(*force_pt_level))
  1026. return PT_PAGE_TABLE_LEVEL;
  1027. host_level = host_mapping_level(vcpu, large_gfn);
  1028. if (host_level == PT_PAGE_TABLE_LEVEL)
  1029. return host_level;
  1030. max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
  1031. for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
  1032. if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
  1033. break;
  1034. return level - 1;
  1035. }
  1036. /*
  1037. * About rmap_head encoding:
  1038. *
  1039. * If the bit zero of rmap_head->val is clear, then it points to the only spte
  1040. * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
  1041. * pte_list_desc containing more mappings.
  1042. */
  1043. /*
  1044. * Returns the number of pointers in the rmap chain, not counting the new one.
  1045. */
  1046. static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
  1047. struct kvm_rmap_head *rmap_head)
  1048. {
  1049. struct pte_list_desc *desc;
  1050. int i, count = 0;
  1051. if (!rmap_head->val) {
  1052. rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
  1053. rmap_head->val = (unsigned long)spte;
  1054. } else if (!(rmap_head->val & 1)) {
  1055. rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
  1056. desc = mmu_alloc_pte_list_desc(vcpu);
  1057. desc->sptes[0] = (u64 *)rmap_head->val;
  1058. desc->sptes[1] = spte;
  1059. rmap_head->val = (unsigned long)desc | 1;
  1060. ++count;
  1061. } else {
  1062. rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
  1063. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1064. while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
  1065. desc = desc->more;
  1066. count += PTE_LIST_EXT;
  1067. }
  1068. if (desc->sptes[PTE_LIST_EXT-1]) {
  1069. desc->more = mmu_alloc_pte_list_desc(vcpu);
  1070. desc = desc->more;
  1071. }
  1072. for (i = 0; desc->sptes[i]; ++i)
  1073. ++count;
  1074. desc->sptes[i] = spte;
  1075. }
  1076. return count;
  1077. }
  1078. static void
  1079. pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
  1080. struct pte_list_desc *desc, int i,
  1081. struct pte_list_desc *prev_desc)
  1082. {
  1083. int j;
  1084. for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
  1085. ;
  1086. desc->sptes[i] = desc->sptes[j];
  1087. desc->sptes[j] = NULL;
  1088. if (j != 0)
  1089. return;
  1090. if (!prev_desc && !desc->more)
  1091. rmap_head->val = (unsigned long)desc->sptes[0];
  1092. else
  1093. if (prev_desc)
  1094. prev_desc->more = desc->more;
  1095. else
  1096. rmap_head->val = (unsigned long)desc->more | 1;
  1097. mmu_free_pte_list_desc(desc);
  1098. }
  1099. static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
  1100. {
  1101. struct pte_list_desc *desc;
  1102. struct pte_list_desc *prev_desc;
  1103. int i;
  1104. if (!rmap_head->val) {
  1105. printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
  1106. BUG();
  1107. } else if (!(rmap_head->val & 1)) {
  1108. rmap_printk("pte_list_remove: %p 1->0\n", spte);
  1109. if ((u64 *)rmap_head->val != spte) {
  1110. printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
  1111. BUG();
  1112. }
  1113. rmap_head->val = 0;
  1114. } else {
  1115. rmap_printk("pte_list_remove: %p many->many\n", spte);
  1116. desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1117. prev_desc = NULL;
  1118. while (desc) {
  1119. for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
  1120. if (desc->sptes[i] == spte) {
  1121. pte_list_desc_remove_entry(rmap_head,
  1122. desc, i, prev_desc);
  1123. return;
  1124. }
  1125. }
  1126. prev_desc = desc;
  1127. desc = desc->more;
  1128. }
  1129. pr_err("pte_list_remove: %p many->many\n", spte);
  1130. BUG();
  1131. }
  1132. }
  1133. static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
  1134. struct kvm_memory_slot *slot)
  1135. {
  1136. unsigned long idx;
  1137. idx = gfn_to_index(gfn, slot->base_gfn, level);
  1138. return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
  1139. }
  1140. static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
  1141. struct kvm_mmu_page *sp)
  1142. {
  1143. struct kvm_memslots *slots;
  1144. struct kvm_memory_slot *slot;
  1145. slots = kvm_memslots_for_spte_role(kvm, sp->role);
  1146. slot = __gfn_to_memslot(slots, gfn);
  1147. return __gfn_to_rmap(gfn, sp->role.level, slot);
  1148. }
  1149. static bool rmap_can_add(struct kvm_vcpu *vcpu)
  1150. {
  1151. struct kvm_mmu_memory_cache *cache;
  1152. cache = &vcpu->arch.mmu_pte_list_desc_cache;
  1153. return mmu_memory_cache_free_objects(cache);
  1154. }
  1155. static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
  1156. {
  1157. struct kvm_mmu_page *sp;
  1158. struct kvm_rmap_head *rmap_head;
  1159. sp = page_header(__pa(spte));
  1160. kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
  1161. rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
  1162. return pte_list_add(vcpu, spte, rmap_head);
  1163. }
  1164. static void rmap_remove(struct kvm *kvm, u64 *spte)
  1165. {
  1166. struct kvm_mmu_page *sp;
  1167. gfn_t gfn;
  1168. struct kvm_rmap_head *rmap_head;
  1169. sp = page_header(__pa(spte));
  1170. gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
  1171. rmap_head = gfn_to_rmap(kvm, gfn, sp);
  1172. pte_list_remove(spte, rmap_head);
  1173. }
  1174. /*
  1175. * Used by the following functions to iterate through the sptes linked by a
  1176. * rmap. All fields are private and not assumed to be used outside.
  1177. */
  1178. struct rmap_iterator {
  1179. /* private fields */
  1180. struct pte_list_desc *desc; /* holds the sptep if not NULL */
  1181. int pos; /* index of the sptep */
  1182. };
  1183. /*
  1184. * Iteration must be started by this function. This should also be used after
  1185. * removing/dropping sptes from the rmap link because in such cases the
  1186. * information in the itererator may not be valid.
  1187. *
  1188. * Returns sptep if found, NULL otherwise.
  1189. */
  1190. static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
  1191. struct rmap_iterator *iter)
  1192. {
  1193. u64 *sptep;
  1194. if (!rmap_head->val)
  1195. return NULL;
  1196. if (!(rmap_head->val & 1)) {
  1197. iter->desc = NULL;
  1198. sptep = (u64 *)rmap_head->val;
  1199. goto out;
  1200. }
  1201. iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
  1202. iter->pos = 0;
  1203. sptep = iter->desc->sptes[iter->pos];
  1204. out:
  1205. BUG_ON(!is_shadow_present_pte(*sptep));
  1206. return sptep;
  1207. }
  1208. /*
  1209. * Must be used with a valid iterator: e.g. after rmap_get_first().
  1210. *
  1211. * Returns sptep if found, NULL otherwise.
  1212. */
  1213. static u64 *rmap_get_next(struct rmap_iterator *iter)
  1214. {
  1215. u64 *sptep;
  1216. if (iter->desc) {
  1217. if (iter->pos < PTE_LIST_EXT - 1) {
  1218. ++iter->pos;
  1219. sptep = iter->desc->sptes[iter->pos];
  1220. if (sptep)
  1221. goto out;
  1222. }
  1223. iter->desc = iter->desc->more;
  1224. if (iter->desc) {
  1225. iter->pos = 0;
  1226. /* desc->sptes[0] cannot be NULL */
  1227. sptep = iter->desc->sptes[iter->pos];
  1228. goto out;
  1229. }
  1230. }
  1231. return NULL;
  1232. out:
  1233. BUG_ON(!is_shadow_present_pte(*sptep));
  1234. return sptep;
  1235. }
  1236. #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
  1237. for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
  1238. _spte_; _spte_ = rmap_get_next(_iter_))
  1239. static void drop_spte(struct kvm *kvm, u64 *sptep)
  1240. {
  1241. if (mmu_spte_clear_track_bits(sptep))
  1242. rmap_remove(kvm, sptep);
  1243. }
  1244. static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
  1245. {
  1246. if (is_large_pte(*sptep)) {
  1247. WARN_ON(page_header(__pa(sptep))->role.level ==
  1248. PT_PAGE_TABLE_LEVEL);
  1249. drop_spte(kvm, sptep);
  1250. --kvm->stat.lpages;
  1251. return true;
  1252. }
  1253. return false;
  1254. }
  1255. static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
  1256. {
  1257. if (__drop_large_spte(vcpu->kvm, sptep))
  1258. kvm_flush_remote_tlbs(vcpu->kvm);
  1259. }
  1260. /*
  1261. * Write-protect on the specified @sptep, @pt_protect indicates whether
  1262. * spte write-protection is caused by protecting shadow page table.
  1263. *
  1264. * Note: write protection is difference between dirty logging and spte
  1265. * protection:
  1266. * - for dirty logging, the spte can be set to writable at anytime if
  1267. * its dirty bitmap is properly set.
  1268. * - for spte protection, the spte can be writable only after unsync-ing
  1269. * shadow page.
  1270. *
  1271. * Return true if tlb need be flushed.
  1272. */
  1273. static bool spte_write_protect(u64 *sptep, bool pt_protect)
  1274. {
  1275. u64 spte = *sptep;
  1276. if (!is_writable_pte(spte) &&
  1277. !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
  1278. return false;
  1279. rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
  1280. if (pt_protect)
  1281. spte &= ~SPTE_MMU_WRITEABLE;
  1282. spte = spte & ~PT_WRITABLE_MASK;
  1283. return mmu_spte_update(sptep, spte);
  1284. }
  1285. static bool __rmap_write_protect(struct kvm *kvm,
  1286. struct kvm_rmap_head *rmap_head,
  1287. bool pt_protect)
  1288. {
  1289. u64 *sptep;
  1290. struct rmap_iterator iter;
  1291. bool flush = false;
  1292. for_each_rmap_spte(rmap_head, &iter, sptep)
  1293. flush |= spte_write_protect(sptep, pt_protect);
  1294. return flush;
  1295. }
  1296. static bool spte_clear_dirty(u64 *sptep)
  1297. {
  1298. u64 spte = *sptep;
  1299. rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
  1300. spte &= ~shadow_dirty_mask;
  1301. return mmu_spte_update(sptep, spte);
  1302. }
  1303. static bool wrprot_ad_disabled_spte(u64 *sptep)
  1304. {
  1305. bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
  1306. (unsigned long *)sptep);
  1307. if (was_writable)
  1308. kvm_set_pfn_dirty(spte_to_pfn(*sptep));
  1309. return was_writable;
  1310. }
  1311. /*
  1312. * Gets the GFN ready for another round of dirty logging by clearing the
  1313. * - D bit on ad-enabled SPTEs, and
  1314. * - W bit on ad-disabled SPTEs.
  1315. * Returns true iff any D or W bits were cleared.
  1316. */
  1317. static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1318. {
  1319. u64 *sptep;
  1320. struct rmap_iterator iter;
  1321. bool flush = false;
  1322. for_each_rmap_spte(rmap_head, &iter, sptep)
  1323. if (spte_ad_enabled(*sptep))
  1324. flush |= spte_clear_dirty(sptep);
  1325. else
  1326. flush |= wrprot_ad_disabled_spte(sptep);
  1327. return flush;
  1328. }
  1329. static bool spte_set_dirty(u64 *sptep)
  1330. {
  1331. u64 spte = *sptep;
  1332. rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
  1333. spte |= shadow_dirty_mask;
  1334. return mmu_spte_update(sptep, spte);
  1335. }
  1336. static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1337. {
  1338. u64 *sptep;
  1339. struct rmap_iterator iter;
  1340. bool flush = false;
  1341. for_each_rmap_spte(rmap_head, &iter, sptep)
  1342. if (spte_ad_enabled(*sptep))
  1343. flush |= spte_set_dirty(sptep);
  1344. return flush;
  1345. }
  1346. /**
  1347. * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
  1348. * @kvm: kvm instance
  1349. * @slot: slot to protect
  1350. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1351. * @mask: indicates which pages we should protect
  1352. *
  1353. * Used when we do not need to care about huge page mappings: e.g. during dirty
  1354. * logging we do not have any such mappings.
  1355. */
  1356. static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
  1357. struct kvm_memory_slot *slot,
  1358. gfn_t gfn_offset, unsigned long mask)
  1359. {
  1360. struct kvm_rmap_head *rmap_head;
  1361. while (mask) {
  1362. rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1363. PT_PAGE_TABLE_LEVEL, slot);
  1364. __rmap_write_protect(kvm, rmap_head, false);
  1365. /* clear the first set bit */
  1366. mask &= mask - 1;
  1367. }
  1368. }
  1369. /**
  1370. * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
  1371. * protect the page if the D-bit isn't supported.
  1372. * @kvm: kvm instance
  1373. * @slot: slot to clear D-bit
  1374. * @gfn_offset: start of the BITS_PER_LONG pages we care about
  1375. * @mask: indicates which pages we should clear D-bit
  1376. *
  1377. * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
  1378. */
  1379. void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
  1380. struct kvm_memory_slot *slot,
  1381. gfn_t gfn_offset, unsigned long mask)
  1382. {
  1383. struct kvm_rmap_head *rmap_head;
  1384. while (mask) {
  1385. rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
  1386. PT_PAGE_TABLE_LEVEL, slot);
  1387. __rmap_clear_dirty(kvm, rmap_head);
  1388. /* clear the first set bit */
  1389. mask &= mask - 1;
  1390. }
  1391. }
  1392. EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
  1393. /**
  1394. * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
  1395. * PT level pages.
  1396. *
  1397. * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
  1398. * enable dirty logging for them.
  1399. *
  1400. * Used when we do not need to care about huge page mappings: e.g. during dirty
  1401. * logging we do not have any such mappings.
  1402. */
  1403. void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
  1404. struct kvm_memory_slot *slot,
  1405. gfn_t gfn_offset, unsigned long mask)
  1406. {
  1407. if (kvm_x86_ops->enable_log_dirty_pt_masked)
  1408. kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
  1409. mask);
  1410. else
  1411. kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
  1412. }
  1413. /**
  1414. * kvm_arch_write_log_dirty - emulate dirty page logging
  1415. * @vcpu: Guest mode vcpu
  1416. *
  1417. * Emulate arch specific page modification logging for the
  1418. * nested hypervisor
  1419. */
  1420. int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu, gpa_t l2_gpa)
  1421. {
  1422. if (kvm_x86_ops->write_log_dirty)
  1423. return kvm_x86_ops->write_log_dirty(vcpu, l2_gpa);
  1424. return 0;
  1425. }
  1426. bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
  1427. struct kvm_memory_slot *slot, u64 gfn)
  1428. {
  1429. struct kvm_rmap_head *rmap_head;
  1430. int i;
  1431. bool write_protected = false;
  1432. for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
  1433. rmap_head = __gfn_to_rmap(gfn, i, slot);
  1434. write_protected |= __rmap_write_protect(kvm, rmap_head, true);
  1435. }
  1436. return write_protected;
  1437. }
  1438. static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
  1439. {
  1440. struct kvm_memory_slot *slot;
  1441. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1442. return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
  1443. }
  1444. static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
  1445. {
  1446. u64 *sptep;
  1447. struct rmap_iterator iter;
  1448. bool flush = false;
  1449. while ((sptep = rmap_get_first(rmap_head, &iter))) {
  1450. rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
  1451. drop_spte(kvm, sptep);
  1452. flush = true;
  1453. }
  1454. return flush;
  1455. }
  1456. static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1457. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1458. unsigned long data)
  1459. {
  1460. return kvm_zap_rmapp(kvm, rmap_head);
  1461. }
  1462. static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1463. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1464. unsigned long data)
  1465. {
  1466. u64 *sptep;
  1467. struct rmap_iterator iter;
  1468. int need_flush = 0;
  1469. u64 new_spte;
  1470. pte_t *ptep = (pte_t *)data;
  1471. kvm_pfn_t new_pfn;
  1472. WARN_ON(pte_huge(*ptep));
  1473. new_pfn = pte_pfn(*ptep);
  1474. restart:
  1475. for_each_rmap_spte(rmap_head, &iter, sptep) {
  1476. rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
  1477. sptep, *sptep, gfn, level);
  1478. need_flush = 1;
  1479. if (pte_write(*ptep)) {
  1480. drop_spte(kvm, sptep);
  1481. goto restart;
  1482. } else {
  1483. new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
  1484. new_spte |= (u64)new_pfn << PAGE_SHIFT;
  1485. new_spte &= ~PT_WRITABLE_MASK;
  1486. new_spte &= ~SPTE_HOST_WRITEABLE;
  1487. new_spte = mark_spte_for_access_track(new_spte);
  1488. mmu_spte_clear_track_bits(sptep);
  1489. mmu_spte_set(sptep, new_spte);
  1490. }
  1491. }
  1492. if (need_flush)
  1493. kvm_flush_remote_tlbs(kvm);
  1494. return 0;
  1495. }
  1496. struct slot_rmap_walk_iterator {
  1497. /* input fields. */
  1498. struct kvm_memory_slot *slot;
  1499. gfn_t start_gfn;
  1500. gfn_t end_gfn;
  1501. int start_level;
  1502. int end_level;
  1503. /* output fields. */
  1504. gfn_t gfn;
  1505. struct kvm_rmap_head *rmap;
  1506. int level;
  1507. /* private field. */
  1508. struct kvm_rmap_head *end_rmap;
  1509. };
  1510. static void
  1511. rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
  1512. {
  1513. iterator->level = level;
  1514. iterator->gfn = iterator->start_gfn;
  1515. iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
  1516. iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
  1517. iterator->slot);
  1518. }
  1519. static void
  1520. slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
  1521. struct kvm_memory_slot *slot, int start_level,
  1522. int end_level, gfn_t start_gfn, gfn_t end_gfn)
  1523. {
  1524. iterator->slot = slot;
  1525. iterator->start_level = start_level;
  1526. iterator->end_level = end_level;
  1527. iterator->start_gfn = start_gfn;
  1528. iterator->end_gfn = end_gfn;
  1529. rmap_walk_init_level(iterator, iterator->start_level);
  1530. }
  1531. static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
  1532. {
  1533. return !!iterator->rmap;
  1534. }
  1535. static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
  1536. {
  1537. if (++iterator->rmap <= iterator->end_rmap) {
  1538. iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
  1539. return;
  1540. }
  1541. if (++iterator->level > iterator->end_level) {
  1542. iterator->rmap = NULL;
  1543. return;
  1544. }
  1545. rmap_walk_init_level(iterator, iterator->level);
  1546. }
  1547. #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
  1548. _start_gfn, _end_gfn, _iter_) \
  1549. for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
  1550. _end_level_, _start_gfn, _end_gfn); \
  1551. slot_rmap_walk_okay(_iter_); \
  1552. slot_rmap_walk_next(_iter_))
  1553. static int kvm_handle_hva_range(struct kvm *kvm,
  1554. unsigned long start,
  1555. unsigned long end,
  1556. unsigned long data,
  1557. int (*handler)(struct kvm *kvm,
  1558. struct kvm_rmap_head *rmap_head,
  1559. struct kvm_memory_slot *slot,
  1560. gfn_t gfn,
  1561. int level,
  1562. unsigned long data))
  1563. {
  1564. struct kvm_memslots *slots;
  1565. struct kvm_memory_slot *memslot;
  1566. struct slot_rmap_walk_iterator iterator;
  1567. int ret = 0;
  1568. int i;
  1569. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  1570. slots = __kvm_memslots(kvm, i);
  1571. kvm_for_each_memslot(memslot, slots) {
  1572. unsigned long hva_start, hva_end;
  1573. gfn_t gfn_start, gfn_end;
  1574. hva_start = max(start, memslot->userspace_addr);
  1575. hva_end = min(end, memslot->userspace_addr +
  1576. (memslot->npages << PAGE_SHIFT));
  1577. if (hva_start >= hva_end)
  1578. continue;
  1579. /*
  1580. * {gfn(page) | page intersects with [hva_start, hva_end)} =
  1581. * {gfn_start, gfn_start+1, ..., gfn_end-1}.
  1582. */
  1583. gfn_start = hva_to_gfn_memslot(hva_start, memslot);
  1584. gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
  1585. for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
  1586. PT_MAX_HUGEPAGE_LEVEL,
  1587. gfn_start, gfn_end - 1,
  1588. &iterator)
  1589. ret |= handler(kvm, iterator.rmap, memslot,
  1590. iterator.gfn, iterator.level, data);
  1591. }
  1592. }
  1593. return ret;
  1594. }
  1595. static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
  1596. unsigned long data,
  1597. int (*handler)(struct kvm *kvm,
  1598. struct kvm_rmap_head *rmap_head,
  1599. struct kvm_memory_slot *slot,
  1600. gfn_t gfn, int level,
  1601. unsigned long data))
  1602. {
  1603. return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
  1604. }
  1605. int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
  1606. {
  1607. return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
  1608. }
  1609. int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
  1610. {
  1611. return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
  1612. }
  1613. void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
  1614. {
  1615. kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
  1616. }
  1617. static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1618. struct kvm_memory_slot *slot, gfn_t gfn, int level,
  1619. unsigned long data)
  1620. {
  1621. u64 *sptep;
  1622. struct rmap_iterator uninitialized_var(iter);
  1623. int young = 0;
  1624. for_each_rmap_spte(rmap_head, &iter, sptep)
  1625. young |= mmu_spte_age(sptep);
  1626. trace_kvm_age_page(gfn, level, slot, young);
  1627. return young;
  1628. }
  1629. static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
  1630. struct kvm_memory_slot *slot, gfn_t gfn,
  1631. int level, unsigned long data)
  1632. {
  1633. u64 *sptep;
  1634. struct rmap_iterator iter;
  1635. for_each_rmap_spte(rmap_head, &iter, sptep)
  1636. if (is_accessed_spte(*sptep))
  1637. return 1;
  1638. return 0;
  1639. }
  1640. #define RMAP_RECYCLE_THRESHOLD 1000
  1641. static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
  1642. {
  1643. struct kvm_rmap_head *rmap_head;
  1644. struct kvm_mmu_page *sp;
  1645. sp = page_header(__pa(spte));
  1646. rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
  1647. kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
  1648. kvm_flush_remote_tlbs(vcpu->kvm);
  1649. }
  1650. int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
  1651. {
  1652. return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
  1653. }
  1654. int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
  1655. {
  1656. return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
  1657. }
  1658. #ifdef MMU_DEBUG
  1659. static int is_empty_shadow_page(u64 *spt)
  1660. {
  1661. u64 *pos;
  1662. u64 *end;
  1663. for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
  1664. if (is_shadow_present_pte(*pos)) {
  1665. printk(KERN_ERR "%s: %p %llx\n", __func__,
  1666. pos, *pos);
  1667. return 0;
  1668. }
  1669. return 1;
  1670. }
  1671. #endif
  1672. /*
  1673. * This value is the sum of all of the kvm instances's
  1674. * kvm->arch.n_used_mmu_pages values. We need a global,
  1675. * aggregate version in order to make the slab shrinker
  1676. * faster
  1677. */
  1678. static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
  1679. {
  1680. kvm->arch.n_used_mmu_pages += nr;
  1681. percpu_counter_add(&kvm_total_used_mmu_pages, nr);
  1682. }
  1683. static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
  1684. {
  1685. MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
  1686. hlist_del(&sp->hash_link);
  1687. list_del(&sp->link);
  1688. free_page((unsigned long)sp->spt);
  1689. if (!sp->role.direct)
  1690. free_page((unsigned long)sp->gfns);
  1691. kmem_cache_free(mmu_page_header_cache, sp);
  1692. }
  1693. static unsigned kvm_page_table_hashfn(gfn_t gfn)
  1694. {
  1695. return hash_64(gfn, KVM_MMU_HASH_SHIFT);
  1696. }
  1697. static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
  1698. struct kvm_mmu_page *sp, u64 *parent_pte)
  1699. {
  1700. if (!parent_pte)
  1701. return;
  1702. pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
  1703. }
  1704. static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
  1705. u64 *parent_pte)
  1706. {
  1707. pte_list_remove(parent_pte, &sp->parent_ptes);
  1708. }
  1709. static void drop_parent_pte(struct kvm_mmu_page *sp,
  1710. u64 *parent_pte)
  1711. {
  1712. mmu_page_remove_parent_pte(sp, parent_pte);
  1713. mmu_spte_clear_no_track(parent_pte);
  1714. }
  1715. static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
  1716. {
  1717. struct kvm_mmu_page *sp;
  1718. sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
  1719. sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
  1720. if (!direct)
  1721. sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
  1722. set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
  1723. /*
  1724. * The active_mmu_pages list is the FIFO list, do not move the
  1725. * page until it is zapped. kvm_zap_obsolete_pages depends on
  1726. * this feature. See the comments in kvm_zap_obsolete_pages().
  1727. */
  1728. list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
  1729. kvm_mod_used_mmu_pages(vcpu->kvm, +1);
  1730. return sp;
  1731. }
  1732. static void mark_unsync(u64 *spte);
  1733. static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
  1734. {
  1735. u64 *sptep;
  1736. struct rmap_iterator iter;
  1737. for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
  1738. mark_unsync(sptep);
  1739. }
  1740. }
  1741. static void mark_unsync(u64 *spte)
  1742. {
  1743. struct kvm_mmu_page *sp;
  1744. unsigned int index;
  1745. sp = page_header(__pa(spte));
  1746. index = spte - sp->spt;
  1747. if (__test_and_set_bit(index, sp->unsync_child_bitmap))
  1748. return;
  1749. if (sp->unsync_children++)
  1750. return;
  1751. kvm_mmu_mark_parents_unsync(sp);
  1752. }
  1753. static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
  1754. struct kvm_mmu_page *sp)
  1755. {
  1756. return 0;
  1757. }
  1758. static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
  1759. {
  1760. }
  1761. static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
  1762. struct kvm_mmu_page *sp, u64 *spte,
  1763. const void *pte)
  1764. {
  1765. WARN_ON(1);
  1766. }
  1767. #define KVM_PAGE_ARRAY_NR 16
  1768. struct kvm_mmu_pages {
  1769. struct mmu_page_and_offset {
  1770. struct kvm_mmu_page *sp;
  1771. unsigned int idx;
  1772. } page[KVM_PAGE_ARRAY_NR];
  1773. unsigned int nr;
  1774. };
  1775. static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
  1776. int idx)
  1777. {
  1778. int i;
  1779. if (sp->unsync)
  1780. for (i=0; i < pvec->nr; i++)
  1781. if (pvec->page[i].sp == sp)
  1782. return 0;
  1783. pvec->page[pvec->nr].sp = sp;
  1784. pvec->page[pvec->nr].idx = idx;
  1785. pvec->nr++;
  1786. return (pvec->nr == KVM_PAGE_ARRAY_NR);
  1787. }
  1788. static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
  1789. {
  1790. --sp->unsync_children;
  1791. WARN_ON((int)sp->unsync_children < 0);
  1792. __clear_bit(idx, sp->unsync_child_bitmap);
  1793. }
  1794. static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
  1795. struct kvm_mmu_pages *pvec)
  1796. {
  1797. int i, ret, nr_unsync_leaf = 0;
  1798. for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
  1799. struct kvm_mmu_page *child;
  1800. u64 ent = sp->spt[i];
  1801. if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
  1802. clear_unsync_child_bit(sp, i);
  1803. continue;
  1804. }
  1805. child = page_header(ent & PT64_BASE_ADDR_MASK);
  1806. if (child->unsync_children) {
  1807. if (mmu_pages_add(pvec, child, i))
  1808. return -ENOSPC;
  1809. ret = __mmu_unsync_walk(child, pvec);
  1810. if (!ret) {
  1811. clear_unsync_child_bit(sp, i);
  1812. continue;
  1813. } else if (ret > 0) {
  1814. nr_unsync_leaf += ret;
  1815. } else
  1816. return ret;
  1817. } else if (child->unsync) {
  1818. nr_unsync_leaf++;
  1819. if (mmu_pages_add(pvec, child, i))
  1820. return -ENOSPC;
  1821. } else
  1822. clear_unsync_child_bit(sp, i);
  1823. }
  1824. return nr_unsync_leaf;
  1825. }
  1826. #define INVALID_INDEX (-1)
  1827. static int mmu_unsync_walk(struct kvm_mmu_page *sp,
  1828. struct kvm_mmu_pages *pvec)
  1829. {
  1830. pvec->nr = 0;
  1831. if (!sp->unsync_children)
  1832. return 0;
  1833. mmu_pages_add(pvec, sp, INVALID_INDEX);
  1834. return __mmu_unsync_walk(sp, pvec);
  1835. }
  1836. static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
  1837. {
  1838. WARN_ON(!sp->unsync);
  1839. trace_kvm_mmu_sync_page(sp);
  1840. sp->unsync = 0;
  1841. --kvm->stat.mmu_unsync;
  1842. }
  1843. static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  1844. struct list_head *invalid_list);
  1845. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  1846. struct list_head *invalid_list);
  1847. /*
  1848. * NOTE: we should pay more attention on the zapped-obsolete page
  1849. * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
  1850. * since it has been deleted from active_mmu_pages but still can be found
  1851. * at hast list.
  1852. *
  1853. * for_each_valid_sp() has skipped that kind of pages.
  1854. */
  1855. #define for_each_valid_sp(_kvm, _sp, _gfn) \
  1856. hlist_for_each_entry(_sp, \
  1857. &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
  1858. if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) { \
  1859. } else
  1860. #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
  1861. for_each_valid_sp(_kvm, _sp, _gfn) \
  1862. if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
  1863. /* @sp->gfn should be write-protected at the call site */
  1864. static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  1865. struct list_head *invalid_list)
  1866. {
  1867. if (sp->role.cr4_pae != !!is_pae(vcpu)) {
  1868. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
  1869. return false;
  1870. }
  1871. if (vcpu->arch.mmu.sync_page(vcpu, sp) == 0) {
  1872. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
  1873. return false;
  1874. }
  1875. return true;
  1876. }
  1877. static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
  1878. struct list_head *invalid_list,
  1879. bool remote_flush, bool local_flush)
  1880. {
  1881. if (!list_empty(invalid_list)) {
  1882. kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
  1883. return;
  1884. }
  1885. if (remote_flush)
  1886. kvm_flush_remote_tlbs(vcpu->kvm);
  1887. else if (local_flush)
  1888. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  1889. }
  1890. #ifdef CONFIG_KVM_MMU_AUDIT
  1891. #include "mmu_audit.c"
  1892. #else
  1893. static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
  1894. static void mmu_audit_disable(void) { }
  1895. #endif
  1896. static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  1897. {
  1898. return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
  1899. }
  1900. static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  1901. struct list_head *invalid_list)
  1902. {
  1903. kvm_unlink_unsync_page(vcpu->kvm, sp);
  1904. return __kvm_sync_page(vcpu, sp, invalid_list);
  1905. }
  1906. /* @gfn should be write-protected at the call site */
  1907. static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
  1908. struct list_head *invalid_list)
  1909. {
  1910. struct kvm_mmu_page *s;
  1911. bool ret = false;
  1912. for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
  1913. if (!s->unsync)
  1914. continue;
  1915. WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
  1916. ret |= kvm_sync_page(vcpu, s, invalid_list);
  1917. }
  1918. return ret;
  1919. }
  1920. struct mmu_page_path {
  1921. struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
  1922. unsigned int idx[PT64_ROOT_MAX_LEVEL];
  1923. };
  1924. #define for_each_sp(pvec, sp, parents, i) \
  1925. for (i = mmu_pages_first(&pvec, &parents); \
  1926. i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
  1927. i = mmu_pages_next(&pvec, &parents, i))
  1928. static int mmu_pages_next(struct kvm_mmu_pages *pvec,
  1929. struct mmu_page_path *parents,
  1930. int i)
  1931. {
  1932. int n;
  1933. for (n = i+1; n < pvec->nr; n++) {
  1934. struct kvm_mmu_page *sp = pvec->page[n].sp;
  1935. unsigned idx = pvec->page[n].idx;
  1936. int level = sp->role.level;
  1937. parents->idx[level-1] = idx;
  1938. if (level == PT_PAGE_TABLE_LEVEL)
  1939. break;
  1940. parents->parent[level-2] = sp;
  1941. }
  1942. return n;
  1943. }
  1944. static int mmu_pages_first(struct kvm_mmu_pages *pvec,
  1945. struct mmu_page_path *parents)
  1946. {
  1947. struct kvm_mmu_page *sp;
  1948. int level;
  1949. if (pvec->nr == 0)
  1950. return 0;
  1951. WARN_ON(pvec->page[0].idx != INVALID_INDEX);
  1952. sp = pvec->page[0].sp;
  1953. level = sp->role.level;
  1954. WARN_ON(level == PT_PAGE_TABLE_LEVEL);
  1955. parents->parent[level-2] = sp;
  1956. /* Also set up a sentinel. Further entries in pvec are all
  1957. * children of sp, so this element is never overwritten.
  1958. */
  1959. parents->parent[level-1] = NULL;
  1960. return mmu_pages_next(pvec, parents, 0);
  1961. }
  1962. static void mmu_pages_clear_parents(struct mmu_page_path *parents)
  1963. {
  1964. struct kvm_mmu_page *sp;
  1965. unsigned int level = 0;
  1966. do {
  1967. unsigned int idx = parents->idx[level];
  1968. sp = parents->parent[level];
  1969. if (!sp)
  1970. return;
  1971. WARN_ON(idx == INVALID_INDEX);
  1972. clear_unsync_child_bit(sp, idx);
  1973. level++;
  1974. } while (!sp->unsync_children);
  1975. }
  1976. static void mmu_sync_children(struct kvm_vcpu *vcpu,
  1977. struct kvm_mmu_page *parent)
  1978. {
  1979. int i;
  1980. struct kvm_mmu_page *sp;
  1981. struct mmu_page_path parents;
  1982. struct kvm_mmu_pages pages;
  1983. LIST_HEAD(invalid_list);
  1984. bool flush = false;
  1985. while (mmu_unsync_walk(parent, &pages)) {
  1986. bool protected = false;
  1987. for_each_sp(pages, sp, parents, i)
  1988. protected |= rmap_write_protect(vcpu, sp->gfn);
  1989. if (protected) {
  1990. kvm_flush_remote_tlbs(vcpu->kvm);
  1991. flush = false;
  1992. }
  1993. for_each_sp(pages, sp, parents, i) {
  1994. flush |= kvm_sync_page(vcpu, sp, &invalid_list);
  1995. mmu_pages_clear_parents(&parents);
  1996. }
  1997. if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
  1998. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  1999. cond_resched_lock(&vcpu->kvm->mmu_lock);
  2000. flush = false;
  2001. }
  2002. }
  2003. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  2004. }
  2005. static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
  2006. {
  2007. atomic_set(&sp->write_flooding_count, 0);
  2008. }
  2009. static void clear_sp_write_flooding_count(u64 *spte)
  2010. {
  2011. struct kvm_mmu_page *sp = page_header(__pa(spte));
  2012. __clear_sp_write_flooding_count(sp);
  2013. }
  2014. static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
  2015. gfn_t gfn,
  2016. gva_t gaddr,
  2017. unsigned level,
  2018. int direct,
  2019. unsigned access)
  2020. {
  2021. union kvm_mmu_page_role role;
  2022. unsigned quadrant;
  2023. struct kvm_mmu_page *sp;
  2024. bool need_sync = false;
  2025. bool flush = false;
  2026. int collisions = 0;
  2027. LIST_HEAD(invalid_list);
  2028. role = vcpu->arch.mmu.base_role;
  2029. role.level = level;
  2030. role.direct = direct;
  2031. if (role.direct)
  2032. role.cr4_pae = 0;
  2033. role.access = access;
  2034. if (!vcpu->arch.mmu.direct_map
  2035. && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
  2036. quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
  2037. quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
  2038. role.quadrant = quadrant;
  2039. }
  2040. for_each_valid_sp(vcpu->kvm, sp, gfn) {
  2041. if (sp->gfn != gfn) {
  2042. collisions++;
  2043. continue;
  2044. }
  2045. if (!need_sync && sp->unsync)
  2046. need_sync = true;
  2047. if (sp->role.word != role.word)
  2048. continue;
  2049. if (sp->unsync) {
  2050. /* The page is good, but __kvm_sync_page might still end
  2051. * up zapping it. If so, break in order to rebuild it.
  2052. */
  2053. if (!__kvm_sync_page(vcpu, sp, &invalid_list))
  2054. break;
  2055. WARN_ON(!list_empty(&invalid_list));
  2056. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  2057. }
  2058. if (sp->unsync_children)
  2059. kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
  2060. __clear_sp_write_flooding_count(sp);
  2061. trace_kvm_mmu_get_page(sp, false);
  2062. goto out;
  2063. }
  2064. ++vcpu->kvm->stat.mmu_cache_miss;
  2065. sp = kvm_mmu_alloc_page(vcpu, direct);
  2066. sp->gfn = gfn;
  2067. sp->role = role;
  2068. hlist_add_head(&sp->hash_link,
  2069. &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
  2070. if (!direct) {
  2071. /*
  2072. * we should do write protection before syncing pages
  2073. * otherwise the content of the synced shadow page may
  2074. * be inconsistent with guest page table.
  2075. */
  2076. account_shadowed(vcpu->kvm, sp);
  2077. if (level == PT_PAGE_TABLE_LEVEL &&
  2078. rmap_write_protect(vcpu, gfn))
  2079. kvm_flush_remote_tlbs(vcpu->kvm);
  2080. if (level > PT_PAGE_TABLE_LEVEL && need_sync)
  2081. flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
  2082. }
  2083. sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
  2084. clear_page(sp->spt);
  2085. trace_kvm_mmu_get_page(sp, true);
  2086. kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
  2087. out:
  2088. if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
  2089. vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
  2090. return sp;
  2091. }
  2092. static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
  2093. struct kvm_vcpu *vcpu, u64 addr)
  2094. {
  2095. iterator->addr = addr;
  2096. iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
  2097. iterator->level = vcpu->arch.mmu.shadow_root_level;
  2098. if (iterator->level == PT64_ROOT_4LEVEL &&
  2099. vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL &&
  2100. !vcpu->arch.mmu.direct_map)
  2101. --iterator->level;
  2102. if (iterator->level == PT32E_ROOT_LEVEL) {
  2103. iterator->shadow_addr
  2104. = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
  2105. iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
  2106. --iterator->level;
  2107. if (!iterator->shadow_addr)
  2108. iterator->level = 0;
  2109. }
  2110. }
  2111. static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
  2112. {
  2113. if (iterator->level < PT_PAGE_TABLE_LEVEL)
  2114. return false;
  2115. iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
  2116. iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
  2117. return true;
  2118. }
  2119. static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
  2120. u64 spte)
  2121. {
  2122. if (is_last_spte(spte, iterator->level)) {
  2123. iterator->level = 0;
  2124. return;
  2125. }
  2126. iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
  2127. --iterator->level;
  2128. }
  2129. static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
  2130. {
  2131. return __shadow_walk_next(iterator, *iterator->sptep);
  2132. }
  2133. static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
  2134. struct kvm_mmu_page *sp)
  2135. {
  2136. u64 spte;
  2137. BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
  2138. spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
  2139. shadow_user_mask | shadow_x_mask | shadow_me_mask;
  2140. if (sp_ad_disabled(sp))
  2141. spte |= shadow_acc_track_value;
  2142. else
  2143. spte |= shadow_accessed_mask;
  2144. mmu_spte_set(sptep, spte);
  2145. mmu_page_add_parent_pte(vcpu, sp, sptep);
  2146. if (sp->unsync_children || sp->unsync)
  2147. mark_unsync(sptep);
  2148. }
  2149. static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
  2150. unsigned direct_access)
  2151. {
  2152. if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
  2153. struct kvm_mmu_page *child;
  2154. /*
  2155. * For the direct sp, if the guest pte's dirty bit
  2156. * changed form clean to dirty, it will corrupt the
  2157. * sp's access: allow writable in the read-only sp,
  2158. * so we should update the spte at this point to get
  2159. * a new sp with the correct access.
  2160. */
  2161. child = page_header(*sptep & PT64_BASE_ADDR_MASK);
  2162. if (child->role.access == direct_access)
  2163. return;
  2164. drop_parent_pte(child, sptep);
  2165. kvm_flush_remote_tlbs(vcpu->kvm);
  2166. }
  2167. }
  2168. static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
  2169. u64 *spte)
  2170. {
  2171. u64 pte;
  2172. struct kvm_mmu_page *child;
  2173. pte = *spte;
  2174. if (is_shadow_present_pte(pte)) {
  2175. if (is_last_spte(pte, sp->role.level)) {
  2176. drop_spte(kvm, spte);
  2177. if (is_large_pte(pte))
  2178. --kvm->stat.lpages;
  2179. } else {
  2180. child = page_header(pte & PT64_BASE_ADDR_MASK);
  2181. drop_parent_pte(child, spte);
  2182. }
  2183. return true;
  2184. }
  2185. if (is_mmio_spte(pte))
  2186. mmu_spte_clear_no_track(spte);
  2187. return false;
  2188. }
  2189. static void kvm_mmu_page_unlink_children(struct kvm *kvm,
  2190. struct kvm_mmu_page *sp)
  2191. {
  2192. unsigned i;
  2193. for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
  2194. mmu_page_zap_pte(kvm, sp, sp->spt + i);
  2195. }
  2196. static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
  2197. {
  2198. u64 *sptep;
  2199. struct rmap_iterator iter;
  2200. while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
  2201. drop_parent_pte(sp, sptep);
  2202. }
  2203. static int mmu_zap_unsync_children(struct kvm *kvm,
  2204. struct kvm_mmu_page *parent,
  2205. struct list_head *invalid_list)
  2206. {
  2207. int i, zapped = 0;
  2208. struct mmu_page_path parents;
  2209. struct kvm_mmu_pages pages;
  2210. if (parent->role.level == PT_PAGE_TABLE_LEVEL)
  2211. return 0;
  2212. while (mmu_unsync_walk(parent, &pages)) {
  2213. struct kvm_mmu_page *sp;
  2214. for_each_sp(pages, sp, parents, i) {
  2215. kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2216. mmu_pages_clear_parents(&parents);
  2217. zapped++;
  2218. }
  2219. }
  2220. return zapped;
  2221. }
  2222. static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
  2223. struct list_head *invalid_list)
  2224. {
  2225. int ret;
  2226. trace_kvm_mmu_prepare_zap_page(sp);
  2227. ++kvm->stat.mmu_shadow_zapped;
  2228. ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
  2229. kvm_mmu_page_unlink_children(kvm, sp);
  2230. kvm_mmu_unlink_parents(kvm, sp);
  2231. if (!sp->role.invalid && !sp->role.direct)
  2232. unaccount_shadowed(kvm, sp);
  2233. if (sp->unsync)
  2234. kvm_unlink_unsync_page(kvm, sp);
  2235. if (!sp->root_count) {
  2236. /* Count self */
  2237. ret++;
  2238. list_move(&sp->link, invalid_list);
  2239. kvm_mod_used_mmu_pages(kvm, -1);
  2240. } else {
  2241. list_move(&sp->link, &kvm->arch.active_mmu_pages);
  2242. /*
  2243. * The obsolete pages can not be used on any vcpus.
  2244. * See the comments in kvm_mmu_invalidate_zap_all_pages().
  2245. */
  2246. if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
  2247. kvm_reload_remote_mmus(kvm);
  2248. }
  2249. if (sp->lpage_disallowed)
  2250. unaccount_huge_nx_page(kvm, sp);
  2251. sp->role.invalid = 1;
  2252. return ret;
  2253. }
  2254. static void kvm_mmu_commit_zap_page(struct kvm *kvm,
  2255. struct list_head *invalid_list)
  2256. {
  2257. struct kvm_mmu_page *sp, *nsp;
  2258. if (list_empty(invalid_list))
  2259. return;
  2260. /*
  2261. * We need to make sure everyone sees our modifications to
  2262. * the page tables and see changes to vcpu->mode here. The barrier
  2263. * in the kvm_flush_remote_tlbs() achieves this. This pairs
  2264. * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
  2265. *
  2266. * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
  2267. * guest mode and/or lockless shadow page table walks.
  2268. */
  2269. kvm_flush_remote_tlbs(kvm);
  2270. list_for_each_entry_safe(sp, nsp, invalid_list, link) {
  2271. WARN_ON(!sp->role.invalid || sp->root_count);
  2272. kvm_mmu_free_page(sp);
  2273. }
  2274. }
  2275. static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
  2276. struct list_head *invalid_list)
  2277. {
  2278. struct kvm_mmu_page *sp;
  2279. if (list_empty(&kvm->arch.active_mmu_pages))
  2280. return false;
  2281. sp = list_last_entry(&kvm->arch.active_mmu_pages,
  2282. struct kvm_mmu_page, link);
  2283. return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  2284. }
  2285. /*
  2286. * Changing the number of mmu pages allocated to the vm
  2287. * Note: if goal_nr_mmu_pages is too small, you will get dead lock
  2288. */
  2289. void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
  2290. {
  2291. LIST_HEAD(invalid_list);
  2292. spin_lock(&kvm->mmu_lock);
  2293. if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
  2294. /* Need to free some mmu pages to achieve the goal. */
  2295. while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
  2296. if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
  2297. break;
  2298. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2299. goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
  2300. }
  2301. kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
  2302. spin_unlock(&kvm->mmu_lock);
  2303. }
  2304. int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
  2305. {
  2306. struct kvm_mmu_page *sp;
  2307. LIST_HEAD(invalid_list);
  2308. int r;
  2309. pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
  2310. r = 0;
  2311. spin_lock(&kvm->mmu_lock);
  2312. for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
  2313. pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
  2314. sp->role.word);
  2315. r = 1;
  2316. kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
  2317. }
  2318. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  2319. spin_unlock(&kvm->mmu_lock);
  2320. return r;
  2321. }
  2322. EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
  2323. static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
  2324. {
  2325. trace_kvm_mmu_unsync_page(sp);
  2326. ++vcpu->kvm->stat.mmu_unsync;
  2327. sp->unsync = 1;
  2328. kvm_mmu_mark_parents_unsync(sp);
  2329. }
  2330. static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
  2331. bool can_unsync)
  2332. {
  2333. struct kvm_mmu_page *sp;
  2334. if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
  2335. return true;
  2336. for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
  2337. if (!can_unsync)
  2338. return true;
  2339. if (sp->unsync)
  2340. continue;
  2341. WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
  2342. kvm_unsync_page(vcpu, sp);
  2343. }
  2344. return false;
  2345. }
  2346. static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
  2347. {
  2348. if (pfn_valid(pfn))
  2349. return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn));
  2350. return true;
  2351. }
  2352. static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
  2353. unsigned pte_access, int level,
  2354. gfn_t gfn, kvm_pfn_t pfn, bool speculative,
  2355. bool can_unsync, bool host_writable)
  2356. {
  2357. u64 spte = 0;
  2358. int ret = 0;
  2359. struct kvm_mmu_page *sp;
  2360. if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
  2361. return 0;
  2362. sp = page_header(__pa(sptep));
  2363. if (sp_ad_disabled(sp))
  2364. spte |= shadow_acc_track_value;
  2365. /*
  2366. * For the EPT case, shadow_present_mask is 0 if hardware
  2367. * supports exec-only page table entries. In that case,
  2368. * ACC_USER_MASK and shadow_user_mask are used to represent
  2369. * read access. See FNAME(gpte_access) in paging_tmpl.h.
  2370. */
  2371. spte |= shadow_present_mask;
  2372. if (!speculative)
  2373. spte |= spte_shadow_accessed_mask(spte);
  2374. if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
  2375. is_nx_huge_page_enabled()) {
  2376. pte_access &= ~ACC_EXEC_MASK;
  2377. }
  2378. if (pte_access & ACC_EXEC_MASK)
  2379. spte |= shadow_x_mask;
  2380. else
  2381. spte |= shadow_nx_mask;
  2382. if (pte_access & ACC_USER_MASK)
  2383. spte |= shadow_user_mask;
  2384. if (level > PT_PAGE_TABLE_LEVEL)
  2385. spte |= PT_PAGE_SIZE_MASK;
  2386. if (tdp_enabled)
  2387. spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
  2388. kvm_is_mmio_pfn(pfn));
  2389. if (host_writable)
  2390. spte |= SPTE_HOST_WRITEABLE;
  2391. else
  2392. pte_access &= ~ACC_WRITE_MASK;
  2393. if (!kvm_is_mmio_pfn(pfn))
  2394. spte |= shadow_me_mask;
  2395. spte |= (u64)pfn << PAGE_SHIFT;
  2396. if (pte_access & ACC_WRITE_MASK) {
  2397. /*
  2398. * Other vcpu creates new sp in the window between
  2399. * mapping_level() and acquiring mmu-lock. We can
  2400. * allow guest to retry the access, the mapping can
  2401. * be fixed if guest refault.
  2402. */
  2403. if (level > PT_PAGE_TABLE_LEVEL &&
  2404. mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
  2405. goto done;
  2406. spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
  2407. /*
  2408. * Optimization: for pte sync, if spte was writable the hash
  2409. * lookup is unnecessary (and expensive). Write protection
  2410. * is responsibility of mmu_get_page / kvm_sync_page.
  2411. * Same reasoning can be applied to dirty page accounting.
  2412. */
  2413. if (!can_unsync && is_writable_pte(*sptep))
  2414. goto set_pte;
  2415. if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
  2416. pgprintk("%s: found shadow page for %llx, marking ro\n",
  2417. __func__, gfn);
  2418. ret = 1;
  2419. pte_access &= ~ACC_WRITE_MASK;
  2420. spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
  2421. }
  2422. }
  2423. if (pte_access & ACC_WRITE_MASK) {
  2424. kvm_vcpu_mark_page_dirty(vcpu, gfn);
  2425. spte |= spte_shadow_dirty_mask(spte);
  2426. }
  2427. if (speculative)
  2428. spte = mark_spte_for_access_track(spte);
  2429. set_pte:
  2430. if (mmu_spte_update(sptep, spte))
  2431. kvm_flush_remote_tlbs(vcpu->kvm);
  2432. done:
  2433. return ret;
  2434. }
  2435. static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
  2436. int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
  2437. bool speculative, bool host_writable)
  2438. {
  2439. int was_rmapped = 0;
  2440. int rmap_count;
  2441. int ret = RET_PF_RETRY;
  2442. pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
  2443. *sptep, write_fault, gfn);
  2444. if (is_shadow_present_pte(*sptep)) {
  2445. /*
  2446. * If we overwrite a PTE page pointer with a 2MB PMD, unlink
  2447. * the parent of the now unreachable PTE.
  2448. */
  2449. if (level > PT_PAGE_TABLE_LEVEL &&
  2450. !is_large_pte(*sptep)) {
  2451. struct kvm_mmu_page *child;
  2452. u64 pte = *sptep;
  2453. child = page_header(pte & PT64_BASE_ADDR_MASK);
  2454. drop_parent_pte(child, sptep);
  2455. kvm_flush_remote_tlbs(vcpu->kvm);
  2456. } else if (pfn != spte_to_pfn(*sptep)) {
  2457. pgprintk("hfn old %llx new %llx\n",
  2458. spte_to_pfn(*sptep), pfn);
  2459. drop_spte(vcpu->kvm, sptep);
  2460. kvm_flush_remote_tlbs(vcpu->kvm);
  2461. } else
  2462. was_rmapped = 1;
  2463. }
  2464. if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
  2465. true, host_writable)) {
  2466. if (write_fault)
  2467. ret = RET_PF_EMULATE;
  2468. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  2469. }
  2470. if (unlikely(is_mmio_spte(*sptep)))
  2471. ret = RET_PF_EMULATE;
  2472. pgprintk("%s: setting spte %llx\n", __func__, *sptep);
  2473. trace_kvm_mmu_set_spte(level, gfn, sptep);
  2474. if (!was_rmapped && is_large_pte(*sptep))
  2475. ++vcpu->kvm->stat.lpages;
  2476. if (is_shadow_present_pte(*sptep)) {
  2477. if (!was_rmapped) {
  2478. rmap_count = rmap_add(vcpu, sptep, gfn);
  2479. if (rmap_count > RMAP_RECYCLE_THRESHOLD)
  2480. rmap_recycle(vcpu, sptep, gfn);
  2481. }
  2482. }
  2483. return ret;
  2484. }
  2485. static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
  2486. bool no_dirty_log)
  2487. {
  2488. struct kvm_memory_slot *slot;
  2489. slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
  2490. if (!slot)
  2491. return KVM_PFN_ERR_FAULT;
  2492. return gfn_to_pfn_memslot_atomic(slot, gfn);
  2493. }
  2494. static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
  2495. struct kvm_mmu_page *sp,
  2496. u64 *start, u64 *end)
  2497. {
  2498. struct page *pages[PTE_PREFETCH_NUM];
  2499. struct kvm_memory_slot *slot;
  2500. unsigned access = sp->role.access;
  2501. int i, ret;
  2502. gfn_t gfn;
  2503. gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
  2504. slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
  2505. if (!slot)
  2506. return -1;
  2507. ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
  2508. if (ret <= 0)
  2509. return -1;
  2510. for (i = 0; i < ret; i++, gfn++, start++) {
  2511. mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
  2512. page_to_pfn(pages[i]), true, true);
  2513. put_page(pages[i]);
  2514. }
  2515. return 0;
  2516. }
  2517. static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
  2518. struct kvm_mmu_page *sp, u64 *sptep)
  2519. {
  2520. u64 *spte, *start = NULL;
  2521. int i;
  2522. WARN_ON(!sp->role.direct);
  2523. i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
  2524. spte = sp->spt + i;
  2525. for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
  2526. if (is_shadow_present_pte(*spte) || spte == sptep) {
  2527. if (!start)
  2528. continue;
  2529. if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
  2530. break;
  2531. start = NULL;
  2532. } else if (!start)
  2533. start = spte;
  2534. }
  2535. }
  2536. static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
  2537. {
  2538. struct kvm_mmu_page *sp;
  2539. sp = page_header(__pa(sptep));
  2540. /*
  2541. * Without accessed bits, there's no way to distinguish between
  2542. * actually accessed translations and prefetched, so disable pte
  2543. * prefetch if accessed bits aren't available.
  2544. */
  2545. if (sp_ad_disabled(sp))
  2546. return;
  2547. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  2548. return;
  2549. __direct_pte_prefetch(vcpu, sp, sptep);
  2550. }
  2551. static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
  2552. gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
  2553. {
  2554. int level = *levelp;
  2555. u64 spte = *it.sptep;
  2556. if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
  2557. is_nx_huge_page_enabled() &&
  2558. is_shadow_present_pte(spte) &&
  2559. !is_large_pte(spte)) {
  2560. /*
  2561. * A small SPTE exists for this pfn, but FNAME(fetch)
  2562. * and __direct_map would like to create a large PTE
  2563. * instead: just force them to go down another level,
  2564. * patching back for them into pfn the next 9 bits of
  2565. * the address.
  2566. */
  2567. u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
  2568. *pfnp |= gfn & page_mask;
  2569. (*levelp)--;
  2570. }
  2571. }
  2572. static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
  2573. int map_writable, int level, kvm_pfn_t pfn,
  2574. bool prefault, bool lpage_disallowed)
  2575. {
  2576. struct kvm_shadow_walk_iterator it;
  2577. struct kvm_mmu_page *sp;
  2578. int ret;
  2579. gfn_t gfn = gpa >> PAGE_SHIFT;
  2580. gfn_t base_gfn = gfn;
  2581. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  2582. return RET_PF_RETRY;
  2583. trace_kvm_mmu_spte_requested(gpa, level, pfn);
  2584. for_each_shadow_entry(vcpu, gpa, it) {
  2585. /*
  2586. * We cannot overwrite existing page tables with an NX
  2587. * large page, as the leaf could be executable.
  2588. */
  2589. disallowed_hugepage_adjust(it, gfn, &pfn, &level);
  2590. base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
  2591. if (it.level == level)
  2592. break;
  2593. drop_large_spte(vcpu, it.sptep);
  2594. if (!is_shadow_present_pte(*it.sptep)) {
  2595. sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
  2596. it.level - 1, true, ACC_ALL);
  2597. link_shadow_page(vcpu, it.sptep, sp);
  2598. if (lpage_disallowed)
  2599. account_huge_nx_page(vcpu->kvm, sp);
  2600. }
  2601. }
  2602. ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
  2603. write, level, base_gfn, pfn, prefault,
  2604. map_writable);
  2605. direct_pte_prefetch(vcpu, it.sptep);
  2606. ++vcpu->stat.pf_fixed;
  2607. return ret;
  2608. }
  2609. static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
  2610. {
  2611. siginfo_t info;
  2612. info.si_signo = SIGBUS;
  2613. info.si_errno = 0;
  2614. info.si_code = BUS_MCEERR_AR;
  2615. info.si_addr = (void __user *)address;
  2616. info.si_addr_lsb = PAGE_SHIFT;
  2617. send_sig_info(SIGBUS, &info, tsk);
  2618. }
  2619. static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
  2620. {
  2621. /*
  2622. * Do not cache the mmio info caused by writing the readonly gfn
  2623. * into the spte otherwise read access on readonly gfn also can
  2624. * caused mmio page fault and treat it as mmio access.
  2625. */
  2626. if (pfn == KVM_PFN_ERR_RO_FAULT)
  2627. return RET_PF_EMULATE;
  2628. if (pfn == KVM_PFN_ERR_HWPOISON) {
  2629. kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
  2630. return RET_PF_RETRY;
  2631. }
  2632. return -EFAULT;
  2633. }
  2634. static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
  2635. gfn_t gfn, kvm_pfn_t *pfnp,
  2636. int *levelp)
  2637. {
  2638. kvm_pfn_t pfn = *pfnp;
  2639. int level = *levelp;
  2640. /*
  2641. * Check if it's a transparent hugepage. If this would be an
  2642. * hugetlbfs page, level wouldn't be set to
  2643. * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
  2644. * here.
  2645. */
  2646. if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
  2647. !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
  2648. PageTransCompoundMap(pfn_to_page(pfn)) &&
  2649. !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
  2650. unsigned long mask;
  2651. /*
  2652. * mmu_notifier_retry was successful and we hold the
  2653. * mmu_lock here, so the pmd can't become splitting
  2654. * from under us, and in turn
  2655. * __split_huge_page_refcount() can't run from under
  2656. * us and we can safely transfer the refcount from
  2657. * PG_tail to PG_head as we switch the pfn to tail to
  2658. * head.
  2659. */
  2660. *levelp = level = PT_DIRECTORY_LEVEL;
  2661. mask = KVM_PAGES_PER_HPAGE(level) - 1;
  2662. VM_BUG_ON((gfn & mask) != (pfn & mask));
  2663. if (pfn & mask) {
  2664. kvm_release_pfn_clean(pfn);
  2665. pfn &= ~mask;
  2666. kvm_get_pfn(pfn);
  2667. *pfnp = pfn;
  2668. }
  2669. }
  2670. }
  2671. static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
  2672. kvm_pfn_t pfn, unsigned access, int *ret_val)
  2673. {
  2674. /* The pfn is invalid, report the error! */
  2675. if (unlikely(is_error_pfn(pfn))) {
  2676. *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
  2677. return true;
  2678. }
  2679. if (unlikely(is_noslot_pfn(pfn)))
  2680. vcpu_cache_mmio_info(vcpu, gva, gfn, access);
  2681. return false;
  2682. }
  2683. static bool page_fault_can_be_fast(u32 error_code)
  2684. {
  2685. /*
  2686. * Do not fix the mmio spte with invalid generation number which
  2687. * need to be updated by slow page fault path.
  2688. */
  2689. if (unlikely(error_code & PFERR_RSVD_MASK))
  2690. return false;
  2691. /* See if the page fault is due to an NX violation */
  2692. if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
  2693. == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
  2694. return false;
  2695. /*
  2696. * #PF can be fast if:
  2697. * 1. The shadow page table entry is not present, which could mean that
  2698. * the fault is potentially caused by access tracking (if enabled).
  2699. * 2. The shadow page table entry is present and the fault
  2700. * is caused by write-protect, that means we just need change the W
  2701. * bit of the spte which can be done out of mmu-lock.
  2702. *
  2703. * However, if access tracking is disabled we know that a non-present
  2704. * page must be a genuine page fault where we have to create a new SPTE.
  2705. * So, if access tracking is disabled, we return true only for write
  2706. * accesses to a present page.
  2707. */
  2708. return shadow_acc_track_mask != 0 ||
  2709. ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
  2710. == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
  2711. }
  2712. /*
  2713. * Returns true if the SPTE was fixed successfully. Otherwise,
  2714. * someone else modified the SPTE from its original value.
  2715. */
  2716. static bool
  2717. fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
  2718. u64 *sptep, u64 old_spte, u64 new_spte)
  2719. {
  2720. gfn_t gfn;
  2721. WARN_ON(!sp->role.direct);
  2722. /*
  2723. * Theoretically we could also set dirty bit (and flush TLB) here in
  2724. * order to eliminate unnecessary PML logging. See comments in
  2725. * set_spte. But fast_page_fault is very unlikely to happen with PML
  2726. * enabled, so we do not do this. This might result in the same GPA
  2727. * to be logged in PML buffer again when the write really happens, and
  2728. * eventually to be called by mark_page_dirty twice. But it's also no
  2729. * harm. This also avoids the TLB flush needed after setting dirty bit
  2730. * so non-PML cases won't be impacted.
  2731. *
  2732. * Compare with set_spte where instead shadow_dirty_mask is set.
  2733. */
  2734. if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
  2735. return false;
  2736. if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
  2737. /*
  2738. * The gfn of direct spte is stable since it is
  2739. * calculated by sp->gfn.
  2740. */
  2741. gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
  2742. kvm_vcpu_mark_page_dirty(vcpu, gfn);
  2743. }
  2744. return true;
  2745. }
  2746. static bool is_access_allowed(u32 fault_err_code, u64 spte)
  2747. {
  2748. if (fault_err_code & PFERR_FETCH_MASK)
  2749. return is_executable_pte(spte);
  2750. if (fault_err_code & PFERR_WRITE_MASK)
  2751. return is_writable_pte(spte);
  2752. /* Fault was on Read access */
  2753. return spte & PT_PRESENT_MASK;
  2754. }
  2755. /*
  2756. * Return value:
  2757. * - true: let the vcpu to access on the same address again.
  2758. * - false: let the real page fault path to fix it.
  2759. */
  2760. static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
  2761. u32 error_code)
  2762. {
  2763. struct kvm_shadow_walk_iterator iterator;
  2764. struct kvm_mmu_page *sp;
  2765. bool fault_handled = false;
  2766. u64 spte = 0ull;
  2767. uint retry_count = 0;
  2768. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  2769. return false;
  2770. if (!page_fault_can_be_fast(error_code))
  2771. return false;
  2772. walk_shadow_page_lockless_begin(vcpu);
  2773. do {
  2774. u64 new_spte;
  2775. for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
  2776. if (!is_shadow_present_pte(spte) ||
  2777. iterator.level < level)
  2778. break;
  2779. sp = page_header(__pa(iterator.sptep));
  2780. if (!is_last_spte(spte, sp->role.level))
  2781. break;
  2782. /*
  2783. * Check whether the memory access that caused the fault would
  2784. * still cause it if it were to be performed right now. If not,
  2785. * then this is a spurious fault caused by TLB lazily flushed,
  2786. * or some other CPU has already fixed the PTE after the
  2787. * current CPU took the fault.
  2788. *
  2789. * Need not check the access of upper level table entries since
  2790. * they are always ACC_ALL.
  2791. */
  2792. if (is_access_allowed(error_code, spte)) {
  2793. fault_handled = true;
  2794. break;
  2795. }
  2796. new_spte = spte;
  2797. if (is_access_track_spte(spte))
  2798. new_spte = restore_acc_track_spte(new_spte);
  2799. /*
  2800. * Currently, to simplify the code, write-protection can
  2801. * be removed in the fast path only if the SPTE was
  2802. * write-protected for dirty-logging or access tracking.
  2803. */
  2804. if ((error_code & PFERR_WRITE_MASK) &&
  2805. spte_can_locklessly_be_made_writable(spte))
  2806. {
  2807. new_spte |= PT_WRITABLE_MASK;
  2808. /*
  2809. * Do not fix write-permission on the large spte. Since
  2810. * we only dirty the first page into the dirty-bitmap in
  2811. * fast_pf_fix_direct_spte(), other pages are missed
  2812. * if its slot has dirty logging enabled.
  2813. *
  2814. * Instead, we let the slow page fault path create a
  2815. * normal spte to fix the access.
  2816. *
  2817. * See the comments in kvm_arch_commit_memory_region().
  2818. */
  2819. if (sp->role.level > PT_PAGE_TABLE_LEVEL)
  2820. break;
  2821. }
  2822. /* Verify that the fault can be handled in the fast path */
  2823. if (new_spte == spte ||
  2824. !is_access_allowed(error_code, new_spte))
  2825. break;
  2826. /*
  2827. * Currently, fast page fault only works for direct mapping
  2828. * since the gfn is not stable for indirect shadow page. See
  2829. * Documentation/virtual/kvm/locking.txt to get more detail.
  2830. */
  2831. fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
  2832. iterator.sptep, spte,
  2833. new_spte);
  2834. if (fault_handled)
  2835. break;
  2836. if (++retry_count > 4) {
  2837. printk_once(KERN_WARNING
  2838. "kvm: Fast #PF retrying more than 4 times.\n");
  2839. break;
  2840. }
  2841. } while (true);
  2842. trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
  2843. spte, fault_handled);
  2844. walk_shadow_page_lockless_end(vcpu);
  2845. return fault_handled;
  2846. }
  2847. static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
  2848. gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
  2849. static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
  2850. static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
  2851. gfn_t gfn, bool prefault)
  2852. {
  2853. int r;
  2854. int level;
  2855. bool force_pt_level;
  2856. kvm_pfn_t pfn;
  2857. unsigned long mmu_seq;
  2858. bool map_writable, write = error_code & PFERR_WRITE_MASK;
  2859. bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
  2860. is_nx_huge_page_enabled();
  2861. force_pt_level = lpage_disallowed;
  2862. level = mapping_level(vcpu, gfn, &force_pt_level);
  2863. if (likely(!force_pt_level)) {
  2864. /*
  2865. * This path builds a PAE pagetable - so we can map
  2866. * 2mb pages at maximum. Therefore check if the level
  2867. * is larger than that.
  2868. */
  2869. if (level > PT_DIRECTORY_LEVEL)
  2870. level = PT_DIRECTORY_LEVEL;
  2871. gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
  2872. }
  2873. if (fast_page_fault(vcpu, v, level, error_code))
  2874. return RET_PF_RETRY;
  2875. mmu_seq = vcpu->kvm->mmu_notifier_seq;
  2876. smp_rmb();
  2877. if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
  2878. return RET_PF_RETRY;
  2879. if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
  2880. return r;
  2881. r = RET_PF_RETRY;
  2882. spin_lock(&vcpu->kvm->mmu_lock);
  2883. if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
  2884. goto out_unlock;
  2885. if (make_mmu_pages_available(vcpu) < 0)
  2886. goto out_unlock;
  2887. if (likely(!force_pt_level))
  2888. transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
  2889. r = __direct_map(vcpu, v, write, map_writable, level, pfn,
  2890. prefault, false);
  2891. out_unlock:
  2892. spin_unlock(&vcpu->kvm->mmu_lock);
  2893. kvm_release_pfn_clean(pfn);
  2894. return r;
  2895. }
  2896. static void mmu_free_roots(struct kvm_vcpu *vcpu)
  2897. {
  2898. int i;
  2899. struct kvm_mmu_page *sp;
  2900. LIST_HEAD(invalid_list);
  2901. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  2902. return;
  2903. if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL &&
  2904. (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL ||
  2905. vcpu->arch.mmu.direct_map)) {
  2906. hpa_t root = vcpu->arch.mmu.root_hpa;
  2907. spin_lock(&vcpu->kvm->mmu_lock);
  2908. sp = page_header(root);
  2909. --sp->root_count;
  2910. if (!sp->root_count && sp->role.invalid) {
  2911. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
  2912. kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
  2913. }
  2914. spin_unlock(&vcpu->kvm->mmu_lock);
  2915. vcpu->arch.mmu.root_hpa = INVALID_PAGE;
  2916. return;
  2917. }
  2918. spin_lock(&vcpu->kvm->mmu_lock);
  2919. for (i = 0; i < 4; ++i) {
  2920. hpa_t root = vcpu->arch.mmu.pae_root[i];
  2921. if (root) {
  2922. root &= PT64_BASE_ADDR_MASK;
  2923. sp = page_header(root);
  2924. --sp->root_count;
  2925. if (!sp->root_count && sp->role.invalid)
  2926. kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
  2927. &invalid_list);
  2928. }
  2929. vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
  2930. }
  2931. kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
  2932. spin_unlock(&vcpu->kvm->mmu_lock);
  2933. vcpu->arch.mmu.root_hpa = INVALID_PAGE;
  2934. }
  2935. static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
  2936. {
  2937. int ret = 0;
  2938. if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
  2939. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2940. ret = 1;
  2941. }
  2942. return ret;
  2943. }
  2944. static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
  2945. {
  2946. struct kvm_mmu_page *sp;
  2947. unsigned i;
  2948. if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
  2949. spin_lock(&vcpu->kvm->mmu_lock);
  2950. if(make_mmu_pages_available(vcpu) < 0) {
  2951. spin_unlock(&vcpu->kvm->mmu_lock);
  2952. return -ENOSPC;
  2953. }
  2954. sp = kvm_mmu_get_page(vcpu, 0, 0,
  2955. vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
  2956. ++sp->root_count;
  2957. spin_unlock(&vcpu->kvm->mmu_lock);
  2958. vcpu->arch.mmu.root_hpa = __pa(sp->spt);
  2959. } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
  2960. for (i = 0; i < 4; ++i) {
  2961. hpa_t root = vcpu->arch.mmu.pae_root[i];
  2962. MMU_WARN_ON(VALID_PAGE(root));
  2963. spin_lock(&vcpu->kvm->mmu_lock);
  2964. if (make_mmu_pages_available(vcpu) < 0) {
  2965. spin_unlock(&vcpu->kvm->mmu_lock);
  2966. return -ENOSPC;
  2967. }
  2968. sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
  2969. i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
  2970. root = __pa(sp->spt);
  2971. ++sp->root_count;
  2972. spin_unlock(&vcpu->kvm->mmu_lock);
  2973. vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
  2974. }
  2975. vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
  2976. } else
  2977. BUG();
  2978. return 0;
  2979. }
  2980. static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
  2981. {
  2982. struct kvm_mmu_page *sp;
  2983. u64 pdptr, pm_mask;
  2984. gfn_t root_gfn;
  2985. int i;
  2986. root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
  2987. if (mmu_check_root(vcpu, root_gfn))
  2988. return 1;
  2989. /*
  2990. * Do we shadow a long mode page table? If so we need to
  2991. * write-protect the guests page table root.
  2992. */
  2993. if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
  2994. hpa_t root = vcpu->arch.mmu.root_hpa;
  2995. MMU_WARN_ON(VALID_PAGE(root));
  2996. spin_lock(&vcpu->kvm->mmu_lock);
  2997. if (make_mmu_pages_available(vcpu) < 0) {
  2998. spin_unlock(&vcpu->kvm->mmu_lock);
  2999. return -ENOSPC;
  3000. }
  3001. sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
  3002. vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
  3003. root = __pa(sp->spt);
  3004. ++sp->root_count;
  3005. spin_unlock(&vcpu->kvm->mmu_lock);
  3006. vcpu->arch.mmu.root_hpa = root;
  3007. return 0;
  3008. }
  3009. /*
  3010. * We shadow a 32 bit page table. This may be a legacy 2-level
  3011. * or a PAE 3-level page table. In either case we need to be aware that
  3012. * the shadow page table may be a PAE or a long mode page table.
  3013. */
  3014. pm_mask = PT_PRESENT_MASK;
  3015. if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
  3016. pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
  3017. for (i = 0; i < 4; ++i) {
  3018. hpa_t root = vcpu->arch.mmu.pae_root[i];
  3019. MMU_WARN_ON(VALID_PAGE(root));
  3020. if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
  3021. pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
  3022. if (!(pdptr & PT_PRESENT_MASK)) {
  3023. vcpu->arch.mmu.pae_root[i] = 0;
  3024. continue;
  3025. }
  3026. root_gfn = pdptr >> PAGE_SHIFT;
  3027. if (mmu_check_root(vcpu, root_gfn))
  3028. return 1;
  3029. }
  3030. spin_lock(&vcpu->kvm->mmu_lock);
  3031. if (make_mmu_pages_available(vcpu) < 0) {
  3032. spin_unlock(&vcpu->kvm->mmu_lock);
  3033. return -ENOSPC;
  3034. }
  3035. sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
  3036. 0, ACC_ALL);
  3037. root = __pa(sp->spt);
  3038. ++sp->root_count;
  3039. spin_unlock(&vcpu->kvm->mmu_lock);
  3040. vcpu->arch.mmu.pae_root[i] = root | pm_mask;
  3041. }
  3042. vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
  3043. /*
  3044. * If we shadow a 32 bit page table with a long mode page
  3045. * table we enter this path.
  3046. */
  3047. if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
  3048. if (vcpu->arch.mmu.lm_root == NULL) {
  3049. /*
  3050. * The additional page necessary for this is only
  3051. * allocated on demand.
  3052. */
  3053. u64 *lm_root;
  3054. lm_root = (void*)get_zeroed_page(GFP_KERNEL);
  3055. if (lm_root == NULL)
  3056. return 1;
  3057. lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
  3058. vcpu->arch.mmu.lm_root = lm_root;
  3059. }
  3060. vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
  3061. }
  3062. return 0;
  3063. }
  3064. static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
  3065. {
  3066. if (vcpu->arch.mmu.direct_map)
  3067. return mmu_alloc_direct_roots(vcpu);
  3068. else
  3069. return mmu_alloc_shadow_roots(vcpu);
  3070. }
  3071. static void mmu_sync_roots(struct kvm_vcpu *vcpu)
  3072. {
  3073. int i;
  3074. struct kvm_mmu_page *sp;
  3075. if (vcpu->arch.mmu.direct_map)
  3076. return;
  3077. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  3078. return;
  3079. vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
  3080. kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
  3081. if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
  3082. hpa_t root = vcpu->arch.mmu.root_hpa;
  3083. sp = page_header(root);
  3084. mmu_sync_children(vcpu, sp);
  3085. kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
  3086. return;
  3087. }
  3088. for (i = 0; i < 4; ++i) {
  3089. hpa_t root = vcpu->arch.mmu.pae_root[i];
  3090. if (root && VALID_PAGE(root)) {
  3091. root &= PT64_BASE_ADDR_MASK;
  3092. sp = page_header(root);
  3093. mmu_sync_children(vcpu, sp);
  3094. }
  3095. }
  3096. kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
  3097. }
  3098. void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
  3099. {
  3100. spin_lock(&vcpu->kvm->mmu_lock);
  3101. mmu_sync_roots(vcpu);
  3102. spin_unlock(&vcpu->kvm->mmu_lock);
  3103. }
  3104. EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
  3105. static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
  3106. u32 access, struct x86_exception *exception)
  3107. {
  3108. if (exception)
  3109. exception->error_code = 0;
  3110. return vaddr;
  3111. }
  3112. static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
  3113. u32 access,
  3114. struct x86_exception *exception)
  3115. {
  3116. if (exception)
  3117. exception->error_code = 0;
  3118. return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
  3119. }
  3120. static bool
  3121. __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
  3122. {
  3123. int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
  3124. return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
  3125. ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
  3126. }
  3127. static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
  3128. {
  3129. return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
  3130. }
  3131. static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
  3132. {
  3133. return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
  3134. }
  3135. static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3136. {
  3137. /*
  3138. * A nested guest cannot use the MMIO cache if it is using nested
  3139. * page tables, because cr2 is a nGPA while the cache stores GPAs.
  3140. */
  3141. if (mmu_is_nested(vcpu))
  3142. return false;
  3143. if (direct)
  3144. return vcpu_match_mmio_gpa(vcpu, addr);
  3145. return vcpu_match_mmio_gva(vcpu, addr);
  3146. }
  3147. /* return true if reserved bit is detected on spte. */
  3148. static bool
  3149. walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
  3150. {
  3151. struct kvm_shadow_walk_iterator iterator;
  3152. u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
  3153. int root, leaf;
  3154. bool reserved = false;
  3155. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  3156. goto exit;
  3157. walk_shadow_page_lockless_begin(vcpu);
  3158. for (shadow_walk_init(&iterator, vcpu, addr),
  3159. leaf = root = iterator.level;
  3160. shadow_walk_okay(&iterator);
  3161. __shadow_walk_next(&iterator, spte)) {
  3162. spte = mmu_spte_get_lockless(iterator.sptep);
  3163. sptes[leaf - 1] = spte;
  3164. leaf--;
  3165. if (!is_shadow_present_pte(spte))
  3166. break;
  3167. reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
  3168. iterator.level);
  3169. }
  3170. walk_shadow_page_lockless_end(vcpu);
  3171. if (reserved) {
  3172. pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
  3173. __func__, addr);
  3174. while (root > leaf) {
  3175. pr_err("------ spte 0x%llx level %d.\n",
  3176. sptes[root - 1], root);
  3177. root--;
  3178. }
  3179. }
  3180. exit:
  3181. *sptep = spte;
  3182. return reserved;
  3183. }
  3184. static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
  3185. {
  3186. u64 spte;
  3187. bool reserved;
  3188. if (mmio_info_in_cache(vcpu, addr, direct))
  3189. return RET_PF_EMULATE;
  3190. reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
  3191. if (WARN_ON(reserved))
  3192. return -EINVAL;
  3193. if (is_mmio_spte(spte)) {
  3194. gfn_t gfn = get_mmio_spte_gfn(spte);
  3195. unsigned access = get_mmio_spte_access(spte);
  3196. if (!check_mmio_spte(vcpu, spte))
  3197. return RET_PF_INVALID;
  3198. if (direct)
  3199. addr = 0;
  3200. trace_handle_mmio_page_fault(addr, gfn, access);
  3201. vcpu_cache_mmio_info(vcpu, addr, gfn, access);
  3202. return RET_PF_EMULATE;
  3203. }
  3204. /*
  3205. * If the page table is zapped by other cpus, let CPU fault again on
  3206. * the address.
  3207. */
  3208. return RET_PF_RETRY;
  3209. }
  3210. EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
  3211. static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
  3212. u32 error_code, gfn_t gfn)
  3213. {
  3214. if (unlikely(error_code & PFERR_RSVD_MASK))
  3215. return false;
  3216. if (!(error_code & PFERR_PRESENT_MASK) ||
  3217. !(error_code & PFERR_WRITE_MASK))
  3218. return false;
  3219. /*
  3220. * guest is writing the page which is write tracked which can
  3221. * not be fixed by page fault handler.
  3222. */
  3223. if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
  3224. return true;
  3225. return false;
  3226. }
  3227. static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
  3228. {
  3229. struct kvm_shadow_walk_iterator iterator;
  3230. u64 spte;
  3231. if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
  3232. return;
  3233. walk_shadow_page_lockless_begin(vcpu);
  3234. for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
  3235. clear_sp_write_flooding_count(iterator.sptep);
  3236. if (!is_shadow_present_pte(spte))
  3237. break;
  3238. }
  3239. walk_shadow_page_lockless_end(vcpu);
  3240. }
  3241. static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
  3242. u32 error_code, bool prefault)
  3243. {
  3244. gfn_t gfn = gva >> PAGE_SHIFT;
  3245. int r;
  3246. pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
  3247. if (page_fault_handle_page_track(vcpu, error_code, gfn))
  3248. return RET_PF_EMULATE;
  3249. r = mmu_topup_memory_caches(vcpu);
  3250. if (r)
  3251. return r;
  3252. MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
  3253. return nonpaging_map(vcpu, gva & PAGE_MASK,
  3254. error_code, gfn, prefault);
  3255. }
  3256. static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
  3257. {
  3258. struct kvm_arch_async_pf arch;
  3259. arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
  3260. arch.gfn = gfn;
  3261. arch.direct_map = vcpu->arch.mmu.direct_map;
  3262. arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
  3263. return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
  3264. }
  3265. bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
  3266. {
  3267. if (unlikely(!lapic_in_kernel(vcpu) ||
  3268. kvm_event_needs_reinjection(vcpu) ||
  3269. vcpu->arch.exception.pending))
  3270. return false;
  3271. if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
  3272. return false;
  3273. return kvm_x86_ops->interrupt_allowed(vcpu);
  3274. }
  3275. static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
  3276. gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
  3277. {
  3278. struct kvm_memory_slot *slot;
  3279. bool async;
  3280. slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  3281. async = false;
  3282. *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
  3283. if (!async)
  3284. return false; /* *pfn has correct page already */
  3285. if (!prefault && kvm_can_do_async_pf(vcpu)) {
  3286. trace_kvm_try_async_get_page(gva, gfn);
  3287. if (kvm_find_async_pf_gfn(vcpu, gfn)) {
  3288. trace_kvm_async_pf_doublefault(gva, gfn);
  3289. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  3290. return true;
  3291. } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
  3292. return true;
  3293. }
  3294. *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
  3295. return false;
  3296. }
  3297. int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
  3298. u64 fault_address, char *insn, int insn_len,
  3299. bool need_unprotect)
  3300. {
  3301. int r = 1;
  3302. vcpu->arch.l1tf_flush_l1d = true;
  3303. switch (vcpu->arch.apf.host_apf_reason) {
  3304. default:
  3305. trace_kvm_page_fault(fault_address, error_code);
  3306. if (need_unprotect && kvm_event_needs_reinjection(vcpu))
  3307. kvm_mmu_unprotect_page_virt(vcpu, fault_address);
  3308. r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
  3309. insn_len);
  3310. break;
  3311. case KVM_PV_REASON_PAGE_NOT_PRESENT:
  3312. vcpu->arch.apf.host_apf_reason = 0;
  3313. local_irq_disable();
  3314. kvm_async_pf_task_wait(fault_address, 0);
  3315. local_irq_enable();
  3316. break;
  3317. case KVM_PV_REASON_PAGE_READY:
  3318. vcpu->arch.apf.host_apf_reason = 0;
  3319. local_irq_disable();
  3320. kvm_async_pf_task_wake(fault_address);
  3321. local_irq_enable();
  3322. break;
  3323. }
  3324. return r;
  3325. }
  3326. EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
  3327. static bool
  3328. check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
  3329. {
  3330. int page_num = KVM_PAGES_PER_HPAGE(level);
  3331. gfn &= ~(page_num - 1);
  3332. return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
  3333. }
  3334. static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
  3335. bool prefault)
  3336. {
  3337. kvm_pfn_t pfn;
  3338. int r;
  3339. int level;
  3340. bool force_pt_level;
  3341. gfn_t gfn = gpa >> PAGE_SHIFT;
  3342. unsigned long mmu_seq;
  3343. int write = error_code & PFERR_WRITE_MASK;
  3344. bool map_writable;
  3345. bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
  3346. is_nx_huge_page_enabled();
  3347. MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
  3348. if (page_fault_handle_page_track(vcpu, error_code, gfn))
  3349. return RET_PF_EMULATE;
  3350. r = mmu_topup_memory_caches(vcpu);
  3351. if (r)
  3352. return r;
  3353. force_pt_level =
  3354. lpage_disallowed ||
  3355. !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
  3356. level = mapping_level(vcpu, gfn, &force_pt_level);
  3357. if (likely(!force_pt_level)) {
  3358. if (level > PT_DIRECTORY_LEVEL &&
  3359. !check_hugepage_cache_consistency(vcpu, gfn, level))
  3360. level = PT_DIRECTORY_LEVEL;
  3361. gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
  3362. }
  3363. if (fast_page_fault(vcpu, gpa, level, error_code))
  3364. return RET_PF_RETRY;
  3365. mmu_seq = vcpu->kvm->mmu_notifier_seq;
  3366. smp_rmb();
  3367. if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
  3368. return RET_PF_RETRY;
  3369. if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
  3370. return r;
  3371. r = RET_PF_RETRY;
  3372. spin_lock(&vcpu->kvm->mmu_lock);
  3373. if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
  3374. goto out_unlock;
  3375. if (make_mmu_pages_available(vcpu) < 0)
  3376. goto out_unlock;
  3377. if (likely(!force_pt_level))
  3378. transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
  3379. r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
  3380. prefault, lpage_disallowed);
  3381. out_unlock:
  3382. spin_unlock(&vcpu->kvm->mmu_lock);
  3383. kvm_release_pfn_clean(pfn);
  3384. return r;
  3385. }
  3386. static void nonpaging_init_context(struct kvm_vcpu *vcpu,
  3387. struct kvm_mmu *context)
  3388. {
  3389. context->page_fault = nonpaging_page_fault;
  3390. context->gva_to_gpa = nonpaging_gva_to_gpa;
  3391. context->sync_page = nonpaging_sync_page;
  3392. context->invlpg = nonpaging_invlpg;
  3393. context->update_pte = nonpaging_update_pte;
  3394. context->root_level = 0;
  3395. context->shadow_root_level = PT32E_ROOT_LEVEL;
  3396. context->root_hpa = INVALID_PAGE;
  3397. context->direct_map = true;
  3398. context->nx = false;
  3399. }
  3400. void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
  3401. {
  3402. mmu_free_roots(vcpu);
  3403. }
  3404. static unsigned long get_cr3(struct kvm_vcpu *vcpu)
  3405. {
  3406. return kvm_read_cr3(vcpu);
  3407. }
  3408. static void inject_page_fault(struct kvm_vcpu *vcpu,
  3409. struct x86_exception *fault)
  3410. {
  3411. vcpu->arch.mmu.inject_page_fault(vcpu, fault);
  3412. }
  3413. static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
  3414. unsigned access, int *nr_present)
  3415. {
  3416. if (unlikely(is_mmio_spte(*sptep))) {
  3417. if (gfn != get_mmio_spte_gfn(*sptep)) {
  3418. mmu_spte_clear_no_track(sptep);
  3419. return true;
  3420. }
  3421. (*nr_present)++;
  3422. mark_mmio_spte(vcpu, sptep, gfn, access);
  3423. return true;
  3424. }
  3425. return false;
  3426. }
  3427. static inline bool is_last_gpte(struct kvm_mmu *mmu,
  3428. unsigned level, unsigned gpte)
  3429. {
  3430. /*
  3431. * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
  3432. * If it is clear, there are no large pages at this level, so clear
  3433. * PT_PAGE_SIZE_MASK in gpte if that is the case.
  3434. */
  3435. gpte &= level - mmu->last_nonleaf_level;
  3436. /*
  3437. * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
  3438. * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
  3439. * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
  3440. */
  3441. gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
  3442. return gpte & PT_PAGE_SIZE_MASK;
  3443. }
  3444. #define PTTYPE_EPT 18 /* arbitrary */
  3445. #define PTTYPE PTTYPE_EPT
  3446. #include "paging_tmpl.h"
  3447. #undef PTTYPE
  3448. #define PTTYPE 64
  3449. #include "paging_tmpl.h"
  3450. #undef PTTYPE
  3451. #define PTTYPE 32
  3452. #include "paging_tmpl.h"
  3453. #undef PTTYPE
  3454. static void
  3455. __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
  3456. struct rsvd_bits_validate *rsvd_check,
  3457. int maxphyaddr, int level, bool nx, bool gbpages,
  3458. bool pse, bool amd)
  3459. {
  3460. u64 exb_bit_rsvd = 0;
  3461. u64 gbpages_bit_rsvd = 0;
  3462. u64 nonleaf_bit8_rsvd = 0;
  3463. rsvd_check->bad_mt_xwr = 0;
  3464. if (!nx)
  3465. exb_bit_rsvd = rsvd_bits(63, 63);
  3466. if (!gbpages)
  3467. gbpages_bit_rsvd = rsvd_bits(7, 7);
  3468. /*
  3469. * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
  3470. * leaf entries) on AMD CPUs only.
  3471. */
  3472. if (amd)
  3473. nonleaf_bit8_rsvd = rsvd_bits(8, 8);
  3474. switch (level) {
  3475. case PT32_ROOT_LEVEL:
  3476. /* no rsvd bits for 2 level 4K page table entries */
  3477. rsvd_check->rsvd_bits_mask[0][1] = 0;
  3478. rsvd_check->rsvd_bits_mask[0][0] = 0;
  3479. rsvd_check->rsvd_bits_mask[1][0] =
  3480. rsvd_check->rsvd_bits_mask[0][0];
  3481. if (!pse) {
  3482. rsvd_check->rsvd_bits_mask[1][1] = 0;
  3483. break;
  3484. }
  3485. if (is_cpuid_PSE36())
  3486. /* 36bits PSE 4MB page */
  3487. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
  3488. else
  3489. /* 32 bits PSE 4MB page */
  3490. rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
  3491. break;
  3492. case PT32E_ROOT_LEVEL:
  3493. rsvd_check->rsvd_bits_mask[0][2] =
  3494. rsvd_bits(maxphyaddr, 63) |
  3495. rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
  3496. rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
  3497. rsvd_bits(maxphyaddr, 62); /* PDE */
  3498. rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
  3499. rsvd_bits(maxphyaddr, 62); /* PTE */
  3500. rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
  3501. rsvd_bits(maxphyaddr, 62) |
  3502. rsvd_bits(13, 20); /* large page */
  3503. rsvd_check->rsvd_bits_mask[1][0] =
  3504. rsvd_check->rsvd_bits_mask[0][0];
  3505. break;
  3506. case PT64_ROOT_5LEVEL:
  3507. rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
  3508. nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
  3509. rsvd_bits(maxphyaddr, 51);
  3510. rsvd_check->rsvd_bits_mask[1][4] =
  3511. rsvd_check->rsvd_bits_mask[0][4];
  3512. case PT64_ROOT_4LEVEL:
  3513. rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
  3514. nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
  3515. rsvd_bits(maxphyaddr, 51);
  3516. rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
  3517. gbpages_bit_rsvd |
  3518. rsvd_bits(maxphyaddr, 51);
  3519. rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
  3520. rsvd_bits(maxphyaddr, 51);
  3521. rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
  3522. rsvd_bits(maxphyaddr, 51);
  3523. rsvd_check->rsvd_bits_mask[1][3] =
  3524. rsvd_check->rsvd_bits_mask[0][3];
  3525. rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
  3526. gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
  3527. rsvd_bits(13, 29);
  3528. rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
  3529. rsvd_bits(maxphyaddr, 51) |
  3530. rsvd_bits(13, 20); /* large page */
  3531. rsvd_check->rsvd_bits_mask[1][0] =
  3532. rsvd_check->rsvd_bits_mask[0][0];
  3533. break;
  3534. }
  3535. }
  3536. static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
  3537. struct kvm_mmu *context)
  3538. {
  3539. __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
  3540. cpuid_maxphyaddr(vcpu), context->root_level,
  3541. context->nx,
  3542. guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
  3543. is_pse(vcpu), guest_cpuid_is_amd(vcpu));
  3544. }
  3545. static void
  3546. __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
  3547. int maxphyaddr, bool execonly)
  3548. {
  3549. u64 bad_mt_xwr;
  3550. rsvd_check->rsvd_bits_mask[0][4] =
  3551. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
  3552. rsvd_check->rsvd_bits_mask[0][3] =
  3553. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
  3554. rsvd_check->rsvd_bits_mask[0][2] =
  3555. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
  3556. rsvd_check->rsvd_bits_mask[0][1] =
  3557. rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
  3558. rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
  3559. /* large page */
  3560. rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
  3561. rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
  3562. rsvd_check->rsvd_bits_mask[1][2] =
  3563. rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
  3564. rsvd_check->rsvd_bits_mask[1][1] =
  3565. rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
  3566. rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
  3567. bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
  3568. bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
  3569. bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
  3570. bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
  3571. bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
  3572. if (!execonly) {
  3573. /* bits 0..2 must not be 100 unless VMX capabilities allow it */
  3574. bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
  3575. }
  3576. rsvd_check->bad_mt_xwr = bad_mt_xwr;
  3577. }
  3578. static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
  3579. struct kvm_mmu *context, bool execonly)
  3580. {
  3581. __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
  3582. cpuid_maxphyaddr(vcpu), execonly);
  3583. }
  3584. /*
  3585. * the page table on host is the shadow page table for the page
  3586. * table in guest or amd nested guest, its mmu features completely
  3587. * follow the features in guest.
  3588. */
  3589. void
  3590. reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
  3591. {
  3592. bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
  3593. struct rsvd_bits_validate *shadow_zero_check;
  3594. int i;
  3595. /*
  3596. * Passing "true" to the last argument is okay; it adds a check
  3597. * on bit 8 of the SPTEs which KVM doesn't use anyway.
  3598. */
  3599. shadow_zero_check = &context->shadow_zero_check;
  3600. __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
  3601. shadow_phys_bits,
  3602. context->shadow_root_level, uses_nx,
  3603. guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
  3604. is_pse(vcpu), true);
  3605. if (!shadow_me_mask)
  3606. return;
  3607. for (i = context->shadow_root_level; --i >= 0;) {
  3608. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
  3609. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
  3610. }
  3611. }
  3612. EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
  3613. static inline bool boot_cpu_is_amd(void)
  3614. {
  3615. WARN_ON_ONCE(!tdp_enabled);
  3616. return shadow_x_mask == 0;
  3617. }
  3618. /*
  3619. * the direct page table on host, use as much mmu features as
  3620. * possible, however, kvm currently does not do execution-protection.
  3621. */
  3622. static void
  3623. reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
  3624. struct kvm_mmu *context)
  3625. {
  3626. struct rsvd_bits_validate *shadow_zero_check;
  3627. int i;
  3628. shadow_zero_check = &context->shadow_zero_check;
  3629. if (boot_cpu_is_amd())
  3630. __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
  3631. shadow_phys_bits,
  3632. context->shadow_root_level, false,
  3633. boot_cpu_has(X86_FEATURE_GBPAGES),
  3634. true, true);
  3635. else
  3636. __reset_rsvds_bits_mask_ept(shadow_zero_check,
  3637. shadow_phys_bits,
  3638. false);
  3639. if (!shadow_me_mask)
  3640. return;
  3641. for (i = context->shadow_root_level; --i >= 0;) {
  3642. shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
  3643. shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
  3644. }
  3645. }
  3646. /*
  3647. * as the comments in reset_shadow_zero_bits_mask() except it
  3648. * is the shadow page table for intel nested guest.
  3649. */
  3650. static void
  3651. reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
  3652. struct kvm_mmu *context, bool execonly)
  3653. {
  3654. __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
  3655. shadow_phys_bits, execonly);
  3656. }
  3657. #define BYTE_MASK(access) \
  3658. ((1 & (access) ? 2 : 0) | \
  3659. (2 & (access) ? 4 : 0) | \
  3660. (3 & (access) ? 8 : 0) | \
  3661. (4 & (access) ? 16 : 0) | \
  3662. (5 & (access) ? 32 : 0) | \
  3663. (6 & (access) ? 64 : 0) | \
  3664. (7 & (access) ? 128 : 0))
  3665. static void update_permission_bitmask(struct kvm_vcpu *vcpu,
  3666. struct kvm_mmu *mmu, bool ept)
  3667. {
  3668. unsigned byte;
  3669. const u8 x = BYTE_MASK(ACC_EXEC_MASK);
  3670. const u8 w = BYTE_MASK(ACC_WRITE_MASK);
  3671. const u8 u = BYTE_MASK(ACC_USER_MASK);
  3672. bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
  3673. bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
  3674. bool cr0_wp = is_write_protection(vcpu);
  3675. for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
  3676. unsigned pfec = byte << 1;
  3677. /*
  3678. * Each "*f" variable has a 1 bit for each UWX value
  3679. * that causes a fault with the given PFEC.
  3680. */
  3681. /* Faults from writes to non-writable pages */
  3682. u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
  3683. /* Faults from user mode accesses to supervisor pages */
  3684. u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
  3685. /* Faults from fetches of non-executable pages*/
  3686. u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
  3687. /* Faults from kernel mode fetches of user pages */
  3688. u8 smepf = 0;
  3689. /* Faults from kernel mode accesses of user pages */
  3690. u8 smapf = 0;
  3691. if (!ept) {
  3692. /* Faults from kernel mode accesses to user pages */
  3693. u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
  3694. /* Not really needed: !nx will cause pte.nx to fault */
  3695. if (!mmu->nx)
  3696. ff = 0;
  3697. /* Allow supervisor writes if !cr0.wp */
  3698. if (!cr0_wp)
  3699. wf = (pfec & PFERR_USER_MASK) ? wf : 0;
  3700. /* Disallow supervisor fetches of user code if cr4.smep */
  3701. if (cr4_smep)
  3702. smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
  3703. /*
  3704. * SMAP:kernel-mode data accesses from user-mode
  3705. * mappings should fault. A fault is considered
  3706. * as a SMAP violation if all of the following
  3707. * conditions are ture:
  3708. * - X86_CR4_SMAP is set in CR4
  3709. * - A user page is accessed
  3710. * - The access is not a fetch
  3711. * - Page fault in kernel mode
  3712. * - if CPL = 3 or X86_EFLAGS_AC is clear
  3713. *
  3714. * Here, we cover the first three conditions.
  3715. * The fourth is computed dynamically in permission_fault();
  3716. * PFERR_RSVD_MASK bit will be set in PFEC if the access is
  3717. * *not* subject to SMAP restrictions.
  3718. */
  3719. if (cr4_smap)
  3720. smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
  3721. }
  3722. mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
  3723. }
  3724. }
  3725. /*
  3726. * PKU is an additional mechanism by which the paging controls access to
  3727. * user-mode addresses based on the value in the PKRU register. Protection
  3728. * key violations are reported through a bit in the page fault error code.
  3729. * Unlike other bits of the error code, the PK bit is not known at the
  3730. * call site of e.g. gva_to_gpa; it must be computed directly in
  3731. * permission_fault based on two bits of PKRU, on some machine state (CR4,
  3732. * CR0, EFER, CPL), and on other bits of the error code and the page tables.
  3733. *
  3734. * In particular the following conditions come from the error code, the
  3735. * page tables and the machine state:
  3736. * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
  3737. * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
  3738. * - PK is always zero if U=0 in the page tables
  3739. * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
  3740. *
  3741. * The PKRU bitmask caches the result of these four conditions. The error
  3742. * code (minus the P bit) and the page table's U bit form an index into the
  3743. * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
  3744. * with the two bits of the PKRU register corresponding to the protection key.
  3745. * For the first three conditions above the bits will be 00, thus masking
  3746. * away both AD and WD. For all reads or if the last condition holds, WD
  3747. * only will be masked away.
  3748. */
  3749. static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  3750. bool ept)
  3751. {
  3752. unsigned bit;
  3753. bool wp;
  3754. if (ept) {
  3755. mmu->pkru_mask = 0;
  3756. return;
  3757. }
  3758. /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
  3759. if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
  3760. mmu->pkru_mask = 0;
  3761. return;
  3762. }
  3763. wp = is_write_protection(vcpu);
  3764. for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
  3765. unsigned pfec, pkey_bits;
  3766. bool check_pkey, check_write, ff, uf, wf, pte_user;
  3767. pfec = bit << 1;
  3768. ff = pfec & PFERR_FETCH_MASK;
  3769. uf = pfec & PFERR_USER_MASK;
  3770. wf = pfec & PFERR_WRITE_MASK;
  3771. /* PFEC.RSVD is replaced by ACC_USER_MASK. */
  3772. pte_user = pfec & PFERR_RSVD_MASK;
  3773. /*
  3774. * Only need to check the access which is not an
  3775. * instruction fetch and is to a user page.
  3776. */
  3777. check_pkey = (!ff && pte_user);
  3778. /*
  3779. * write access is controlled by PKRU if it is a
  3780. * user access or CR0.WP = 1.
  3781. */
  3782. check_write = check_pkey && wf && (uf || wp);
  3783. /* PKRU.AD stops both read and write access. */
  3784. pkey_bits = !!check_pkey;
  3785. /* PKRU.WD stops write access. */
  3786. pkey_bits |= (!!check_write) << 1;
  3787. mmu->pkru_mask |= (pkey_bits & 3) << pfec;
  3788. }
  3789. }
  3790. static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
  3791. {
  3792. unsigned root_level = mmu->root_level;
  3793. mmu->last_nonleaf_level = root_level;
  3794. if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
  3795. mmu->last_nonleaf_level++;
  3796. }
  3797. static void paging64_init_context_common(struct kvm_vcpu *vcpu,
  3798. struct kvm_mmu *context,
  3799. int level)
  3800. {
  3801. context->nx = is_nx(vcpu);
  3802. context->root_level = level;
  3803. reset_rsvds_bits_mask(vcpu, context);
  3804. update_permission_bitmask(vcpu, context, false);
  3805. update_pkru_bitmask(vcpu, context, false);
  3806. update_last_nonleaf_level(vcpu, context);
  3807. MMU_WARN_ON(!is_pae(vcpu));
  3808. context->page_fault = paging64_page_fault;
  3809. context->gva_to_gpa = paging64_gva_to_gpa;
  3810. context->sync_page = paging64_sync_page;
  3811. context->invlpg = paging64_invlpg;
  3812. context->update_pte = paging64_update_pte;
  3813. context->shadow_root_level = level;
  3814. context->root_hpa = INVALID_PAGE;
  3815. context->direct_map = false;
  3816. }
  3817. static void paging64_init_context(struct kvm_vcpu *vcpu,
  3818. struct kvm_mmu *context)
  3819. {
  3820. int root_level = is_la57_mode(vcpu) ?
  3821. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  3822. paging64_init_context_common(vcpu, context, root_level);
  3823. }
  3824. static void paging32_init_context(struct kvm_vcpu *vcpu,
  3825. struct kvm_mmu *context)
  3826. {
  3827. context->nx = false;
  3828. context->root_level = PT32_ROOT_LEVEL;
  3829. reset_rsvds_bits_mask(vcpu, context);
  3830. update_permission_bitmask(vcpu, context, false);
  3831. update_pkru_bitmask(vcpu, context, false);
  3832. update_last_nonleaf_level(vcpu, context);
  3833. context->page_fault = paging32_page_fault;
  3834. context->gva_to_gpa = paging32_gva_to_gpa;
  3835. context->sync_page = paging32_sync_page;
  3836. context->invlpg = paging32_invlpg;
  3837. context->update_pte = paging32_update_pte;
  3838. context->shadow_root_level = PT32E_ROOT_LEVEL;
  3839. context->root_hpa = INVALID_PAGE;
  3840. context->direct_map = false;
  3841. }
  3842. static void paging32E_init_context(struct kvm_vcpu *vcpu,
  3843. struct kvm_mmu *context)
  3844. {
  3845. paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
  3846. }
  3847. static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
  3848. {
  3849. struct kvm_mmu *context = &vcpu->arch.mmu;
  3850. context->base_role.word = 0;
  3851. context->base_role.smm = is_smm(vcpu);
  3852. context->base_role.ad_disabled = (shadow_accessed_mask == 0);
  3853. context->page_fault = tdp_page_fault;
  3854. context->sync_page = nonpaging_sync_page;
  3855. context->invlpg = nonpaging_invlpg;
  3856. context->update_pte = nonpaging_update_pte;
  3857. context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
  3858. context->root_hpa = INVALID_PAGE;
  3859. context->direct_map = true;
  3860. context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
  3861. context->get_cr3 = get_cr3;
  3862. context->get_pdptr = kvm_pdptr_read;
  3863. context->inject_page_fault = kvm_inject_page_fault;
  3864. if (!is_paging(vcpu)) {
  3865. context->nx = false;
  3866. context->gva_to_gpa = nonpaging_gva_to_gpa;
  3867. context->root_level = 0;
  3868. } else if (is_long_mode(vcpu)) {
  3869. context->nx = is_nx(vcpu);
  3870. context->root_level = is_la57_mode(vcpu) ?
  3871. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  3872. reset_rsvds_bits_mask(vcpu, context);
  3873. context->gva_to_gpa = paging64_gva_to_gpa;
  3874. } else if (is_pae(vcpu)) {
  3875. context->nx = is_nx(vcpu);
  3876. context->root_level = PT32E_ROOT_LEVEL;
  3877. reset_rsvds_bits_mask(vcpu, context);
  3878. context->gva_to_gpa = paging64_gva_to_gpa;
  3879. } else {
  3880. context->nx = false;
  3881. context->root_level = PT32_ROOT_LEVEL;
  3882. reset_rsvds_bits_mask(vcpu, context);
  3883. context->gva_to_gpa = paging32_gva_to_gpa;
  3884. }
  3885. update_permission_bitmask(vcpu, context, false);
  3886. update_pkru_bitmask(vcpu, context, false);
  3887. update_last_nonleaf_level(vcpu, context);
  3888. reset_tdp_shadow_zero_bits_mask(vcpu, context);
  3889. }
  3890. void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
  3891. {
  3892. bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
  3893. bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
  3894. struct kvm_mmu *context = &vcpu->arch.mmu;
  3895. MMU_WARN_ON(VALID_PAGE(context->root_hpa));
  3896. if (!is_paging(vcpu))
  3897. nonpaging_init_context(vcpu, context);
  3898. else if (is_long_mode(vcpu))
  3899. paging64_init_context(vcpu, context);
  3900. else if (is_pae(vcpu))
  3901. paging32E_init_context(vcpu, context);
  3902. else
  3903. paging32_init_context(vcpu, context);
  3904. context->base_role.nxe = is_nx(vcpu);
  3905. context->base_role.cr4_pae = !!is_pae(vcpu);
  3906. context->base_role.cr0_wp = is_write_protection(vcpu);
  3907. context->base_role.smep_andnot_wp
  3908. = smep && !is_write_protection(vcpu);
  3909. context->base_role.smap_andnot_wp
  3910. = smap && !is_write_protection(vcpu);
  3911. context->base_role.smm = is_smm(vcpu);
  3912. reset_shadow_zero_bits_mask(vcpu, context);
  3913. }
  3914. EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
  3915. void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
  3916. bool accessed_dirty)
  3917. {
  3918. struct kvm_mmu *context = &vcpu->arch.mmu;
  3919. MMU_WARN_ON(VALID_PAGE(context->root_hpa));
  3920. context->shadow_root_level = PT64_ROOT_4LEVEL;
  3921. context->nx = true;
  3922. context->ept_ad = accessed_dirty;
  3923. context->page_fault = ept_page_fault;
  3924. context->gva_to_gpa = ept_gva_to_gpa;
  3925. context->sync_page = ept_sync_page;
  3926. context->invlpg = ept_invlpg;
  3927. context->update_pte = ept_update_pte;
  3928. context->root_level = PT64_ROOT_4LEVEL;
  3929. context->root_hpa = INVALID_PAGE;
  3930. context->direct_map = false;
  3931. context->base_role.ad_disabled = !accessed_dirty;
  3932. update_permission_bitmask(vcpu, context, true);
  3933. update_pkru_bitmask(vcpu, context, true);
  3934. update_last_nonleaf_level(vcpu, context);
  3935. reset_rsvds_bits_mask_ept(vcpu, context, execonly);
  3936. reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
  3937. }
  3938. EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
  3939. static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
  3940. {
  3941. struct kvm_mmu *context = &vcpu->arch.mmu;
  3942. kvm_init_shadow_mmu(vcpu);
  3943. context->set_cr3 = kvm_x86_ops->set_cr3;
  3944. context->get_cr3 = get_cr3;
  3945. context->get_pdptr = kvm_pdptr_read;
  3946. context->inject_page_fault = kvm_inject_page_fault;
  3947. }
  3948. static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
  3949. {
  3950. struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
  3951. g_context->get_cr3 = get_cr3;
  3952. g_context->get_pdptr = kvm_pdptr_read;
  3953. g_context->inject_page_fault = kvm_inject_page_fault;
  3954. /*
  3955. * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
  3956. * L1's nested page tables (e.g. EPT12). The nested translation
  3957. * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
  3958. * L2's page tables as the first level of translation and L1's
  3959. * nested page tables as the second level of translation. Basically
  3960. * the gva_to_gpa functions between mmu and nested_mmu are swapped.
  3961. */
  3962. if (!is_paging(vcpu)) {
  3963. g_context->nx = false;
  3964. g_context->root_level = 0;
  3965. g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
  3966. } else if (is_long_mode(vcpu)) {
  3967. g_context->nx = is_nx(vcpu);
  3968. g_context->root_level = is_la57_mode(vcpu) ?
  3969. PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
  3970. reset_rsvds_bits_mask(vcpu, g_context);
  3971. g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
  3972. } else if (is_pae(vcpu)) {
  3973. g_context->nx = is_nx(vcpu);
  3974. g_context->root_level = PT32E_ROOT_LEVEL;
  3975. reset_rsvds_bits_mask(vcpu, g_context);
  3976. g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
  3977. } else {
  3978. g_context->nx = false;
  3979. g_context->root_level = PT32_ROOT_LEVEL;
  3980. reset_rsvds_bits_mask(vcpu, g_context);
  3981. g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
  3982. }
  3983. update_permission_bitmask(vcpu, g_context, false);
  3984. update_pkru_bitmask(vcpu, g_context, false);
  3985. update_last_nonleaf_level(vcpu, g_context);
  3986. }
  3987. static void init_kvm_mmu(struct kvm_vcpu *vcpu)
  3988. {
  3989. if (mmu_is_nested(vcpu))
  3990. init_kvm_nested_mmu(vcpu);
  3991. else if (tdp_enabled)
  3992. init_kvm_tdp_mmu(vcpu);
  3993. else
  3994. init_kvm_softmmu(vcpu);
  3995. }
  3996. void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
  3997. {
  3998. kvm_mmu_unload(vcpu);
  3999. init_kvm_mmu(vcpu);
  4000. }
  4001. EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
  4002. int kvm_mmu_load(struct kvm_vcpu *vcpu)
  4003. {
  4004. int r;
  4005. r = mmu_topup_memory_caches(vcpu);
  4006. if (r)
  4007. goto out;
  4008. r = mmu_alloc_roots(vcpu);
  4009. kvm_mmu_sync_roots(vcpu);
  4010. if (r)
  4011. goto out;
  4012. /* set_cr3() should ensure TLB has been flushed */
  4013. vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
  4014. out:
  4015. return r;
  4016. }
  4017. EXPORT_SYMBOL_GPL(kvm_mmu_load);
  4018. void kvm_mmu_unload(struct kvm_vcpu *vcpu)
  4019. {
  4020. mmu_free_roots(vcpu);
  4021. WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
  4022. }
  4023. EXPORT_SYMBOL_GPL(kvm_mmu_unload);
  4024. static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
  4025. struct kvm_mmu_page *sp, u64 *spte,
  4026. const void *new)
  4027. {
  4028. if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
  4029. ++vcpu->kvm->stat.mmu_pde_zapped;
  4030. return;
  4031. }
  4032. ++vcpu->kvm->stat.mmu_pte_updated;
  4033. vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
  4034. }
  4035. static bool need_remote_flush(u64 old, u64 new)
  4036. {
  4037. if (!is_shadow_present_pte(old))
  4038. return false;
  4039. if (!is_shadow_present_pte(new))
  4040. return true;
  4041. if ((old ^ new) & PT64_BASE_ADDR_MASK)
  4042. return true;
  4043. old ^= shadow_nx_mask;
  4044. new ^= shadow_nx_mask;
  4045. return (old & ~new & PT64_PERM_MASK) != 0;
  4046. }
  4047. static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
  4048. int *bytes)
  4049. {
  4050. u64 gentry = 0;
  4051. int r;
  4052. /*
  4053. * Assume that the pte write on a page table of the same type
  4054. * as the current vcpu paging mode since we update the sptes only
  4055. * when they have the same mode.
  4056. */
  4057. if (is_pae(vcpu) && *bytes == 4) {
  4058. /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
  4059. *gpa &= ~(gpa_t)7;
  4060. *bytes = 8;
  4061. }
  4062. if (*bytes == 4 || *bytes == 8) {
  4063. r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
  4064. if (r)
  4065. gentry = 0;
  4066. }
  4067. return gentry;
  4068. }
  4069. /*
  4070. * If we're seeing too many writes to a page, it may no longer be a page table,
  4071. * or we may be forking, in which case it is better to unmap the page.
  4072. */
  4073. static bool detect_write_flooding(struct kvm_mmu_page *sp)
  4074. {
  4075. /*
  4076. * Skip write-flooding detected for the sp whose level is 1, because
  4077. * it can become unsync, then the guest page is not write-protected.
  4078. */
  4079. if (sp->role.level == PT_PAGE_TABLE_LEVEL)
  4080. return false;
  4081. atomic_inc(&sp->write_flooding_count);
  4082. return atomic_read(&sp->write_flooding_count) >= 3;
  4083. }
  4084. /*
  4085. * Misaligned accesses are too much trouble to fix up; also, they usually
  4086. * indicate a page is not used as a page table.
  4087. */
  4088. static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
  4089. int bytes)
  4090. {
  4091. unsigned offset, pte_size, misaligned;
  4092. pgprintk("misaligned: gpa %llx bytes %d role %x\n",
  4093. gpa, bytes, sp->role.word);
  4094. offset = offset_in_page(gpa);
  4095. pte_size = sp->role.cr4_pae ? 8 : 4;
  4096. /*
  4097. * Sometimes, the OS only writes the last one bytes to update status
  4098. * bits, for example, in linux, andb instruction is used in clear_bit().
  4099. */
  4100. if (!(offset & (pte_size - 1)) && bytes == 1)
  4101. return false;
  4102. misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
  4103. misaligned |= bytes < 4;
  4104. return misaligned;
  4105. }
  4106. static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
  4107. {
  4108. unsigned page_offset, quadrant;
  4109. u64 *spte;
  4110. int level;
  4111. page_offset = offset_in_page(gpa);
  4112. level = sp->role.level;
  4113. *nspte = 1;
  4114. if (!sp->role.cr4_pae) {
  4115. page_offset <<= 1; /* 32->64 */
  4116. /*
  4117. * A 32-bit pde maps 4MB while the shadow pdes map
  4118. * only 2MB. So we need to double the offset again
  4119. * and zap two pdes instead of one.
  4120. */
  4121. if (level == PT32_ROOT_LEVEL) {
  4122. page_offset &= ~7; /* kill rounding error */
  4123. page_offset <<= 1;
  4124. *nspte = 2;
  4125. }
  4126. quadrant = page_offset >> PAGE_SHIFT;
  4127. page_offset &= ~PAGE_MASK;
  4128. if (quadrant != sp->role.quadrant)
  4129. return NULL;
  4130. }
  4131. spte = &sp->spt[page_offset / sizeof(*spte)];
  4132. return spte;
  4133. }
  4134. static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
  4135. const u8 *new, int bytes,
  4136. struct kvm_page_track_notifier_node *node)
  4137. {
  4138. gfn_t gfn = gpa >> PAGE_SHIFT;
  4139. struct kvm_mmu_page *sp;
  4140. LIST_HEAD(invalid_list);
  4141. u64 entry, gentry, *spte;
  4142. int npte;
  4143. bool remote_flush, local_flush;
  4144. union kvm_mmu_page_role mask = { };
  4145. mask.cr0_wp = 1;
  4146. mask.cr4_pae = 1;
  4147. mask.nxe = 1;
  4148. mask.smep_andnot_wp = 1;
  4149. mask.smap_andnot_wp = 1;
  4150. mask.smm = 1;
  4151. mask.ad_disabled = 1;
  4152. /*
  4153. * If we don't have indirect shadow pages, it means no page is
  4154. * write-protected, so we can exit simply.
  4155. */
  4156. if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
  4157. return;
  4158. remote_flush = local_flush = false;
  4159. pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
  4160. /*
  4161. * No need to care whether allocation memory is successful
  4162. * or not since pte prefetch is skiped if it does not have
  4163. * enough objects in the cache.
  4164. */
  4165. mmu_topup_memory_caches(vcpu);
  4166. spin_lock(&vcpu->kvm->mmu_lock);
  4167. gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
  4168. ++vcpu->kvm->stat.mmu_pte_write;
  4169. kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
  4170. for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
  4171. if (detect_write_misaligned(sp, gpa, bytes) ||
  4172. detect_write_flooding(sp)) {
  4173. kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
  4174. ++vcpu->kvm->stat.mmu_flooded;
  4175. continue;
  4176. }
  4177. spte = get_written_sptes(sp, gpa, &npte);
  4178. if (!spte)
  4179. continue;
  4180. local_flush = true;
  4181. while (npte--) {
  4182. entry = *spte;
  4183. mmu_page_zap_pte(vcpu->kvm, sp, spte);
  4184. if (gentry &&
  4185. !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
  4186. & mask.word) && rmap_can_add(vcpu))
  4187. mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
  4188. if (need_remote_flush(entry, *spte))
  4189. remote_flush = true;
  4190. ++spte;
  4191. }
  4192. }
  4193. kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
  4194. kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
  4195. spin_unlock(&vcpu->kvm->mmu_lock);
  4196. }
  4197. int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
  4198. {
  4199. gpa_t gpa;
  4200. int r;
  4201. if (vcpu->arch.mmu.direct_map)
  4202. return 0;
  4203. gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
  4204. r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
  4205. return r;
  4206. }
  4207. EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
  4208. static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
  4209. {
  4210. LIST_HEAD(invalid_list);
  4211. if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
  4212. return 0;
  4213. while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
  4214. if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
  4215. break;
  4216. ++vcpu->kvm->stat.mmu_recycled;
  4217. }
  4218. kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
  4219. if (!kvm_mmu_available_pages(vcpu->kvm))
  4220. return -ENOSPC;
  4221. return 0;
  4222. }
  4223. int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
  4224. void *insn, int insn_len)
  4225. {
  4226. int r, emulation_type = EMULTYPE_RETRY;
  4227. enum emulation_result er;
  4228. bool direct = vcpu->arch.mmu.direct_map;
  4229. /* With shadow page tables, fault_address contains a GVA or nGPA. */
  4230. if (vcpu->arch.mmu.direct_map) {
  4231. vcpu->arch.gpa_available = true;
  4232. vcpu->arch.gpa_val = cr2;
  4233. }
  4234. r = RET_PF_INVALID;
  4235. if (unlikely(error_code & PFERR_RSVD_MASK)) {
  4236. r = handle_mmio_page_fault(vcpu, cr2, direct);
  4237. if (r == RET_PF_EMULATE) {
  4238. emulation_type = 0;
  4239. goto emulate;
  4240. }
  4241. }
  4242. if (r == RET_PF_INVALID) {
  4243. r = vcpu->arch.mmu.page_fault(vcpu, cr2, lower_32_bits(error_code),
  4244. false);
  4245. WARN_ON(r == RET_PF_INVALID);
  4246. }
  4247. if (r == RET_PF_RETRY)
  4248. return 1;
  4249. if (r < 0)
  4250. return r;
  4251. /*
  4252. * Before emulating the instruction, check if the error code
  4253. * was due to a RO violation while translating the guest page.
  4254. * This can occur when using nested virtualization with nested
  4255. * paging in both guests. If true, we simply unprotect the page
  4256. * and resume the guest.
  4257. */
  4258. if (vcpu->arch.mmu.direct_map &&
  4259. (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
  4260. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
  4261. return 1;
  4262. }
  4263. if (mmio_info_in_cache(vcpu, cr2, direct))
  4264. emulation_type = 0;
  4265. emulate:
  4266. er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
  4267. switch (er) {
  4268. case EMULATE_DONE:
  4269. return 1;
  4270. case EMULATE_USER_EXIT:
  4271. ++vcpu->stat.mmio_exits;
  4272. /* fall through */
  4273. case EMULATE_FAIL:
  4274. return 0;
  4275. default:
  4276. BUG();
  4277. }
  4278. }
  4279. EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
  4280. void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
  4281. {
  4282. vcpu->arch.mmu.invlpg(vcpu, gva);
  4283. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  4284. ++vcpu->stat.invlpg;
  4285. }
  4286. EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
  4287. void kvm_enable_tdp(void)
  4288. {
  4289. tdp_enabled = true;
  4290. }
  4291. EXPORT_SYMBOL_GPL(kvm_enable_tdp);
  4292. void kvm_disable_tdp(void)
  4293. {
  4294. tdp_enabled = false;
  4295. }
  4296. EXPORT_SYMBOL_GPL(kvm_disable_tdp);
  4297. static void free_mmu_pages(struct kvm_vcpu *vcpu)
  4298. {
  4299. free_page((unsigned long)vcpu->arch.mmu.pae_root);
  4300. if (vcpu->arch.mmu.lm_root != NULL)
  4301. free_page((unsigned long)vcpu->arch.mmu.lm_root);
  4302. }
  4303. static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
  4304. {
  4305. struct page *page;
  4306. int i;
  4307. /*
  4308. * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
  4309. * Therefore we need to allocate shadow page tables in the first
  4310. * 4GB of memory, which happens to fit the DMA32 zone.
  4311. */
  4312. page = alloc_page(GFP_KERNEL | __GFP_DMA32);
  4313. if (!page)
  4314. return -ENOMEM;
  4315. vcpu->arch.mmu.pae_root = page_address(page);
  4316. for (i = 0; i < 4; ++i)
  4317. vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
  4318. return 0;
  4319. }
  4320. int kvm_mmu_create(struct kvm_vcpu *vcpu)
  4321. {
  4322. vcpu->arch.walk_mmu = &vcpu->arch.mmu;
  4323. vcpu->arch.mmu.root_hpa = INVALID_PAGE;
  4324. vcpu->arch.mmu.translate_gpa = translate_gpa;
  4325. vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
  4326. return alloc_mmu_pages(vcpu);
  4327. }
  4328. void kvm_mmu_setup(struct kvm_vcpu *vcpu)
  4329. {
  4330. MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
  4331. init_kvm_mmu(vcpu);
  4332. }
  4333. static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
  4334. struct kvm_memory_slot *slot,
  4335. struct kvm_page_track_notifier_node *node)
  4336. {
  4337. kvm_mmu_invalidate_zap_all_pages(kvm);
  4338. }
  4339. void kvm_mmu_init_vm(struct kvm *kvm)
  4340. {
  4341. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  4342. node->track_write = kvm_mmu_pte_write;
  4343. node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
  4344. kvm_page_track_register_notifier(kvm, node);
  4345. }
  4346. void kvm_mmu_uninit_vm(struct kvm *kvm)
  4347. {
  4348. struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
  4349. kvm_page_track_unregister_notifier(kvm, node);
  4350. }
  4351. /* The return value indicates if tlb flush on all vcpus is needed. */
  4352. typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
  4353. /* The caller should hold mmu-lock before calling this function. */
  4354. static __always_inline bool
  4355. slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4356. slot_level_handler fn, int start_level, int end_level,
  4357. gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
  4358. {
  4359. struct slot_rmap_walk_iterator iterator;
  4360. bool flush = false;
  4361. for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
  4362. end_gfn, &iterator) {
  4363. if (iterator.rmap)
  4364. flush |= fn(kvm, iterator.rmap);
  4365. if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
  4366. if (flush && lock_flush_tlb) {
  4367. kvm_flush_remote_tlbs(kvm);
  4368. flush = false;
  4369. }
  4370. cond_resched_lock(&kvm->mmu_lock);
  4371. }
  4372. }
  4373. if (flush && lock_flush_tlb) {
  4374. kvm_flush_remote_tlbs(kvm);
  4375. flush = false;
  4376. }
  4377. return flush;
  4378. }
  4379. static __always_inline bool
  4380. slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4381. slot_level_handler fn, int start_level, int end_level,
  4382. bool lock_flush_tlb)
  4383. {
  4384. return slot_handle_level_range(kvm, memslot, fn, start_level,
  4385. end_level, memslot->base_gfn,
  4386. memslot->base_gfn + memslot->npages - 1,
  4387. lock_flush_tlb);
  4388. }
  4389. static __always_inline bool
  4390. slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4391. slot_level_handler fn, bool lock_flush_tlb)
  4392. {
  4393. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
  4394. PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
  4395. }
  4396. static __always_inline bool
  4397. slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4398. slot_level_handler fn, bool lock_flush_tlb)
  4399. {
  4400. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
  4401. PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
  4402. }
  4403. static __always_inline bool
  4404. slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
  4405. slot_level_handler fn, bool lock_flush_tlb)
  4406. {
  4407. return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
  4408. PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
  4409. }
  4410. void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
  4411. {
  4412. struct kvm_memslots *slots;
  4413. struct kvm_memory_slot *memslot;
  4414. int i;
  4415. spin_lock(&kvm->mmu_lock);
  4416. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  4417. slots = __kvm_memslots(kvm, i);
  4418. kvm_for_each_memslot(memslot, slots) {
  4419. gfn_t start, end;
  4420. start = max(gfn_start, memslot->base_gfn);
  4421. end = min(gfn_end, memslot->base_gfn + memslot->npages);
  4422. if (start >= end)
  4423. continue;
  4424. slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
  4425. PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
  4426. start, end - 1, true);
  4427. }
  4428. }
  4429. spin_unlock(&kvm->mmu_lock);
  4430. }
  4431. static bool slot_rmap_write_protect(struct kvm *kvm,
  4432. struct kvm_rmap_head *rmap_head)
  4433. {
  4434. return __rmap_write_protect(kvm, rmap_head, false);
  4435. }
  4436. void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
  4437. struct kvm_memory_slot *memslot)
  4438. {
  4439. bool flush;
  4440. spin_lock(&kvm->mmu_lock);
  4441. flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
  4442. false);
  4443. spin_unlock(&kvm->mmu_lock);
  4444. /*
  4445. * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
  4446. * which do tlb flush out of mmu-lock should be serialized by
  4447. * kvm->slots_lock otherwise tlb flush would be missed.
  4448. */
  4449. lockdep_assert_held(&kvm->slots_lock);
  4450. /*
  4451. * We can flush all the TLBs out of the mmu lock without TLB
  4452. * corruption since we just change the spte from writable to
  4453. * readonly so that we only need to care the case of changing
  4454. * spte from present to present (changing the spte from present
  4455. * to nonpresent will flush all the TLBs immediately), in other
  4456. * words, the only case we care is mmu_spte_update() where we
  4457. * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
  4458. * instead of PT_WRITABLE_MASK, that means it does not depend
  4459. * on PT_WRITABLE_MASK anymore.
  4460. */
  4461. if (flush)
  4462. kvm_flush_remote_tlbs(kvm);
  4463. }
  4464. static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
  4465. struct kvm_rmap_head *rmap_head)
  4466. {
  4467. u64 *sptep;
  4468. struct rmap_iterator iter;
  4469. int need_tlb_flush = 0;
  4470. kvm_pfn_t pfn;
  4471. struct kvm_mmu_page *sp;
  4472. restart:
  4473. for_each_rmap_spte(rmap_head, &iter, sptep) {
  4474. sp = page_header(__pa(sptep));
  4475. pfn = spte_to_pfn(*sptep);
  4476. /*
  4477. * We cannot do huge page mapping for indirect shadow pages,
  4478. * which are found on the last rmap (level = 1) when not using
  4479. * tdp; such shadow pages are synced with the page table in
  4480. * the guest, and the guest page table is using 4K page size
  4481. * mapping if the indirect sp has level = 1.
  4482. */
  4483. if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
  4484. !kvm_is_zone_device_pfn(pfn) &&
  4485. PageTransCompoundMap(pfn_to_page(pfn))) {
  4486. drop_spte(kvm, sptep);
  4487. need_tlb_flush = 1;
  4488. goto restart;
  4489. }
  4490. }
  4491. return need_tlb_flush;
  4492. }
  4493. void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
  4494. const struct kvm_memory_slot *memslot)
  4495. {
  4496. /* FIXME: const-ify all uses of struct kvm_memory_slot. */
  4497. spin_lock(&kvm->mmu_lock);
  4498. slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
  4499. kvm_mmu_zap_collapsible_spte, true);
  4500. spin_unlock(&kvm->mmu_lock);
  4501. }
  4502. void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
  4503. struct kvm_memory_slot *memslot)
  4504. {
  4505. bool flush;
  4506. spin_lock(&kvm->mmu_lock);
  4507. flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
  4508. spin_unlock(&kvm->mmu_lock);
  4509. lockdep_assert_held(&kvm->slots_lock);
  4510. /*
  4511. * It's also safe to flush TLBs out of mmu lock here as currently this
  4512. * function is only used for dirty logging, in which case flushing TLB
  4513. * out of mmu lock also guarantees no dirty pages will be lost in
  4514. * dirty_bitmap.
  4515. */
  4516. if (flush)
  4517. kvm_flush_remote_tlbs(kvm);
  4518. }
  4519. EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
  4520. void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
  4521. struct kvm_memory_slot *memslot)
  4522. {
  4523. bool flush;
  4524. spin_lock(&kvm->mmu_lock);
  4525. flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
  4526. false);
  4527. spin_unlock(&kvm->mmu_lock);
  4528. /* see kvm_mmu_slot_remove_write_access */
  4529. lockdep_assert_held(&kvm->slots_lock);
  4530. if (flush)
  4531. kvm_flush_remote_tlbs(kvm);
  4532. }
  4533. EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
  4534. void kvm_mmu_slot_set_dirty(struct kvm *kvm,
  4535. struct kvm_memory_slot *memslot)
  4536. {
  4537. bool flush;
  4538. spin_lock(&kvm->mmu_lock);
  4539. flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
  4540. spin_unlock(&kvm->mmu_lock);
  4541. lockdep_assert_held(&kvm->slots_lock);
  4542. /* see kvm_mmu_slot_leaf_clear_dirty */
  4543. if (flush)
  4544. kvm_flush_remote_tlbs(kvm);
  4545. }
  4546. EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
  4547. #define BATCH_ZAP_PAGES 10
  4548. static void kvm_zap_obsolete_pages(struct kvm *kvm)
  4549. {
  4550. struct kvm_mmu_page *sp, *node;
  4551. int batch = 0;
  4552. restart:
  4553. list_for_each_entry_safe_reverse(sp, node,
  4554. &kvm->arch.active_mmu_pages, link) {
  4555. int ret;
  4556. /*
  4557. * No obsolete page exists before new created page since
  4558. * active_mmu_pages is the FIFO list.
  4559. */
  4560. if (!is_obsolete_sp(kvm, sp))
  4561. break;
  4562. /*
  4563. * Since we are reversely walking the list and the invalid
  4564. * list will be moved to the head, skip the invalid page
  4565. * can help us to avoid the infinity list walking.
  4566. */
  4567. if (sp->role.invalid)
  4568. continue;
  4569. /*
  4570. * Need not flush tlb since we only zap the sp with invalid
  4571. * generation number.
  4572. */
  4573. if (batch >= BATCH_ZAP_PAGES &&
  4574. cond_resched_lock(&kvm->mmu_lock)) {
  4575. batch = 0;
  4576. goto restart;
  4577. }
  4578. ret = kvm_mmu_prepare_zap_page(kvm, sp,
  4579. &kvm->arch.zapped_obsolete_pages);
  4580. batch += ret;
  4581. if (ret)
  4582. goto restart;
  4583. }
  4584. /*
  4585. * Should flush tlb before free page tables since lockless-walking
  4586. * may use the pages.
  4587. */
  4588. kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
  4589. }
  4590. /*
  4591. * Fast invalidate all shadow pages and use lock-break technique
  4592. * to zap obsolete pages.
  4593. *
  4594. * It's required when memslot is being deleted or VM is being
  4595. * destroyed, in these cases, we should ensure that KVM MMU does
  4596. * not use any resource of the being-deleted slot or all slots
  4597. * after calling the function.
  4598. */
  4599. void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
  4600. {
  4601. spin_lock(&kvm->mmu_lock);
  4602. trace_kvm_mmu_invalidate_zap_all_pages(kvm);
  4603. kvm->arch.mmu_valid_gen++;
  4604. /*
  4605. * Notify all vcpus to reload its shadow page table
  4606. * and flush TLB. Then all vcpus will switch to new
  4607. * shadow page table with the new mmu_valid_gen.
  4608. *
  4609. * Note: we should do this under the protection of
  4610. * mmu-lock, otherwise, vcpu would purge shadow page
  4611. * but miss tlb flush.
  4612. */
  4613. kvm_reload_remote_mmus(kvm);
  4614. kvm_zap_obsolete_pages(kvm);
  4615. spin_unlock(&kvm->mmu_lock);
  4616. }
  4617. static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
  4618. {
  4619. return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
  4620. }
  4621. void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
  4622. {
  4623. gen &= MMIO_GEN_MASK;
  4624. /*
  4625. * Shift to eliminate the "update in-progress" flag, which isn't
  4626. * included in the spte's generation number.
  4627. */
  4628. gen >>= 1;
  4629. /*
  4630. * Generation numbers are incremented in multiples of the number of
  4631. * address spaces in order to provide unique generations across all
  4632. * address spaces. Strip what is effectively the address space
  4633. * modifier prior to checking for a wrap of the MMIO generation so
  4634. * that a wrap in any address space is detected.
  4635. */
  4636. gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
  4637. /*
  4638. * The very rare case: if the MMIO generation number has wrapped,
  4639. * zap all shadow pages.
  4640. */
  4641. if (unlikely(gen == 0)) {
  4642. kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
  4643. kvm_mmu_invalidate_zap_all_pages(kvm);
  4644. }
  4645. }
  4646. static unsigned long
  4647. mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  4648. {
  4649. struct kvm *kvm;
  4650. int nr_to_scan = sc->nr_to_scan;
  4651. unsigned long freed = 0;
  4652. mutex_lock(&kvm_lock);
  4653. list_for_each_entry(kvm, &vm_list, vm_list) {
  4654. int idx;
  4655. LIST_HEAD(invalid_list);
  4656. /*
  4657. * Never scan more than sc->nr_to_scan VM instances.
  4658. * Will not hit this condition practically since we do not try
  4659. * to shrink more than one VM and it is very unlikely to see
  4660. * !n_used_mmu_pages so many times.
  4661. */
  4662. if (!nr_to_scan--)
  4663. break;
  4664. /*
  4665. * n_used_mmu_pages is accessed without holding kvm->mmu_lock
  4666. * here. We may skip a VM instance errorneosly, but we do not
  4667. * want to shrink a VM that only started to populate its MMU
  4668. * anyway.
  4669. */
  4670. if (!kvm->arch.n_used_mmu_pages &&
  4671. !kvm_has_zapped_obsolete_pages(kvm))
  4672. continue;
  4673. idx = srcu_read_lock(&kvm->srcu);
  4674. spin_lock(&kvm->mmu_lock);
  4675. if (kvm_has_zapped_obsolete_pages(kvm)) {
  4676. kvm_mmu_commit_zap_page(kvm,
  4677. &kvm->arch.zapped_obsolete_pages);
  4678. goto unlock;
  4679. }
  4680. if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
  4681. freed++;
  4682. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  4683. unlock:
  4684. spin_unlock(&kvm->mmu_lock);
  4685. srcu_read_unlock(&kvm->srcu, idx);
  4686. /*
  4687. * unfair on small ones
  4688. * per-vm shrinkers cry out
  4689. * sadness comes quickly
  4690. */
  4691. list_move_tail(&kvm->vm_list, &vm_list);
  4692. break;
  4693. }
  4694. mutex_unlock(&kvm_lock);
  4695. return freed;
  4696. }
  4697. static unsigned long
  4698. mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  4699. {
  4700. return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
  4701. }
  4702. static struct shrinker mmu_shrinker = {
  4703. .count_objects = mmu_shrink_count,
  4704. .scan_objects = mmu_shrink_scan,
  4705. .seeks = DEFAULT_SEEKS * 10,
  4706. };
  4707. static void mmu_destroy_caches(void)
  4708. {
  4709. if (pte_list_desc_cache)
  4710. kmem_cache_destroy(pte_list_desc_cache);
  4711. if (mmu_page_header_cache)
  4712. kmem_cache_destroy(mmu_page_header_cache);
  4713. }
  4714. static bool get_nx_auto_mode(void)
  4715. {
  4716. /* Return true when CPU has the bug, and mitigations are ON */
  4717. return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
  4718. }
  4719. static void __set_nx_huge_pages(bool val)
  4720. {
  4721. nx_huge_pages = itlb_multihit_kvm_mitigation = val;
  4722. }
  4723. static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
  4724. {
  4725. bool old_val = nx_huge_pages;
  4726. bool new_val;
  4727. /* In "auto" mode deploy workaround only if CPU has the bug. */
  4728. if (sysfs_streq(val, "off"))
  4729. new_val = 0;
  4730. else if (sysfs_streq(val, "force"))
  4731. new_val = 1;
  4732. else if (sysfs_streq(val, "auto"))
  4733. new_val = get_nx_auto_mode();
  4734. else if (strtobool(val, &new_val) < 0)
  4735. return -EINVAL;
  4736. __set_nx_huge_pages(new_val);
  4737. if (new_val != old_val) {
  4738. struct kvm *kvm;
  4739. int idx;
  4740. mutex_lock(&kvm_lock);
  4741. list_for_each_entry(kvm, &vm_list, vm_list) {
  4742. idx = srcu_read_lock(&kvm->srcu);
  4743. kvm_mmu_invalidate_zap_all_pages(kvm);
  4744. srcu_read_unlock(&kvm->srcu, idx);
  4745. wake_up_process(kvm->arch.nx_lpage_recovery_thread);
  4746. }
  4747. mutex_unlock(&kvm_lock);
  4748. }
  4749. return 0;
  4750. }
  4751. static void kvm_set_mmio_spte_mask(void)
  4752. {
  4753. u64 mask;
  4754. /*
  4755. * Set a reserved PA bit in MMIO SPTEs to generate page faults with
  4756. * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
  4757. * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
  4758. * 52-bit physical addresses then there are no reserved PA bits in the
  4759. * PTEs and so the reserved PA approach must be disabled.
  4760. */
  4761. if (shadow_phys_bits < 52)
  4762. mask = BIT_ULL(51) | PT_PRESENT_MASK;
  4763. else
  4764. mask = 0;
  4765. kvm_mmu_set_mmio_spte_mask(mask, mask);
  4766. }
  4767. int kvm_mmu_module_init(void)
  4768. {
  4769. if (nx_huge_pages == -1)
  4770. __set_nx_huge_pages(get_nx_auto_mode());
  4771. kvm_mmu_reset_all_pte_masks();
  4772. kvm_set_mmio_spte_mask();
  4773. pte_list_desc_cache = kmem_cache_create("pte_list_desc",
  4774. sizeof(struct pte_list_desc),
  4775. 0, SLAB_ACCOUNT, NULL);
  4776. if (!pte_list_desc_cache)
  4777. goto nomem;
  4778. mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
  4779. sizeof(struct kvm_mmu_page),
  4780. 0, SLAB_ACCOUNT, NULL);
  4781. if (!mmu_page_header_cache)
  4782. goto nomem;
  4783. if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
  4784. goto nomem;
  4785. register_shrinker(&mmu_shrinker);
  4786. return 0;
  4787. nomem:
  4788. mmu_destroy_caches();
  4789. return -ENOMEM;
  4790. }
  4791. /*
  4792. * Caculate mmu pages needed for kvm.
  4793. */
  4794. unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
  4795. {
  4796. unsigned int nr_mmu_pages;
  4797. unsigned int nr_pages = 0;
  4798. struct kvm_memslots *slots;
  4799. struct kvm_memory_slot *memslot;
  4800. int i;
  4801. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  4802. slots = __kvm_memslots(kvm, i);
  4803. kvm_for_each_memslot(memslot, slots)
  4804. nr_pages += memslot->npages;
  4805. }
  4806. nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
  4807. nr_mmu_pages = max(nr_mmu_pages,
  4808. (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
  4809. return nr_mmu_pages;
  4810. }
  4811. void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
  4812. {
  4813. kvm_mmu_unload(vcpu);
  4814. free_mmu_pages(vcpu);
  4815. mmu_free_memory_caches(vcpu);
  4816. }
  4817. void kvm_mmu_module_exit(void)
  4818. {
  4819. mmu_destroy_caches();
  4820. percpu_counter_destroy(&kvm_total_used_mmu_pages);
  4821. unregister_shrinker(&mmu_shrinker);
  4822. mmu_audit_disable();
  4823. }
  4824. static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
  4825. {
  4826. unsigned int old_val;
  4827. int err;
  4828. old_val = nx_huge_pages_recovery_ratio;
  4829. err = param_set_uint(val, kp);
  4830. if (err)
  4831. return err;
  4832. if (READ_ONCE(nx_huge_pages) &&
  4833. !old_val && nx_huge_pages_recovery_ratio) {
  4834. struct kvm *kvm;
  4835. mutex_lock(&kvm_lock);
  4836. list_for_each_entry(kvm, &vm_list, vm_list)
  4837. wake_up_process(kvm->arch.nx_lpage_recovery_thread);
  4838. mutex_unlock(&kvm_lock);
  4839. }
  4840. return err;
  4841. }
  4842. static void kvm_recover_nx_lpages(struct kvm *kvm)
  4843. {
  4844. int rcu_idx;
  4845. struct kvm_mmu_page *sp;
  4846. unsigned int ratio;
  4847. LIST_HEAD(invalid_list);
  4848. ulong to_zap;
  4849. rcu_idx = srcu_read_lock(&kvm->srcu);
  4850. spin_lock(&kvm->mmu_lock);
  4851. ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
  4852. to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
  4853. while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
  4854. /*
  4855. * We use a separate list instead of just using active_mmu_pages
  4856. * because the number of lpage_disallowed pages is expected to
  4857. * be relatively small compared to the total.
  4858. */
  4859. sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
  4860. struct kvm_mmu_page,
  4861. lpage_disallowed_link);
  4862. WARN_ON_ONCE(!sp->lpage_disallowed);
  4863. kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
  4864. WARN_ON_ONCE(sp->lpage_disallowed);
  4865. if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
  4866. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  4867. if (to_zap)
  4868. cond_resched_lock(&kvm->mmu_lock);
  4869. }
  4870. }
  4871. kvm_mmu_commit_zap_page(kvm, &invalid_list);
  4872. spin_unlock(&kvm->mmu_lock);
  4873. srcu_read_unlock(&kvm->srcu, rcu_idx);
  4874. }
  4875. static long get_nx_lpage_recovery_timeout(u64 start_time)
  4876. {
  4877. return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
  4878. ? start_time + 60 * HZ - get_jiffies_64()
  4879. : MAX_SCHEDULE_TIMEOUT;
  4880. }
  4881. static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
  4882. {
  4883. u64 start_time;
  4884. long remaining_time;
  4885. while (true) {
  4886. start_time = get_jiffies_64();
  4887. remaining_time = get_nx_lpage_recovery_timeout(start_time);
  4888. set_current_state(TASK_INTERRUPTIBLE);
  4889. while (!kthread_should_stop() && remaining_time > 0) {
  4890. schedule_timeout(remaining_time);
  4891. remaining_time = get_nx_lpage_recovery_timeout(start_time);
  4892. set_current_state(TASK_INTERRUPTIBLE);
  4893. }
  4894. set_current_state(TASK_RUNNING);
  4895. if (kthread_should_stop())
  4896. return 0;
  4897. kvm_recover_nx_lpages(kvm);
  4898. }
  4899. }
  4900. int kvm_mmu_post_init_vm(struct kvm *kvm)
  4901. {
  4902. int err;
  4903. err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
  4904. "kvm-nx-lpage-recovery",
  4905. &kvm->arch.nx_lpage_recovery_thread);
  4906. if (!err)
  4907. kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
  4908. return err;
  4909. }
  4910. void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
  4911. {
  4912. if (kvm->arch.nx_lpage_recovery_thread)
  4913. kthread_stop(kvm->arch.nx_lpage_recovery_thread);
  4914. }