x86.c 251 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742
  1. /*
  2. * Kernel-based Virtual Machine driver for Linux
  3. *
  4. * derived from drivers/kvm/kvm_main.c
  5. *
  6. * Copyright (C) 2006 Qumranet, Inc.
  7. * Copyright (C) 2008 Qumranet, Inc.
  8. * Copyright IBM Corporation, 2008
  9. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  10. *
  11. * Authors:
  12. * Avi Kivity <avi@qumranet.com>
  13. * Yaniv Kamay <yaniv@qumranet.com>
  14. * Amit Shah <amit.shah@qumranet.com>
  15. * Ben-Ami Yassour <benami@il.ibm.com>
  16. *
  17. * This work is licensed under the terms of the GNU GPL, version 2. See
  18. * the COPYING file in the top-level directory.
  19. *
  20. */
  21. #include <linux/kvm_host.h>
  22. #include "irq.h"
  23. #include "mmu.h"
  24. #include "i8254.h"
  25. #include "tss.h"
  26. #include "kvm_cache_regs.h"
  27. #include "x86.h"
  28. #include "cpuid.h"
  29. #include "pmu.h"
  30. #include "hyperv.h"
  31. #include <linux/clocksource.h>
  32. #include <linux/interrupt.h>
  33. #include <linux/kvm.h>
  34. #include <linux/fs.h>
  35. #include <linux/vmalloc.h>
  36. #include <linux/export.h>
  37. #include <linux/moduleparam.h>
  38. #include <linux/mman.h>
  39. #include <linux/highmem.h>
  40. #include <linux/iommu.h>
  41. #include <linux/intel-iommu.h>
  42. #include <linux/cpufreq.h>
  43. #include <linux/user-return-notifier.h>
  44. #include <linux/srcu.h>
  45. #include <linux/slab.h>
  46. #include <linux/perf_event.h>
  47. #include <linux/uaccess.h>
  48. #include <linux/hash.h>
  49. #include <linux/pci.h>
  50. #include <linux/timekeeper_internal.h>
  51. #include <linux/pvclock_gtod.h>
  52. #include <linux/kvm_irqfd.h>
  53. #include <linux/irqbypass.h>
  54. #include <linux/sched/stat.h>
  55. #include <linux/mem_encrypt.h>
  56. #include <trace/events/kvm.h>
  57. #include <asm/debugreg.h>
  58. #include <asm/msr.h>
  59. #include <asm/desc.h>
  60. #include <asm/mce.h>
  61. #include <linux/kernel_stat.h>
  62. #include <asm/fpu/internal.h> /* Ugh! */
  63. #include <asm/pvclock.h>
  64. #include <asm/div64.h>
  65. #include <asm/irq_remapping.h>
  66. #include <asm/mshyperv.h>
  67. #include <asm/hypervisor.h>
  68. #define CREATE_TRACE_POINTS
  69. #include "trace.h"
  70. #define MAX_IO_MSRS 256
  71. #define KVM_MAX_MCE_BANKS 32
  72. u64 __read_mostly kvm_mce_cap_supported = MCG_CTL_P | MCG_SER_P;
  73. EXPORT_SYMBOL_GPL(kvm_mce_cap_supported);
  74. #define emul_to_vcpu(ctxt) \
  75. container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
  76. /* EFER defaults:
  77. * - enable syscall per default because its emulated by KVM
  78. * - enable LME and LMA per default on 64 bit KVM
  79. */
  80. #ifdef CONFIG_X86_64
  81. static
  82. u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
  83. #else
  84. static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  85. #endif
  86. #define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
  87. #define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
  88. #define KVM_X2APIC_API_VALID_FLAGS (KVM_X2APIC_API_USE_32BIT_IDS | \
  89. KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  90. static void update_cr8_intercept(struct kvm_vcpu *vcpu);
  91. static void process_nmi(struct kvm_vcpu *vcpu);
  92. static void enter_smm(struct kvm_vcpu *vcpu);
  93. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
  94. static void store_regs(struct kvm_vcpu *vcpu);
  95. static int sync_regs(struct kvm_vcpu *vcpu);
  96. struct kvm_x86_ops *kvm_x86_ops __read_mostly;
  97. EXPORT_SYMBOL_GPL(kvm_x86_ops);
  98. static bool __read_mostly ignore_msrs = 0;
  99. module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
  100. static bool __read_mostly report_ignored_msrs = true;
  101. module_param(report_ignored_msrs, bool, S_IRUGO | S_IWUSR);
  102. unsigned int min_timer_period_us = 200;
  103. module_param(min_timer_period_us, uint, S_IRUGO | S_IWUSR);
  104. static bool __read_mostly kvmclock_periodic_sync = true;
  105. module_param(kvmclock_periodic_sync, bool, S_IRUGO);
  106. bool __read_mostly kvm_has_tsc_control;
  107. EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
  108. u32 __read_mostly kvm_max_guest_tsc_khz;
  109. EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
  110. u8 __read_mostly kvm_tsc_scaling_ratio_frac_bits;
  111. EXPORT_SYMBOL_GPL(kvm_tsc_scaling_ratio_frac_bits);
  112. u64 __read_mostly kvm_max_tsc_scaling_ratio;
  113. EXPORT_SYMBOL_GPL(kvm_max_tsc_scaling_ratio);
  114. u64 __read_mostly kvm_default_tsc_scaling_ratio;
  115. EXPORT_SYMBOL_GPL(kvm_default_tsc_scaling_ratio);
  116. /* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
  117. static u32 __read_mostly tsc_tolerance_ppm = 250;
  118. module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
  119. /* lapic timer advance (tscdeadline mode only) in nanoseconds */
  120. unsigned int __read_mostly lapic_timer_advance_ns = 1000;
  121. module_param(lapic_timer_advance_ns, uint, S_IRUGO | S_IWUSR);
  122. EXPORT_SYMBOL_GPL(lapic_timer_advance_ns);
  123. static bool __read_mostly vector_hashing = true;
  124. module_param(vector_hashing, bool, S_IRUGO);
  125. bool __read_mostly enable_vmware_backdoor = false;
  126. module_param(enable_vmware_backdoor, bool, S_IRUGO);
  127. EXPORT_SYMBOL_GPL(enable_vmware_backdoor);
  128. static bool __read_mostly force_emulation_prefix = false;
  129. module_param(force_emulation_prefix, bool, S_IRUGO);
  130. #define KVM_NR_SHARED_MSRS 16
  131. struct kvm_shared_msrs_global {
  132. int nr;
  133. u32 msrs[KVM_NR_SHARED_MSRS];
  134. };
  135. struct kvm_shared_msrs {
  136. struct user_return_notifier urn;
  137. bool registered;
  138. struct kvm_shared_msr_values {
  139. u64 host;
  140. u64 curr;
  141. } values[KVM_NR_SHARED_MSRS];
  142. };
  143. static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
  144. static struct kvm_shared_msrs __percpu *shared_msrs;
  145. struct kvm_stats_debugfs_item debugfs_entries[] = {
  146. { "pf_fixed", VCPU_STAT(pf_fixed) },
  147. { "pf_guest", VCPU_STAT(pf_guest) },
  148. { "tlb_flush", VCPU_STAT(tlb_flush) },
  149. { "invlpg", VCPU_STAT(invlpg) },
  150. { "exits", VCPU_STAT(exits) },
  151. { "io_exits", VCPU_STAT(io_exits) },
  152. { "mmio_exits", VCPU_STAT(mmio_exits) },
  153. { "signal_exits", VCPU_STAT(signal_exits) },
  154. { "irq_window", VCPU_STAT(irq_window_exits) },
  155. { "nmi_window", VCPU_STAT(nmi_window_exits) },
  156. { "halt_exits", VCPU_STAT(halt_exits) },
  157. { "halt_successful_poll", VCPU_STAT(halt_successful_poll) },
  158. { "halt_attempted_poll", VCPU_STAT(halt_attempted_poll) },
  159. { "halt_poll_invalid", VCPU_STAT(halt_poll_invalid) },
  160. { "halt_wakeup", VCPU_STAT(halt_wakeup) },
  161. { "hypercalls", VCPU_STAT(hypercalls) },
  162. { "request_irq", VCPU_STAT(request_irq_exits) },
  163. { "irq_exits", VCPU_STAT(irq_exits) },
  164. { "host_state_reload", VCPU_STAT(host_state_reload) },
  165. { "fpu_reload", VCPU_STAT(fpu_reload) },
  166. { "insn_emulation", VCPU_STAT(insn_emulation) },
  167. { "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
  168. { "irq_injections", VCPU_STAT(irq_injections) },
  169. { "nmi_injections", VCPU_STAT(nmi_injections) },
  170. { "req_event", VCPU_STAT(req_event) },
  171. { "l1d_flush", VCPU_STAT(l1d_flush) },
  172. { "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
  173. { "mmu_pte_write", VM_STAT(mmu_pte_write) },
  174. { "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
  175. { "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
  176. { "mmu_flooded", VM_STAT(mmu_flooded) },
  177. { "mmu_recycled", VM_STAT(mmu_recycled) },
  178. { "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
  179. { "mmu_unsync", VM_STAT(mmu_unsync) },
  180. { "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
  181. { "largepages", VM_STAT(lpages) },
  182. { "max_mmu_page_hash_collisions",
  183. VM_STAT(max_mmu_page_hash_collisions) },
  184. { NULL }
  185. };
  186. u64 __read_mostly host_xcr0;
  187. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
  188. static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
  189. {
  190. int i;
  191. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
  192. vcpu->arch.apf.gfns[i] = ~0;
  193. }
  194. static void kvm_on_user_return(struct user_return_notifier *urn)
  195. {
  196. unsigned slot;
  197. struct kvm_shared_msrs *locals
  198. = container_of(urn, struct kvm_shared_msrs, urn);
  199. struct kvm_shared_msr_values *values;
  200. unsigned long flags;
  201. /*
  202. * Disabling irqs at this point since the following code could be
  203. * interrupted and executed through kvm_arch_hardware_disable()
  204. */
  205. local_irq_save(flags);
  206. if (locals->registered) {
  207. locals->registered = false;
  208. user_return_notifier_unregister(urn);
  209. }
  210. local_irq_restore(flags);
  211. for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
  212. values = &locals->values[slot];
  213. if (values->host != values->curr) {
  214. wrmsrl(shared_msrs_global.msrs[slot], values->host);
  215. values->curr = values->host;
  216. }
  217. }
  218. }
  219. static void shared_msr_update(unsigned slot, u32 msr)
  220. {
  221. u64 value;
  222. unsigned int cpu = smp_processor_id();
  223. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  224. /* only read, and nobody should modify it at this time,
  225. * so don't need lock */
  226. if (slot >= shared_msrs_global.nr) {
  227. printk(KERN_ERR "kvm: invalid MSR slot!");
  228. return;
  229. }
  230. rdmsrl_safe(msr, &value);
  231. smsr->values[slot].host = value;
  232. smsr->values[slot].curr = value;
  233. }
  234. void kvm_define_shared_msr(unsigned slot, u32 msr)
  235. {
  236. BUG_ON(slot >= KVM_NR_SHARED_MSRS);
  237. shared_msrs_global.msrs[slot] = msr;
  238. if (slot >= shared_msrs_global.nr)
  239. shared_msrs_global.nr = slot + 1;
  240. }
  241. EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
  242. static void kvm_shared_msr_cpu_online(void)
  243. {
  244. unsigned i;
  245. for (i = 0; i < shared_msrs_global.nr; ++i)
  246. shared_msr_update(i, shared_msrs_global.msrs[i]);
  247. }
  248. int kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
  249. {
  250. unsigned int cpu = smp_processor_id();
  251. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  252. int err;
  253. if (((value ^ smsr->values[slot].curr) & mask) == 0)
  254. return 0;
  255. smsr->values[slot].curr = value;
  256. err = wrmsrl_safe(shared_msrs_global.msrs[slot], value);
  257. if (err)
  258. return 1;
  259. if (!smsr->registered) {
  260. smsr->urn.on_user_return = kvm_on_user_return;
  261. user_return_notifier_register(&smsr->urn);
  262. smsr->registered = true;
  263. }
  264. return 0;
  265. }
  266. EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
  267. static void drop_user_return_notifiers(void)
  268. {
  269. unsigned int cpu = smp_processor_id();
  270. struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
  271. if (smsr->registered)
  272. kvm_on_user_return(&smsr->urn);
  273. }
  274. u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
  275. {
  276. return vcpu->arch.apic_base;
  277. }
  278. EXPORT_SYMBOL_GPL(kvm_get_apic_base);
  279. enum lapic_mode kvm_get_apic_mode(struct kvm_vcpu *vcpu)
  280. {
  281. return kvm_apic_mode(kvm_get_apic_base(vcpu));
  282. }
  283. EXPORT_SYMBOL_GPL(kvm_get_apic_mode);
  284. int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  285. {
  286. enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
  287. enum lapic_mode new_mode = kvm_apic_mode(msr_info->data);
  288. u64 reserved_bits = ((~0ULL) << cpuid_maxphyaddr(vcpu)) | 0x2ff |
  289. (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
  290. if ((msr_info->data & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
  291. return 1;
  292. if (!msr_info->host_initiated) {
  293. if (old_mode == LAPIC_MODE_X2APIC && new_mode == LAPIC_MODE_XAPIC)
  294. return 1;
  295. if (old_mode == LAPIC_MODE_DISABLED && new_mode == LAPIC_MODE_X2APIC)
  296. return 1;
  297. }
  298. kvm_lapic_set_base(vcpu, msr_info->data);
  299. return 0;
  300. }
  301. EXPORT_SYMBOL_GPL(kvm_set_apic_base);
  302. asmlinkage __visible void kvm_spurious_fault(void)
  303. {
  304. /* Fault while not rebooting. We want the trace. */
  305. BUG();
  306. }
  307. EXPORT_SYMBOL_GPL(kvm_spurious_fault);
  308. #define EXCPT_BENIGN 0
  309. #define EXCPT_CONTRIBUTORY 1
  310. #define EXCPT_PF 2
  311. static int exception_class(int vector)
  312. {
  313. switch (vector) {
  314. case PF_VECTOR:
  315. return EXCPT_PF;
  316. case DE_VECTOR:
  317. case TS_VECTOR:
  318. case NP_VECTOR:
  319. case SS_VECTOR:
  320. case GP_VECTOR:
  321. return EXCPT_CONTRIBUTORY;
  322. default:
  323. break;
  324. }
  325. return EXCPT_BENIGN;
  326. }
  327. #define EXCPT_FAULT 0
  328. #define EXCPT_TRAP 1
  329. #define EXCPT_ABORT 2
  330. #define EXCPT_INTERRUPT 3
  331. static int exception_type(int vector)
  332. {
  333. unsigned int mask;
  334. if (WARN_ON(vector > 31 || vector == NMI_VECTOR))
  335. return EXCPT_INTERRUPT;
  336. mask = 1 << vector;
  337. /* #DB is trap, as instruction watchpoints are handled elsewhere */
  338. if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
  339. return EXCPT_TRAP;
  340. if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
  341. return EXCPT_ABORT;
  342. /* Reserved exceptions will result in fault */
  343. return EXCPT_FAULT;
  344. }
  345. void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu)
  346. {
  347. unsigned nr = vcpu->arch.exception.nr;
  348. bool has_payload = vcpu->arch.exception.has_payload;
  349. unsigned long payload = vcpu->arch.exception.payload;
  350. if (!has_payload)
  351. return;
  352. switch (nr) {
  353. case DB_VECTOR:
  354. /*
  355. * "Certain debug exceptions may clear bit 0-3. The
  356. * remaining contents of the DR6 register are never
  357. * cleared by the processor".
  358. */
  359. vcpu->arch.dr6 &= ~DR_TRAP_BITS;
  360. /*
  361. * DR6.RTM is set by all #DB exceptions that don't clear it.
  362. */
  363. vcpu->arch.dr6 |= DR6_RTM;
  364. vcpu->arch.dr6 |= payload;
  365. /*
  366. * Bit 16 should be set in the payload whenever the #DB
  367. * exception should clear DR6.RTM. This makes the payload
  368. * compatible with the pending debug exceptions under VMX.
  369. * Though not currently documented in the SDM, this also
  370. * makes the payload compatible with the exit qualification
  371. * for #DB exceptions under VMX.
  372. */
  373. vcpu->arch.dr6 ^= payload & DR6_RTM;
  374. break;
  375. case PF_VECTOR:
  376. vcpu->arch.cr2 = payload;
  377. break;
  378. }
  379. vcpu->arch.exception.has_payload = false;
  380. vcpu->arch.exception.payload = 0;
  381. }
  382. EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);
  383. static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
  384. unsigned nr, bool has_error, u32 error_code,
  385. bool has_payload, unsigned long payload, bool reinject)
  386. {
  387. u32 prev_nr;
  388. int class1, class2;
  389. kvm_make_request(KVM_REQ_EVENT, vcpu);
  390. if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) {
  391. queue:
  392. if (has_error && !is_protmode(vcpu))
  393. has_error = false;
  394. if (reinject) {
  395. /*
  396. * On vmentry, vcpu->arch.exception.pending is only
  397. * true if an event injection was blocked by
  398. * nested_run_pending. In that case, however,
  399. * vcpu_enter_guest requests an immediate exit,
  400. * and the guest shouldn't proceed far enough to
  401. * need reinjection.
  402. */
  403. WARN_ON_ONCE(vcpu->arch.exception.pending);
  404. vcpu->arch.exception.injected = true;
  405. if (WARN_ON_ONCE(has_payload)) {
  406. /*
  407. * A reinjected event has already
  408. * delivered its payload.
  409. */
  410. has_payload = false;
  411. payload = 0;
  412. }
  413. } else {
  414. vcpu->arch.exception.pending = true;
  415. vcpu->arch.exception.injected = false;
  416. }
  417. vcpu->arch.exception.has_error_code = has_error;
  418. vcpu->arch.exception.nr = nr;
  419. vcpu->arch.exception.error_code = error_code;
  420. vcpu->arch.exception.has_payload = has_payload;
  421. vcpu->arch.exception.payload = payload;
  422. /*
  423. * In guest mode, payload delivery should be deferred,
  424. * so that the L1 hypervisor can intercept #PF before
  425. * CR2 is modified (or intercept #DB before DR6 is
  426. * modified under nVMX). However, for ABI
  427. * compatibility with KVM_GET_VCPU_EVENTS and
  428. * KVM_SET_VCPU_EVENTS, we can't delay payload
  429. * delivery unless userspace has enabled this
  430. * functionality via the per-VM capability,
  431. * KVM_CAP_EXCEPTION_PAYLOAD.
  432. */
  433. if (!vcpu->kvm->arch.exception_payload_enabled ||
  434. !is_guest_mode(vcpu))
  435. kvm_deliver_exception_payload(vcpu);
  436. return;
  437. }
  438. /* to check exception */
  439. prev_nr = vcpu->arch.exception.nr;
  440. if (prev_nr == DF_VECTOR) {
  441. /* triple fault -> shutdown */
  442. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  443. return;
  444. }
  445. class1 = exception_class(prev_nr);
  446. class2 = exception_class(nr);
  447. if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
  448. || (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
  449. /*
  450. * Generate double fault per SDM Table 5-5. Set
  451. * exception.pending = true so that the double fault
  452. * can trigger a nested vmexit.
  453. */
  454. vcpu->arch.exception.pending = true;
  455. vcpu->arch.exception.injected = false;
  456. vcpu->arch.exception.has_error_code = true;
  457. vcpu->arch.exception.nr = DF_VECTOR;
  458. vcpu->arch.exception.error_code = 0;
  459. vcpu->arch.exception.has_payload = false;
  460. vcpu->arch.exception.payload = 0;
  461. } else
  462. /* replace previous exception with a new one in a hope
  463. that instruction re-execution will regenerate lost
  464. exception */
  465. goto queue;
  466. }
  467. void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  468. {
  469. kvm_multiple_exception(vcpu, nr, false, 0, false, 0, false);
  470. }
  471. EXPORT_SYMBOL_GPL(kvm_queue_exception);
  472. void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
  473. {
  474. kvm_multiple_exception(vcpu, nr, false, 0, false, 0, true);
  475. }
  476. EXPORT_SYMBOL_GPL(kvm_requeue_exception);
  477. static void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr,
  478. unsigned long payload)
  479. {
  480. kvm_multiple_exception(vcpu, nr, false, 0, true, payload, false);
  481. }
  482. static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
  483. u32 error_code, unsigned long payload)
  484. {
  485. kvm_multiple_exception(vcpu, nr, true, error_code,
  486. true, payload, false);
  487. }
  488. int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
  489. {
  490. if (err)
  491. kvm_inject_gp(vcpu, 0);
  492. else
  493. return kvm_skip_emulated_instruction(vcpu);
  494. return 1;
  495. }
  496. EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
  497. void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  498. {
  499. ++vcpu->stat.pf_guest;
  500. vcpu->arch.exception.nested_apf =
  501. is_guest_mode(vcpu) && fault->async_page_fault;
  502. if (vcpu->arch.exception.nested_apf) {
  503. vcpu->arch.apf.nested_apf_token = fault->address;
  504. kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
  505. } else {
  506. kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
  507. fault->address);
  508. }
  509. }
  510. EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
  511. static bool kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  512. {
  513. if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
  514. vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
  515. else
  516. vcpu->arch.mmu->inject_page_fault(vcpu, fault);
  517. return fault->nested_page_fault;
  518. }
  519. void kvm_inject_nmi(struct kvm_vcpu *vcpu)
  520. {
  521. atomic_inc(&vcpu->arch.nmi_queued);
  522. kvm_make_request(KVM_REQ_NMI, vcpu);
  523. }
  524. EXPORT_SYMBOL_GPL(kvm_inject_nmi);
  525. void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  526. {
  527. kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, false);
  528. }
  529. EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
  530. void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
  531. {
  532. kvm_multiple_exception(vcpu, nr, true, error_code, false, 0, true);
  533. }
  534. EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
  535. /*
  536. * Checks if cpl <= required_cpl; if true, return true. Otherwise queue
  537. * a #GP and return false.
  538. */
  539. bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
  540. {
  541. if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
  542. return true;
  543. kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
  544. return false;
  545. }
  546. EXPORT_SYMBOL_GPL(kvm_require_cpl);
  547. bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
  548. {
  549. if ((dr != 4 && dr != 5) || !kvm_read_cr4_bits(vcpu, X86_CR4_DE))
  550. return true;
  551. kvm_queue_exception(vcpu, UD_VECTOR);
  552. return false;
  553. }
  554. EXPORT_SYMBOL_GPL(kvm_require_dr);
  555. /*
  556. * This function will be used to read from the physical memory of the currently
  557. * running guest. The difference to kvm_vcpu_read_guest_page is that this function
  558. * can read from guest physical or from the guest's guest physical memory.
  559. */
  560. int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
  561. gfn_t ngfn, void *data, int offset, int len,
  562. u32 access)
  563. {
  564. struct x86_exception exception;
  565. gfn_t real_gfn;
  566. gpa_t ngpa;
  567. ngpa = gfn_to_gpa(ngfn);
  568. real_gfn = mmu->translate_gpa(vcpu, ngpa, access, &exception);
  569. if (real_gfn == UNMAPPED_GVA)
  570. return -EFAULT;
  571. real_gfn = gpa_to_gfn(real_gfn);
  572. return kvm_vcpu_read_guest_page(vcpu, real_gfn, data, offset, len);
  573. }
  574. EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
  575. static int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  576. void *data, int offset, int len, u32 access)
  577. {
  578. return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
  579. data, offset, len, access);
  580. }
  581. /*
  582. * Load the pae pdptrs. Return true is they are all valid.
  583. */
  584. int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
  585. {
  586. gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
  587. unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
  588. int i;
  589. int ret;
  590. u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
  591. ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
  592. offset * sizeof(u64), sizeof(pdpte),
  593. PFERR_USER_MASK|PFERR_WRITE_MASK);
  594. if (ret < 0) {
  595. ret = 0;
  596. goto out;
  597. }
  598. for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
  599. if ((pdpte[i] & PT_PRESENT_MASK) &&
  600. (pdpte[i] &
  601. vcpu->arch.mmu->guest_rsvd_check.rsvd_bits_mask[0][2])) {
  602. ret = 0;
  603. goto out;
  604. }
  605. }
  606. ret = 1;
  607. memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
  608. __set_bit(VCPU_EXREG_PDPTR,
  609. (unsigned long *)&vcpu->arch.regs_avail);
  610. __set_bit(VCPU_EXREG_PDPTR,
  611. (unsigned long *)&vcpu->arch.regs_dirty);
  612. out:
  613. return ret;
  614. }
  615. EXPORT_SYMBOL_GPL(load_pdptrs);
  616. bool pdptrs_changed(struct kvm_vcpu *vcpu)
  617. {
  618. u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
  619. bool changed = true;
  620. int offset;
  621. gfn_t gfn;
  622. int r;
  623. if (is_long_mode(vcpu) || !is_pae(vcpu) || !is_paging(vcpu))
  624. return false;
  625. if (!test_bit(VCPU_EXREG_PDPTR,
  626. (unsigned long *)&vcpu->arch.regs_avail))
  627. return true;
  628. gfn = (kvm_read_cr3(vcpu) & 0xffffffe0ul) >> PAGE_SHIFT;
  629. offset = (kvm_read_cr3(vcpu) & 0xffffffe0ul) & (PAGE_SIZE - 1);
  630. r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
  631. PFERR_USER_MASK | PFERR_WRITE_MASK);
  632. if (r < 0)
  633. goto out;
  634. changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
  635. out:
  636. return changed;
  637. }
  638. EXPORT_SYMBOL_GPL(pdptrs_changed);
  639. int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
  640. {
  641. unsigned long old_cr0 = kvm_read_cr0(vcpu);
  642. unsigned long update_bits = X86_CR0_PG | X86_CR0_WP;
  643. cr0 |= X86_CR0_ET;
  644. #ifdef CONFIG_X86_64
  645. if (cr0 & 0xffffffff00000000UL)
  646. return 1;
  647. #endif
  648. cr0 &= ~CR0_RESERVED_BITS;
  649. if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
  650. return 1;
  651. if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
  652. return 1;
  653. if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
  654. #ifdef CONFIG_X86_64
  655. if ((vcpu->arch.efer & EFER_LME)) {
  656. int cs_db, cs_l;
  657. if (!is_pae(vcpu))
  658. return 1;
  659. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  660. if (cs_l)
  661. return 1;
  662. } else
  663. #endif
  664. if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  665. kvm_read_cr3(vcpu)))
  666. return 1;
  667. }
  668. if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
  669. return 1;
  670. kvm_x86_ops->set_cr0(vcpu, cr0);
  671. if ((cr0 ^ old_cr0) & X86_CR0_PG) {
  672. kvm_clear_async_pf_completion_queue(vcpu);
  673. kvm_async_pf_hash_reset(vcpu);
  674. }
  675. if ((cr0 ^ old_cr0) & update_bits)
  676. kvm_mmu_reset_context(vcpu);
  677. if (((cr0 ^ old_cr0) & X86_CR0_CD) &&
  678. kvm_arch_has_noncoherent_dma(vcpu->kvm) &&
  679. !kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
  680. kvm_zap_gfn_range(vcpu->kvm, 0, ~0ULL);
  681. return 0;
  682. }
  683. EXPORT_SYMBOL_GPL(kvm_set_cr0);
  684. void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
  685. {
  686. (void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
  687. }
  688. EXPORT_SYMBOL_GPL(kvm_lmsw);
  689. static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
  690. {
  691. if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
  692. !vcpu->guest_xcr0_loaded) {
  693. /* kvm_set_xcr() also depends on this */
  694. if (vcpu->arch.xcr0 != host_xcr0)
  695. xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
  696. vcpu->guest_xcr0_loaded = 1;
  697. }
  698. }
  699. static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
  700. {
  701. if (vcpu->guest_xcr0_loaded) {
  702. if (vcpu->arch.xcr0 != host_xcr0)
  703. xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
  704. vcpu->guest_xcr0_loaded = 0;
  705. }
  706. }
  707. static int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  708. {
  709. u64 xcr0 = xcr;
  710. u64 old_xcr0 = vcpu->arch.xcr0;
  711. u64 valid_bits;
  712. /* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
  713. if (index != XCR_XFEATURE_ENABLED_MASK)
  714. return 1;
  715. if (!(xcr0 & XFEATURE_MASK_FP))
  716. return 1;
  717. if ((xcr0 & XFEATURE_MASK_YMM) && !(xcr0 & XFEATURE_MASK_SSE))
  718. return 1;
  719. /*
  720. * Do not allow the guest to set bits that we do not support
  721. * saving. However, xcr0 bit 0 is always set, even if the
  722. * emulated CPU does not support XSAVE (see fx_init).
  723. */
  724. valid_bits = vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FP;
  725. if (xcr0 & ~valid_bits)
  726. return 1;
  727. if ((!(xcr0 & XFEATURE_MASK_BNDREGS)) !=
  728. (!(xcr0 & XFEATURE_MASK_BNDCSR)))
  729. return 1;
  730. if (xcr0 & XFEATURE_MASK_AVX512) {
  731. if (!(xcr0 & XFEATURE_MASK_YMM))
  732. return 1;
  733. if ((xcr0 & XFEATURE_MASK_AVX512) != XFEATURE_MASK_AVX512)
  734. return 1;
  735. }
  736. vcpu->arch.xcr0 = xcr0;
  737. if ((xcr0 ^ old_xcr0) & XFEATURE_MASK_EXTEND)
  738. kvm_update_cpuid(vcpu);
  739. return 0;
  740. }
  741. int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
  742. {
  743. if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
  744. __kvm_set_xcr(vcpu, index, xcr)) {
  745. kvm_inject_gp(vcpu, 0);
  746. return 1;
  747. }
  748. return 0;
  749. }
  750. EXPORT_SYMBOL_GPL(kvm_set_xcr);
  751. int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
  752. {
  753. unsigned long old_cr4 = kvm_read_cr4(vcpu);
  754. unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE |
  755. X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE;
  756. if (cr4 & CR4_RESERVED_BITS)
  757. return 1;
  758. if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
  759. return 1;
  760. if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
  761. return 1;
  762. if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
  763. return 1;
  764. if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
  765. return 1;
  766. if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
  767. return 1;
  768. if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
  769. return 1;
  770. if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
  771. return 1;
  772. if (is_long_mode(vcpu)) {
  773. if (!(cr4 & X86_CR4_PAE))
  774. return 1;
  775. } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
  776. && ((cr4 ^ old_cr4) & pdptr_bits)
  777. && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
  778. kvm_read_cr3(vcpu)))
  779. return 1;
  780. if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
  781. if (!guest_cpuid_has(vcpu, X86_FEATURE_PCID))
  782. return 1;
  783. /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
  784. if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
  785. return 1;
  786. }
  787. if (kvm_x86_ops->set_cr4(vcpu, cr4))
  788. return 1;
  789. if (((cr4 ^ old_cr4) & pdptr_bits) ||
  790. (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
  791. kvm_mmu_reset_context(vcpu);
  792. if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
  793. kvm_update_cpuid(vcpu);
  794. return 0;
  795. }
  796. EXPORT_SYMBOL_GPL(kvm_set_cr4);
  797. int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
  798. {
  799. bool skip_tlb_flush = false;
  800. #ifdef CONFIG_X86_64
  801. bool pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
  802. if (pcid_enabled) {
  803. skip_tlb_flush = cr3 & X86_CR3_PCID_NOFLUSH;
  804. cr3 &= ~X86_CR3_PCID_NOFLUSH;
  805. }
  806. #endif
  807. if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
  808. if (!skip_tlb_flush) {
  809. kvm_mmu_sync_roots(vcpu);
  810. kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
  811. }
  812. return 0;
  813. }
  814. if (is_long_mode(vcpu) &&
  815. (cr3 & rsvd_bits(cpuid_maxphyaddr(vcpu), 63)))
  816. return 1;
  817. else if (is_pae(vcpu) && is_paging(vcpu) &&
  818. !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
  819. return 1;
  820. kvm_mmu_new_cr3(vcpu, cr3, skip_tlb_flush);
  821. vcpu->arch.cr3 = cr3;
  822. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  823. return 0;
  824. }
  825. EXPORT_SYMBOL_GPL(kvm_set_cr3);
  826. int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
  827. {
  828. if (cr8 & CR8_RESERVED_BITS)
  829. return 1;
  830. if (lapic_in_kernel(vcpu))
  831. kvm_lapic_set_tpr(vcpu, cr8);
  832. else
  833. vcpu->arch.cr8 = cr8;
  834. return 0;
  835. }
  836. EXPORT_SYMBOL_GPL(kvm_set_cr8);
  837. unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
  838. {
  839. if (lapic_in_kernel(vcpu))
  840. return kvm_lapic_get_cr8(vcpu);
  841. else
  842. return vcpu->arch.cr8;
  843. }
  844. EXPORT_SYMBOL_GPL(kvm_get_cr8);
  845. static void kvm_update_dr0123(struct kvm_vcpu *vcpu)
  846. {
  847. int i;
  848. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) {
  849. for (i = 0; i < KVM_NR_DB_REGS; i++)
  850. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  851. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_RELOAD;
  852. }
  853. }
  854. static void kvm_update_dr6(struct kvm_vcpu *vcpu)
  855. {
  856. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  857. kvm_x86_ops->set_dr6(vcpu, vcpu->arch.dr6);
  858. }
  859. static void kvm_update_dr7(struct kvm_vcpu *vcpu)
  860. {
  861. unsigned long dr7;
  862. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  863. dr7 = vcpu->arch.guest_debug_dr7;
  864. else
  865. dr7 = vcpu->arch.dr7;
  866. kvm_x86_ops->set_dr7(vcpu, dr7);
  867. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_BP_ENABLED;
  868. if (dr7 & DR7_BP_EN_MASK)
  869. vcpu->arch.switch_db_regs |= KVM_DEBUGREG_BP_ENABLED;
  870. }
  871. static u64 kvm_dr6_fixed(struct kvm_vcpu *vcpu)
  872. {
  873. u64 fixed = DR6_FIXED_1;
  874. if (!guest_cpuid_has(vcpu, X86_FEATURE_RTM))
  875. fixed |= DR6_RTM;
  876. return fixed;
  877. }
  878. static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  879. {
  880. switch (dr) {
  881. case 0 ... 3:
  882. vcpu->arch.db[dr] = val;
  883. if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
  884. vcpu->arch.eff_db[dr] = val;
  885. break;
  886. case 4:
  887. /* fall through */
  888. case 6:
  889. if (val & 0xffffffff00000000ULL)
  890. return -1; /* #GP */
  891. vcpu->arch.dr6 = (val & DR6_VOLATILE) | kvm_dr6_fixed(vcpu);
  892. kvm_update_dr6(vcpu);
  893. break;
  894. case 5:
  895. /* fall through */
  896. default: /* 7 */
  897. if (val & 0xffffffff00000000ULL)
  898. return -1; /* #GP */
  899. vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
  900. kvm_update_dr7(vcpu);
  901. break;
  902. }
  903. return 0;
  904. }
  905. int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  906. {
  907. if (__kvm_set_dr(vcpu, dr, val)) {
  908. kvm_inject_gp(vcpu, 0);
  909. return 1;
  910. }
  911. return 0;
  912. }
  913. EXPORT_SYMBOL_GPL(kvm_set_dr);
  914. int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  915. {
  916. switch (dr) {
  917. case 0 ... 3:
  918. *val = vcpu->arch.db[dr];
  919. break;
  920. case 4:
  921. /* fall through */
  922. case 6:
  923. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
  924. *val = vcpu->arch.dr6;
  925. else
  926. *val = kvm_x86_ops->get_dr6(vcpu);
  927. break;
  928. case 5:
  929. /* fall through */
  930. default: /* 7 */
  931. *val = vcpu->arch.dr7;
  932. break;
  933. }
  934. return 0;
  935. }
  936. EXPORT_SYMBOL_GPL(kvm_get_dr);
  937. bool kvm_rdpmc(struct kvm_vcpu *vcpu)
  938. {
  939. u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  940. u64 data;
  941. int err;
  942. err = kvm_pmu_rdpmc(vcpu, ecx, &data);
  943. if (err)
  944. return err;
  945. kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
  946. kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
  947. return err;
  948. }
  949. EXPORT_SYMBOL_GPL(kvm_rdpmc);
  950. /*
  951. * List of msr numbers which we expose to userspace through KVM_GET_MSRS
  952. * and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
  953. *
  954. * This list is modified at module load time to reflect the
  955. * capabilities of the host cpu. This capabilities test skips MSRs that are
  956. * kvm-specific. Those are put in emulated_msrs; filtering of emulated_msrs
  957. * may depend on host virtualization features rather than host cpu features.
  958. */
  959. static u32 msrs_to_save[] = {
  960. MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
  961. MSR_STAR,
  962. #ifdef CONFIG_X86_64
  963. MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  964. #endif
  965. MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
  966. MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
  967. MSR_IA32_SPEC_CTRL, MSR_IA32_ARCH_CAPABILITIES
  968. };
  969. static unsigned num_msrs_to_save;
  970. static u32 emulated_msrs[] = {
  971. MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
  972. MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
  973. HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
  974. HV_X64_MSR_TIME_REF_COUNT, HV_X64_MSR_REFERENCE_TSC,
  975. HV_X64_MSR_TSC_FREQUENCY, HV_X64_MSR_APIC_FREQUENCY,
  976. HV_X64_MSR_CRASH_P0, HV_X64_MSR_CRASH_P1, HV_X64_MSR_CRASH_P2,
  977. HV_X64_MSR_CRASH_P3, HV_X64_MSR_CRASH_P4, HV_X64_MSR_CRASH_CTL,
  978. HV_X64_MSR_RESET,
  979. HV_X64_MSR_VP_INDEX,
  980. HV_X64_MSR_VP_RUNTIME,
  981. HV_X64_MSR_SCONTROL,
  982. HV_X64_MSR_STIMER0_CONFIG,
  983. HV_X64_MSR_VP_ASSIST_PAGE,
  984. HV_X64_MSR_REENLIGHTENMENT_CONTROL, HV_X64_MSR_TSC_EMULATION_CONTROL,
  985. HV_X64_MSR_TSC_EMULATION_STATUS,
  986. MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
  987. MSR_KVM_PV_EOI_EN,
  988. MSR_IA32_TSC_ADJUST,
  989. MSR_IA32_TSCDEADLINE,
  990. MSR_IA32_MISC_ENABLE,
  991. MSR_IA32_MCG_STATUS,
  992. MSR_IA32_MCG_CTL,
  993. MSR_IA32_MCG_EXT_CTL,
  994. MSR_IA32_SMBASE,
  995. MSR_SMI_COUNT,
  996. MSR_PLATFORM_INFO,
  997. MSR_MISC_FEATURES_ENABLES,
  998. MSR_AMD64_VIRT_SPEC_CTRL,
  999. };
  1000. static unsigned num_emulated_msrs;
  1001. /*
  1002. * List of msr numbers which are used to expose MSR-based features that
  1003. * can be used by a hypervisor to validate requested CPU features.
  1004. */
  1005. static u32 msr_based_features[] = {
  1006. MSR_IA32_VMX_BASIC,
  1007. MSR_IA32_VMX_TRUE_PINBASED_CTLS,
  1008. MSR_IA32_VMX_PINBASED_CTLS,
  1009. MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
  1010. MSR_IA32_VMX_PROCBASED_CTLS,
  1011. MSR_IA32_VMX_TRUE_EXIT_CTLS,
  1012. MSR_IA32_VMX_EXIT_CTLS,
  1013. MSR_IA32_VMX_TRUE_ENTRY_CTLS,
  1014. MSR_IA32_VMX_ENTRY_CTLS,
  1015. MSR_IA32_VMX_MISC,
  1016. MSR_IA32_VMX_CR0_FIXED0,
  1017. MSR_IA32_VMX_CR0_FIXED1,
  1018. MSR_IA32_VMX_CR4_FIXED0,
  1019. MSR_IA32_VMX_CR4_FIXED1,
  1020. MSR_IA32_VMX_VMCS_ENUM,
  1021. MSR_IA32_VMX_PROCBASED_CTLS2,
  1022. MSR_IA32_VMX_EPT_VPID_CAP,
  1023. MSR_IA32_VMX_VMFUNC,
  1024. MSR_F10H_DECFG,
  1025. MSR_IA32_UCODE_REV,
  1026. MSR_IA32_ARCH_CAPABILITIES,
  1027. };
  1028. static unsigned int num_msr_based_features;
  1029. u64 kvm_get_arch_capabilities(void)
  1030. {
  1031. u64 data;
  1032. rdmsrl_safe(MSR_IA32_ARCH_CAPABILITIES, &data);
  1033. /*
  1034. * If we're doing cache flushes (either "always" or "cond")
  1035. * we will do one whenever the guest does a vmlaunch/vmresume.
  1036. * If an outer hypervisor is doing the cache flush for us
  1037. * (VMENTER_L1D_FLUSH_NESTED_VM), we can safely pass that
  1038. * capability to the guest too, and if EPT is disabled we're not
  1039. * vulnerable. Overall, only VMENTER_L1D_FLUSH_NEVER will
  1040. * require a nested hypervisor to do a flush of its own.
  1041. */
  1042. if (l1tf_vmx_mitigation != VMENTER_L1D_FLUSH_NEVER)
  1043. data |= ARCH_CAP_SKIP_VMENTRY_L1DFLUSH;
  1044. return data;
  1045. }
  1046. EXPORT_SYMBOL_GPL(kvm_get_arch_capabilities);
  1047. static int kvm_get_msr_feature(struct kvm_msr_entry *msr)
  1048. {
  1049. switch (msr->index) {
  1050. case MSR_IA32_ARCH_CAPABILITIES:
  1051. msr->data = kvm_get_arch_capabilities();
  1052. break;
  1053. case MSR_IA32_UCODE_REV:
  1054. rdmsrl_safe(msr->index, &msr->data);
  1055. break;
  1056. default:
  1057. if (kvm_x86_ops->get_msr_feature(msr))
  1058. return 1;
  1059. }
  1060. return 0;
  1061. }
  1062. static int do_get_msr_feature(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1063. {
  1064. struct kvm_msr_entry msr;
  1065. int r;
  1066. msr.index = index;
  1067. r = kvm_get_msr_feature(&msr);
  1068. if (r)
  1069. return r;
  1070. *data = msr.data;
  1071. return 0;
  1072. }
  1073. bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
  1074. {
  1075. if (efer & efer_reserved_bits)
  1076. return false;
  1077. if (efer & EFER_FFXSR && !guest_cpuid_has(vcpu, X86_FEATURE_FXSR_OPT))
  1078. return false;
  1079. if (efer & EFER_SVME && !guest_cpuid_has(vcpu, X86_FEATURE_SVM))
  1080. return false;
  1081. return true;
  1082. }
  1083. EXPORT_SYMBOL_GPL(kvm_valid_efer);
  1084. static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
  1085. {
  1086. u64 old_efer = vcpu->arch.efer;
  1087. if (!kvm_valid_efer(vcpu, efer))
  1088. return 1;
  1089. if (is_paging(vcpu)
  1090. && (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
  1091. return 1;
  1092. efer &= ~EFER_LMA;
  1093. efer |= vcpu->arch.efer & EFER_LMA;
  1094. kvm_x86_ops->set_efer(vcpu, efer);
  1095. /* Update reserved bits */
  1096. if ((efer ^ old_efer) & EFER_NX)
  1097. kvm_mmu_reset_context(vcpu);
  1098. return 0;
  1099. }
  1100. void kvm_enable_efer_bits(u64 mask)
  1101. {
  1102. efer_reserved_bits &= ~mask;
  1103. }
  1104. EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
  1105. /*
  1106. * Writes msr value into into the appropriate "register".
  1107. * Returns 0 on success, non-0 otherwise.
  1108. * Assumes vcpu_load() was already called.
  1109. */
  1110. int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1111. {
  1112. switch (msr->index) {
  1113. case MSR_FS_BASE:
  1114. case MSR_GS_BASE:
  1115. case MSR_KERNEL_GS_BASE:
  1116. case MSR_CSTAR:
  1117. case MSR_LSTAR:
  1118. if (is_noncanonical_address(msr->data, vcpu))
  1119. return 1;
  1120. break;
  1121. case MSR_IA32_SYSENTER_EIP:
  1122. case MSR_IA32_SYSENTER_ESP:
  1123. /*
  1124. * IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if
  1125. * non-canonical address is written on Intel but not on
  1126. * AMD (which ignores the top 32-bits, because it does
  1127. * not implement 64-bit SYSENTER).
  1128. *
  1129. * 64-bit code should hence be able to write a non-canonical
  1130. * value on AMD. Making the address canonical ensures that
  1131. * vmentry does not fail on Intel after writing a non-canonical
  1132. * value, and that something deterministic happens if the guest
  1133. * invokes 64-bit SYSENTER.
  1134. */
  1135. msr->data = get_canonical(msr->data, vcpu_virt_addr_bits(vcpu));
  1136. }
  1137. return kvm_x86_ops->set_msr(vcpu, msr);
  1138. }
  1139. EXPORT_SYMBOL_GPL(kvm_set_msr);
  1140. /*
  1141. * Adapt set_msr() to msr_io()'s calling convention
  1142. */
  1143. static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1144. {
  1145. struct msr_data msr;
  1146. int r;
  1147. msr.index = index;
  1148. msr.host_initiated = true;
  1149. r = kvm_get_msr(vcpu, &msr);
  1150. if (r)
  1151. return r;
  1152. *data = msr.data;
  1153. return 0;
  1154. }
  1155. static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
  1156. {
  1157. struct msr_data msr;
  1158. msr.data = *data;
  1159. msr.index = index;
  1160. msr.host_initiated = true;
  1161. return kvm_set_msr(vcpu, &msr);
  1162. }
  1163. #ifdef CONFIG_X86_64
  1164. struct pvclock_gtod_data {
  1165. seqcount_t seq;
  1166. struct { /* extract of a clocksource struct */
  1167. int vclock_mode;
  1168. u64 cycle_last;
  1169. u64 mask;
  1170. u32 mult;
  1171. u32 shift;
  1172. } clock;
  1173. u64 boot_ns;
  1174. u64 nsec_base;
  1175. u64 wall_time_sec;
  1176. };
  1177. static struct pvclock_gtod_data pvclock_gtod_data;
  1178. static void update_pvclock_gtod(struct timekeeper *tk)
  1179. {
  1180. struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
  1181. u64 boot_ns;
  1182. boot_ns = ktime_to_ns(ktime_add(tk->tkr_mono.base, tk->offs_boot));
  1183. write_seqcount_begin(&vdata->seq);
  1184. /* copy pvclock gtod data */
  1185. vdata->clock.vclock_mode = tk->tkr_mono.clock->archdata.vclock_mode;
  1186. vdata->clock.cycle_last = tk->tkr_mono.cycle_last;
  1187. vdata->clock.mask = tk->tkr_mono.mask;
  1188. vdata->clock.mult = tk->tkr_mono.mult;
  1189. vdata->clock.shift = tk->tkr_mono.shift;
  1190. vdata->boot_ns = boot_ns;
  1191. vdata->nsec_base = tk->tkr_mono.xtime_nsec;
  1192. vdata->wall_time_sec = tk->xtime_sec;
  1193. write_seqcount_end(&vdata->seq);
  1194. }
  1195. #endif
  1196. void kvm_set_pending_timer(struct kvm_vcpu *vcpu)
  1197. {
  1198. /*
  1199. * Note: KVM_REQ_PENDING_TIMER is implicitly checked in
  1200. * vcpu_enter_guest. This function is only called from
  1201. * the physical CPU that is running vcpu.
  1202. */
  1203. kvm_make_request(KVM_REQ_PENDING_TIMER, vcpu);
  1204. }
  1205. static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
  1206. {
  1207. int version;
  1208. int r;
  1209. struct pvclock_wall_clock wc;
  1210. struct timespec64 boot;
  1211. if (!wall_clock)
  1212. return;
  1213. r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
  1214. if (r)
  1215. return;
  1216. if (version & 1)
  1217. ++version; /* first time write, random junk */
  1218. ++version;
  1219. if (kvm_write_guest(kvm, wall_clock, &version, sizeof(version)))
  1220. return;
  1221. /*
  1222. * The guest calculates current wall clock time by adding
  1223. * system time (updated by kvm_guest_time_update below) to the
  1224. * wall clock specified here. guest system time equals host
  1225. * system time for us, thus we must fill in host boot time here.
  1226. */
  1227. getboottime64(&boot);
  1228. if (kvm->arch.kvmclock_offset) {
  1229. struct timespec64 ts = ns_to_timespec64(kvm->arch.kvmclock_offset);
  1230. boot = timespec64_sub(boot, ts);
  1231. }
  1232. wc.sec = (u32)boot.tv_sec; /* overflow in 2106 guest time */
  1233. wc.nsec = boot.tv_nsec;
  1234. wc.version = version;
  1235. kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
  1236. version++;
  1237. kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
  1238. }
  1239. static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
  1240. {
  1241. do_shl32_div32(dividend, divisor);
  1242. return dividend;
  1243. }
  1244. static void kvm_get_time_scale(uint64_t scaled_hz, uint64_t base_hz,
  1245. s8 *pshift, u32 *pmultiplier)
  1246. {
  1247. uint64_t scaled64;
  1248. int32_t shift = 0;
  1249. uint64_t tps64;
  1250. uint32_t tps32;
  1251. tps64 = base_hz;
  1252. scaled64 = scaled_hz;
  1253. while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
  1254. tps64 >>= 1;
  1255. shift--;
  1256. }
  1257. tps32 = (uint32_t)tps64;
  1258. while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
  1259. if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
  1260. scaled64 >>= 1;
  1261. else
  1262. tps32 <<= 1;
  1263. shift++;
  1264. }
  1265. *pshift = shift;
  1266. *pmultiplier = div_frac(scaled64, tps32);
  1267. pr_debug("%s: base_hz %llu => %llu, shift %d, mul %u\n",
  1268. __func__, base_hz, scaled_hz, shift, *pmultiplier);
  1269. }
  1270. #ifdef CONFIG_X86_64
  1271. static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
  1272. #endif
  1273. static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
  1274. static unsigned long max_tsc_khz;
  1275. static u32 adjust_tsc_khz(u32 khz, s32 ppm)
  1276. {
  1277. u64 v = (u64)khz * (1000000 + ppm);
  1278. do_div(v, 1000000);
  1279. return v;
  1280. }
  1281. static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
  1282. {
  1283. u64 ratio;
  1284. /* Guest TSC same frequency as host TSC? */
  1285. if (!scale) {
  1286. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1287. return 0;
  1288. }
  1289. /* TSC scaling supported? */
  1290. if (!kvm_has_tsc_control) {
  1291. if (user_tsc_khz > tsc_khz) {
  1292. vcpu->arch.tsc_catchup = 1;
  1293. vcpu->arch.tsc_always_catchup = 1;
  1294. return 0;
  1295. } else {
  1296. WARN(1, "user requested TSC rate below hardware speed\n");
  1297. return -1;
  1298. }
  1299. }
  1300. /* TSC scaling required - calculate ratio */
  1301. ratio = mul_u64_u32_div(1ULL << kvm_tsc_scaling_ratio_frac_bits,
  1302. user_tsc_khz, tsc_khz);
  1303. if (ratio == 0 || ratio >= kvm_max_tsc_scaling_ratio) {
  1304. WARN_ONCE(1, "Invalid TSC scaling ratio - virtual-tsc-khz=%u\n",
  1305. user_tsc_khz);
  1306. return -1;
  1307. }
  1308. vcpu->arch.tsc_scaling_ratio = ratio;
  1309. return 0;
  1310. }
  1311. static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
  1312. {
  1313. u32 thresh_lo, thresh_hi;
  1314. int use_scaling = 0;
  1315. /* tsc_khz can be zero if TSC calibration fails */
  1316. if (user_tsc_khz == 0) {
  1317. /* set tsc_scaling_ratio to a safe value */
  1318. vcpu->arch.tsc_scaling_ratio = kvm_default_tsc_scaling_ratio;
  1319. return -1;
  1320. }
  1321. /* Compute a scale to convert nanoseconds in TSC cycles */
  1322. kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC,
  1323. &vcpu->arch.virtual_tsc_shift,
  1324. &vcpu->arch.virtual_tsc_mult);
  1325. vcpu->arch.virtual_tsc_khz = user_tsc_khz;
  1326. /*
  1327. * Compute the variation in TSC rate which is acceptable
  1328. * within the range of tolerance and decide if the
  1329. * rate being applied is within that bounds of the hardware
  1330. * rate. If so, no scaling or compensation need be done.
  1331. */
  1332. thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
  1333. thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
  1334. if (user_tsc_khz < thresh_lo || user_tsc_khz > thresh_hi) {
  1335. pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", user_tsc_khz, thresh_lo, thresh_hi);
  1336. use_scaling = 1;
  1337. }
  1338. return set_tsc_khz(vcpu, user_tsc_khz, use_scaling);
  1339. }
  1340. static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
  1341. {
  1342. u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
  1343. vcpu->arch.virtual_tsc_mult,
  1344. vcpu->arch.virtual_tsc_shift);
  1345. tsc += vcpu->arch.this_tsc_write;
  1346. return tsc;
  1347. }
  1348. static inline int gtod_is_based_on_tsc(int mode)
  1349. {
  1350. return mode == VCLOCK_TSC || mode == VCLOCK_HVCLOCK;
  1351. }
  1352. static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
  1353. {
  1354. #ifdef CONFIG_X86_64
  1355. bool vcpus_matched;
  1356. struct kvm_arch *ka = &vcpu->kvm->arch;
  1357. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1358. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1359. atomic_read(&vcpu->kvm->online_vcpus));
  1360. /*
  1361. * Once the masterclock is enabled, always perform request in
  1362. * order to update it.
  1363. *
  1364. * In order to enable masterclock, the host clocksource must be TSC
  1365. * and the vcpus need to have matched TSCs. When that happens,
  1366. * perform request to enable masterclock.
  1367. */
  1368. if (ka->use_master_clock ||
  1369. (gtod_is_based_on_tsc(gtod->clock.vclock_mode) && vcpus_matched))
  1370. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  1371. trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
  1372. atomic_read(&vcpu->kvm->online_vcpus),
  1373. ka->use_master_clock, gtod->clock.vclock_mode);
  1374. #endif
  1375. }
  1376. static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
  1377. {
  1378. u64 curr_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
  1379. vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
  1380. }
  1381. /*
  1382. * Multiply tsc by a fixed point number represented by ratio.
  1383. *
  1384. * The most significant 64-N bits (mult) of ratio represent the
  1385. * integral part of the fixed point number; the remaining N bits
  1386. * (frac) represent the fractional part, ie. ratio represents a fixed
  1387. * point number (mult + frac * 2^(-N)).
  1388. *
  1389. * N equals to kvm_tsc_scaling_ratio_frac_bits.
  1390. */
  1391. static inline u64 __scale_tsc(u64 ratio, u64 tsc)
  1392. {
  1393. return mul_u64_u64_shr(tsc, ratio, kvm_tsc_scaling_ratio_frac_bits);
  1394. }
  1395. u64 kvm_scale_tsc(struct kvm_vcpu *vcpu, u64 tsc)
  1396. {
  1397. u64 _tsc = tsc;
  1398. u64 ratio = vcpu->arch.tsc_scaling_ratio;
  1399. if (ratio != kvm_default_tsc_scaling_ratio)
  1400. _tsc = __scale_tsc(ratio, tsc);
  1401. return _tsc;
  1402. }
  1403. EXPORT_SYMBOL_GPL(kvm_scale_tsc);
  1404. static u64 kvm_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
  1405. {
  1406. u64 tsc;
  1407. tsc = kvm_scale_tsc(vcpu, rdtsc());
  1408. return target_tsc - tsc;
  1409. }
  1410. u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
  1411. {
  1412. u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
  1413. return tsc_offset + kvm_scale_tsc(vcpu, host_tsc);
  1414. }
  1415. EXPORT_SYMBOL_GPL(kvm_read_l1_tsc);
  1416. static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
  1417. {
  1418. vcpu->arch.tsc_offset = kvm_x86_ops->write_l1_tsc_offset(vcpu, offset);
  1419. }
  1420. static inline bool kvm_check_tsc_unstable(void)
  1421. {
  1422. #ifdef CONFIG_X86_64
  1423. /*
  1424. * TSC is marked unstable when we're running on Hyper-V,
  1425. * 'TSC page' clocksource is good.
  1426. */
  1427. if (pvclock_gtod_data.clock.vclock_mode == VCLOCK_HVCLOCK)
  1428. return false;
  1429. #endif
  1430. return check_tsc_unstable();
  1431. }
  1432. void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
  1433. {
  1434. struct kvm *kvm = vcpu->kvm;
  1435. u64 offset, ns, elapsed;
  1436. unsigned long flags;
  1437. bool matched;
  1438. bool already_matched;
  1439. u64 data = msr->data;
  1440. bool synchronizing = false;
  1441. raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
  1442. offset = kvm_compute_tsc_offset(vcpu, data);
  1443. ns = ktime_get_boot_ns();
  1444. elapsed = ns - kvm->arch.last_tsc_nsec;
  1445. if (vcpu->arch.virtual_tsc_khz) {
  1446. if (data == 0 && msr->host_initiated) {
  1447. /*
  1448. * detection of vcpu initialization -- need to sync
  1449. * with other vCPUs. This particularly helps to keep
  1450. * kvm_clock stable after CPU hotplug
  1451. */
  1452. synchronizing = true;
  1453. } else {
  1454. u64 tsc_exp = kvm->arch.last_tsc_write +
  1455. nsec_to_cycles(vcpu, elapsed);
  1456. u64 tsc_hz = vcpu->arch.virtual_tsc_khz * 1000LL;
  1457. /*
  1458. * Special case: TSC write with a small delta (1 second)
  1459. * of virtual cycle time against real time is
  1460. * interpreted as an attempt to synchronize the CPU.
  1461. */
  1462. synchronizing = data < tsc_exp + tsc_hz &&
  1463. data + tsc_hz > tsc_exp;
  1464. }
  1465. }
  1466. /*
  1467. * For a reliable TSC, we can match TSC offsets, and for an unstable
  1468. * TSC, we add elapsed time in this computation. We could let the
  1469. * compensation code attempt to catch up if we fall behind, but
  1470. * it's better to try to match offsets from the beginning.
  1471. */
  1472. if (synchronizing &&
  1473. vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
  1474. if (!kvm_check_tsc_unstable()) {
  1475. offset = kvm->arch.cur_tsc_offset;
  1476. pr_debug("kvm: matched tsc offset for %llu\n", data);
  1477. } else {
  1478. u64 delta = nsec_to_cycles(vcpu, elapsed);
  1479. data += delta;
  1480. offset = kvm_compute_tsc_offset(vcpu, data);
  1481. pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
  1482. }
  1483. matched = true;
  1484. already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation);
  1485. } else {
  1486. /*
  1487. * We split periods of matched TSC writes into generations.
  1488. * For each generation, we track the original measured
  1489. * nanosecond time, offset, and write, so if TSCs are in
  1490. * sync, we can match exact offset, and if not, we can match
  1491. * exact software computation in compute_guest_tsc()
  1492. *
  1493. * These values are tracked in kvm->arch.cur_xxx variables.
  1494. */
  1495. kvm->arch.cur_tsc_generation++;
  1496. kvm->arch.cur_tsc_nsec = ns;
  1497. kvm->arch.cur_tsc_write = data;
  1498. kvm->arch.cur_tsc_offset = offset;
  1499. matched = false;
  1500. pr_debug("kvm: new tsc generation %llu, clock %llu\n",
  1501. kvm->arch.cur_tsc_generation, data);
  1502. }
  1503. /*
  1504. * We also track th most recent recorded KHZ, write and time to
  1505. * allow the matching interval to be extended at each write.
  1506. */
  1507. kvm->arch.last_tsc_nsec = ns;
  1508. kvm->arch.last_tsc_write = data;
  1509. kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
  1510. vcpu->arch.last_guest_tsc = data;
  1511. /* Keep track of which generation this VCPU has synchronized to */
  1512. vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
  1513. vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
  1514. vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
  1515. if (!msr->host_initiated && guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST))
  1516. update_ia32_tsc_adjust_msr(vcpu, offset);
  1517. kvm_vcpu_write_tsc_offset(vcpu, offset);
  1518. raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
  1519. spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
  1520. if (!matched) {
  1521. kvm->arch.nr_vcpus_matched_tsc = 0;
  1522. } else if (!already_matched) {
  1523. kvm->arch.nr_vcpus_matched_tsc++;
  1524. }
  1525. kvm_track_tsc_matching(vcpu);
  1526. spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
  1527. }
  1528. EXPORT_SYMBOL_GPL(kvm_write_tsc);
  1529. static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
  1530. s64 adjustment)
  1531. {
  1532. u64 tsc_offset = kvm_x86_ops->read_l1_tsc_offset(vcpu);
  1533. kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
  1534. }
  1535. static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
  1536. {
  1537. if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio)
  1538. WARN_ON(adjustment < 0);
  1539. adjustment = kvm_scale_tsc(vcpu, (u64) adjustment);
  1540. adjust_tsc_offset_guest(vcpu, adjustment);
  1541. }
  1542. #ifdef CONFIG_X86_64
  1543. static u64 read_tsc(void)
  1544. {
  1545. u64 ret = (u64)rdtsc_ordered();
  1546. u64 last = pvclock_gtod_data.clock.cycle_last;
  1547. if (likely(ret >= last))
  1548. return ret;
  1549. /*
  1550. * GCC likes to generate cmov here, but this branch is extremely
  1551. * predictable (it's just a function of time and the likely is
  1552. * very likely) and there's a data dependence, so force GCC
  1553. * to generate a branch instead. I don't barrier() because
  1554. * we don't actually need a barrier, and if this function
  1555. * ever gets inlined it will generate worse code.
  1556. */
  1557. asm volatile ("");
  1558. return last;
  1559. }
  1560. static inline u64 vgettsc(u64 *tsc_timestamp, int *mode)
  1561. {
  1562. long v;
  1563. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1564. u64 tsc_pg_val;
  1565. switch (gtod->clock.vclock_mode) {
  1566. case VCLOCK_HVCLOCK:
  1567. tsc_pg_val = hv_read_tsc_page_tsc(hv_get_tsc_page(),
  1568. tsc_timestamp);
  1569. if (tsc_pg_val != U64_MAX) {
  1570. /* TSC page valid */
  1571. *mode = VCLOCK_HVCLOCK;
  1572. v = (tsc_pg_val - gtod->clock.cycle_last) &
  1573. gtod->clock.mask;
  1574. } else {
  1575. /* TSC page invalid */
  1576. *mode = VCLOCK_NONE;
  1577. }
  1578. break;
  1579. case VCLOCK_TSC:
  1580. *mode = VCLOCK_TSC;
  1581. *tsc_timestamp = read_tsc();
  1582. v = (*tsc_timestamp - gtod->clock.cycle_last) &
  1583. gtod->clock.mask;
  1584. break;
  1585. default:
  1586. *mode = VCLOCK_NONE;
  1587. }
  1588. if (*mode == VCLOCK_NONE)
  1589. *tsc_timestamp = v = 0;
  1590. return v * gtod->clock.mult;
  1591. }
  1592. static int do_monotonic_boot(s64 *t, u64 *tsc_timestamp)
  1593. {
  1594. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1595. unsigned long seq;
  1596. int mode;
  1597. u64 ns;
  1598. do {
  1599. seq = read_seqcount_begin(&gtod->seq);
  1600. ns = gtod->nsec_base;
  1601. ns += vgettsc(tsc_timestamp, &mode);
  1602. ns >>= gtod->clock.shift;
  1603. ns += gtod->boot_ns;
  1604. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1605. *t = ns;
  1606. return mode;
  1607. }
  1608. static int do_realtime(struct timespec64 *ts, u64 *tsc_timestamp)
  1609. {
  1610. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  1611. unsigned long seq;
  1612. int mode;
  1613. u64 ns;
  1614. do {
  1615. seq = read_seqcount_begin(&gtod->seq);
  1616. ts->tv_sec = gtod->wall_time_sec;
  1617. ns = gtod->nsec_base;
  1618. ns += vgettsc(tsc_timestamp, &mode);
  1619. ns >>= gtod->clock.shift;
  1620. } while (unlikely(read_seqcount_retry(&gtod->seq, seq)));
  1621. ts->tv_sec += __iter_div_u64_rem(ns, NSEC_PER_SEC, &ns);
  1622. ts->tv_nsec = ns;
  1623. return mode;
  1624. }
  1625. /* returns true if host is using TSC based clocksource */
  1626. static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp)
  1627. {
  1628. /* checked again under seqlock below */
  1629. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  1630. return false;
  1631. return gtod_is_based_on_tsc(do_monotonic_boot(kernel_ns,
  1632. tsc_timestamp));
  1633. }
  1634. /* returns true if host is using TSC based clocksource */
  1635. static bool kvm_get_walltime_and_clockread(struct timespec64 *ts,
  1636. u64 *tsc_timestamp)
  1637. {
  1638. /* checked again under seqlock below */
  1639. if (!gtod_is_based_on_tsc(pvclock_gtod_data.clock.vclock_mode))
  1640. return false;
  1641. return gtod_is_based_on_tsc(do_realtime(ts, tsc_timestamp));
  1642. }
  1643. #endif
  1644. /*
  1645. *
  1646. * Assuming a stable TSC across physical CPUS, and a stable TSC
  1647. * across virtual CPUs, the following condition is possible.
  1648. * Each numbered line represents an event visible to both
  1649. * CPUs at the next numbered event.
  1650. *
  1651. * "timespecX" represents host monotonic time. "tscX" represents
  1652. * RDTSC value.
  1653. *
  1654. * VCPU0 on CPU0 | VCPU1 on CPU1
  1655. *
  1656. * 1. read timespec0,tsc0
  1657. * 2. | timespec1 = timespec0 + N
  1658. * | tsc1 = tsc0 + M
  1659. * 3. transition to guest | transition to guest
  1660. * 4. ret0 = timespec0 + (rdtsc - tsc0) |
  1661. * 5. | ret1 = timespec1 + (rdtsc - tsc1)
  1662. * | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
  1663. *
  1664. * Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
  1665. *
  1666. * - ret0 < ret1
  1667. * - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
  1668. * ...
  1669. * - 0 < N - M => M < N
  1670. *
  1671. * That is, when timespec0 != timespec1, M < N. Unfortunately that is not
  1672. * always the case (the difference between two distinct xtime instances
  1673. * might be smaller then the difference between corresponding TSC reads,
  1674. * when updating guest vcpus pvclock areas).
  1675. *
  1676. * To avoid that problem, do not allow visibility of distinct
  1677. * system_timestamp/tsc_timestamp values simultaneously: use a master
  1678. * copy of host monotonic time values. Update that master copy
  1679. * in lockstep.
  1680. *
  1681. * Rely on synchronization of host TSCs and guest TSCs for monotonicity.
  1682. *
  1683. */
  1684. static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
  1685. {
  1686. #ifdef CONFIG_X86_64
  1687. struct kvm_arch *ka = &kvm->arch;
  1688. int vclock_mode;
  1689. bool host_tsc_clocksource, vcpus_matched;
  1690. vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
  1691. atomic_read(&kvm->online_vcpus));
  1692. /*
  1693. * If the host uses TSC clock, then passthrough TSC as stable
  1694. * to the guest.
  1695. */
  1696. host_tsc_clocksource = kvm_get_time_and_clockread(
  1697. &ka->master_kernel_ns,
  1698. &ka->master_cycle_now);
  1699. ka->use_master_clock = host_tsc_clocksource && vcpus_matched
  1700. && !ka->backwards_tsc_observed
  1701. && !ka->boot_vcpu_runs_old_kvmclock;
  1702. if (ka->use_master_clock)
  1703. atomic_set(&kvm_guest_has_master_clock, 1);
  1704. vclock_mode = pvclock_gtod_data.clock.vclock_mode;
  1705. trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
  1706. vcpus_matched);
  1707. #endif
  1708. }
  1709. void kvm_make_mclock_inprogress_request(struct kvm *kvm)
  1710. {
  1711. kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
  1712. }
  1713. static void kvm_gen_update_masterclock(struct kvm *kvm)
  1714. {
  1715. #ifdef CONFIG_X86_64
  1716. int i;
  1717. struct kvm_vcpu *vcpu;
  1718. struct kvm_arch *ka = &kvm->arch;
  1719. spin_lock(&ka->pvclock_gtod_sync_lock);
  1720. kvm_make_mclock_inprogress_request(kvm);
  1721. /* no guest entries from this point */
  1722. pvclock_update_vm_gtod_copy(kvm);
  1723. kvm_for_each_vcpu(i, vcpu, kvm)
  1724. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1725. /* guest entries allowed */
  1726. kvm_for_each_vcpu(i, vcpu, kvm)
  1727. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  1728. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1729. #endif
  1730. }
  1731. u64 get_kvmclock_ns(struct kvm *kvm)
  1732. {
  1733. struct kvm_arch *ka = &kvm->arch;
  1734. struct pvclock_vcpu_time_info hv_clock;
  1735. u64 ret;
  1736. spin_lock(&ka->pvclock_gtod_sync_lock);
  1737. if (!ka->use_master_clock) {
  1738. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1739. return ktime_get_boot_ns() + ka->kvmclock_offset;
  1740. }
  1741. hv_clock.tsc_timestamp = ka->master_cycle_now;
  1742. hv_clock.system_time = ka->master_kernel_ns + ka->kvmclock_offset;
  1743. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1744. /* both __this_cpu_read() and rdtsc() should be on the same cpu */
  1745. get_cpu();
  1746. if (__this_cpu_read(cpu_tsc_khz)) {
  1747. kvm_get_time_scale(NSEC_PER_SEC, __this_cpu_read(cpu_tsc_khz) * 1000LL,
  1748. &hv_clock.tsc_shift,
  1749. &hv_clock.tsc_to_system_mul);
  1750. ret = __pvclock_read_cycles(&hv_clock, rdtsc());
  1751. } else
  1752. ret = ktime_get_boot_ns() + ka->kvmclock_offset;
  1753. put_cpu();
  1754. return ret;
  1755. }
  1756. static void kvm_setup_pvclock_page(struct kvm_vcpu *v)
  1757. {
  1758. struct kvm_vcpu_arch *vcpu = &v->arch;
  1759. struct pvclock_vcpu_time_info guest_hv_clock;
  1760. if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
  1761. &guest_hv_clock, sizeof(guest_hv_clock))))
  1762. return;
  1763. /* This VCPU is paused, but it's legal for a guest to read another
  1764. * VCPU's kvmclock, so we really have to follow the specification where
  1765. * it says that version is odd if data is being modified, and even after
  1766. * it is consistent.
  1767. *
  1768. * Version field updates must be kept separate. This is because
  1769. * kvm_write_guest_cached might use a "rep movs" instruction, and
  1770. * writes within a string instruction are weakly ordered. So there
  1771. * are three writes overall.
  1772. *
  1773. * As a small optimization, only write the version field in the first
  1774. * and third write. The vcpu->pv_time cache is still valid, because the
  1775. * version field is the first in the struct.
  1776. */
  1777. BUILD_BUG_ON(offsetof(struct pvclock_vcpu_time_info, version) != 0);
  1778. if (guest_hv_clock.version & 1)
  1779. ++guest_hv_clock.version; /* first time write, random junk */
  1780. vcpu->hv_clock.version = guest_hv_clock.version + 1;
  1781. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1782. &vcpu->hv_clock,
  1783. sizeof(vcpu->hv_clock.version));
  1784. smp_wmb();
  1785. /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
  1786. vcpu->hv_clock.flags |= (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
  1787. if (vcpu->pvclock_set_guest_stopped_request) {
  1788. vcpu->hv_clock.flags |= PVCLOCK_GUEST_STOPPED;
  1789. vcpu->pvclock_set_guest_stopped_request = false;
  1790. }
  1791. trace_kvm_pvclock_update(v->vcpu_id, &vcpu->hv_clock);
  1792. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1793. &vcpu->hv_clock,
  1794. sizeof(vcpu->hv_clock));
  1795. smp_wmb();
  1796. vcpu->hv_clock.version++;
  1797. kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
  1798. &vcpu->hv_clock,
  1799. sizeof(vcpu->hv_clock.version));
  1800. }
  1801. static int kvm_guest_time_update(struct kvm_vcpu *v)
  1802. {
  1803. unsigned long flags, tgt_tsc_khz;
  1804. struct kvm_vcpu_arch *vcpu = &v->arch;
  1805. struct kvm_arch *ka = &v->kvm->arch;
  1806. s64 kernel_ns;
  1807. u64 tsc_timestamp, host_tsc;
  1808. u8 pvclock_flags;
  1809. bool use_master_clock;
  1810. kernel_ns = 0;
  1811. host_tsc = 0;
  1812. /*
  1813. * If the host uses TSC clock, then passthrough TSC as stable
  1814. * to the guest.
  1815. */
  1816. spin_lock(&ka->pvclock_gtod_sync_lock);
  1817. use_master_clock = ka->use_master_clock;
  1818. if (use_master_clock) {
  1819. host_tsc = ka->master_cycle_now;
  1820. kernel_ns = ka->master_kernel_ns;
  1821. }
  1822. spin_unlock(&ka->pvclock_gtod_sync_lock);
  1823. /* Keep irq disabled to prevent changes to the clock */
  1824. local_irq_save(flags);
  1825. tgt_tsc_khz = __this_cpu_read(cpu_tsc_khz);
  1826. if (unlikely(tgt_tsc_khz == 0)) {
  1827. local_irq_restore(flags);
  1828. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1829. return 1;
  1830. }
  1831. if (!use_master_clock) {
  1832. host_tsc = rdtsc();
  1833. kernel_ns = ktime_get_boot_ns();
  1834. }
  1835. tsc_timestamp = kvm_read_l1_tsc(v, host_tsc);
  1836. /*
  1837. * We may have to catch up the TSC to match elapsed wall clock
  1838. * time for two reasons, even if kvmclock is used.
  1839. * 1) CPU could have been running below the maximum TSC rate
  1840. * 2) Broken TSC compensation resets the base at each VCPU
  1841. * entry to avoid unknown leaps of TSC even when running
  1842. * again on the same CPU. This may cause apparent elapsed
  1843. * time to disappear, and the guest to stand still or run
  1844. * very slowly.
  1845. */
  1846. if (vcpu->tsc_catchup) {
  1847. u64 tsc = compute_guest_tsc(v, kernel_ns);
  1848. if (tsc > tsc_timestamp) {
  1849. adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
  1850. tsc_timestamp = tsc;
  1851. }
  1852. }
  1853. local_irq_restore(flags);
  1854. /* With all the info we got, fill in the values */
  1855. if (kvm_has_tsc_control)
  1856. tgt_tsc_khz = kvm_scale_tsc(v, tgt_tsc_khz);
  1857. if (unlikely(vcpu->hw_tsc_khz != tgt_tsc_khz)) {
  1858. kvm_get_time_scale(NSEC_PER_SEC, tgt_tsc_khz * 1000LL,
  1859. &vcpu->hv_clock.tsc_shift,
  1860. &vcpu->hv_clock.tsc_to_system_mul);
  1861. vcpu->hw_tsc_khz = tgt_tsc_khz;
  1862. }
  1863. vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
  1864. vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
  1865. vcpu->last_guest_tsc = tsc_timestamp;
  1866. /* If the host uses TSC clocksource, then it is stable */
  1867. pvclock_flags = 0;
  1868. if (use_master_clock)
  1869. pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
  1870. vcpu->hv_clock.flags = pvclock_flags;
  1871. if (vcpu->pv_time_enabled)
  1872. kvm_setup_pvclock_page(v);
  1873. if (v == kvm_get_vcpu(v->kvm, 0))
  1874. kvm_hv_setup_tsc_page(v->kvm, &vcpu->hv_clock);
  1875. return 0;
  1876. }
  1877. /*
  1878. * kvmclock updates which are isolated to a given vcpu, such as
  1879. * vcpu->cpu migration, should not allow system_timestamp from
  1880. * the rest of the vcpus to remain static. Otherwise ntp frequency
  1881. * correction applies to one vcpu's system_timestamp but not
  1882. * the others.
  1883. *
  1884. * So in those cases, request a kvmclock update for all vcpus.
  1885. * We need to rate-limit these requests though, as they can
  1886. * considerably slow guests that have a large number of vcpus.
  1887. * The time for a remote vcpu to update its kvmclock is bound
  1888. * by the delay we use to rate-limit the updates.
  1889. */
  1890. #define KVMCLOCK_UPDATE_DELAY msecs_to_jiffies(100)
  1891. static void kvmclock_update_fn(struct work_struct *work)
  1892. {
  1893. int i;
  1894. struct delayed_work *dwork = to_delayed_work(work);
  1895. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1896. kvmclock_update_work);
  1897. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1898. struct kvm_vcpu *vcpu;
  1899. kvm_for_each_vcpu(i, vcpu, kvm) {
  1900. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  1901. kvm_vcpu_kick(vcpu);
  1902. }
  1903. }
  1904. static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
  1905. {
  1906. struct kvm *kvm = v->kvm;
  1907. kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
  1908. schedule_delayed_work(&kvm->arch.kvmclock_update_work,
  1909. KVMCLOCK_UPDATE_DELAY);
  1910. }
  1911. #define KVMCLOCK_SYNC_PERIOD (300 * HZ)
  1912. static void kvmclock_sync_fn(struct work_struct *work)
  1913. {
  1914. struct delayed_work *dwork = to_delayed_work(work);
  1915. struct kvm_arch *ka = container_of(dwork, struct kvm_arch,
  1916. kvmclock_sync_work);
  1917. struct kvm *kvm = container_of(ka, struct kvm, arch);
  1918. if (!kvmclock_periodic_sync)
  1919. return;
  1920. schedule_delayed_work(&kvm->arch.kvmclock_update_work, 0);
  1921. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  1922. KVMCLOCK_SYNC_PERIOD);
  1923. }
  1924. static int set_msr_mce(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  1925. {
  1926. u64 mcg_cap = vcpu->arch.mcg_cap;
  1927. unsigned bank_num = mcg_cap & 0xff;
  1928. u32 msr = msr_info->index;
  1929. u64 data = msr_info->data;
  1930. switch (msr) {
  1931. case MSR_IA32_MCG_STATUS:
  1932. vcpu->arch.mcg_status = data;
  1933. break;
  1934. case MSR_IA32_MCG_CTL:
  1935. if (!(mcg_cap & MCG_CTL_P) &&
  1936. (data || !msr_info->host_initiated))
  1937. return 1;
  1938. if (data != 0 && data != ~(u64)0)
  1939. return 1;
  1940. vcpu->arch.mcg_ctl = data;
  1941. break;
  1942. default:
  1943. if (msr >= MSR_IA32_MC0_CTL &&
  1944. msr < MSR_IA32_MCx_CTL(bank_num)) {
  1945. u32 offset = msr - MSR_IA32_MC0_CTL;
  1946. /* only 0 or all 1s can be written to IA32_MCi_CTL
  1947. * some Linux kernels though clear bit 10 in bank 4 to
  1948. * workaround a BIOS/GART TBL issue on AMD K8s, ignore
  1949. * this to avoid an uncatched #GP in the guest
  1950. */
  1951. if ((offset & 0x3) == 0 &&
  1952. data != 0 && (data | (1 << 10)) != ~(u64)0)
  1953. return -1;
  1954. if (!msr_info->host_initiated &&
  1955. (offset & 0x3) == 1 && data != 0)
  1956. return -1;
  1957. vcpu->arch.mce_banks[offset] = data;
  1958. break;
  1959. }
  1960. return 1;
  1961. }
  1962. return 0;
  1963. }
  1964. static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
  1965. {
  1966. struct kvm *kvm = vcpu->kvm;
  1967. int lm = is_long_mode(vcpu);
  1968. u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
  1969. : (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
  1970. u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
  1971. : kvm->arch.xen_hvm_config.blob_size_32;
  1972. u32 page_num = data & ~PAGE_MASK;
  1973. u64 page_addr = data & PAGE_MASK;
  1974. u8 *page;
  1975. int r;
  1976. r = -E2BIG;
  1977. if (page_num >= blob_size)
  1978. goto out;
  1979. r = -ENOMEM;
  1980. page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
  1981. if (IS_ERR(page)) {
  1982. r = PTR_ERR(page);
  1983. goto out;
  1984. }
  1985. if (kvm_vcpu_write_guest(vcpu, page_addr, page, PAGE_SIZE))
  1986. goto out_free;
  1987. r = 0;
  1988. out_free:
  1989. kfree(page);
  1990. out:
  1991. return r;
  1992. }
  1993. static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
  1994. {
  1995. gpa_t gpa = data & ~0x3f;
  1996. /* Bits 3:5 are reserved, Should be zero */
  1997. if (data & 0x38)
  1998. return 1;
  1999. vcpu->arch.apf.msr_val = data;
  2000. if (!(data & KVM_ASYNC_PF_ENABLED)) {
  2001. kvm_clear_async_pf_completion_queue(vcpu);
  2002. kvm_async_pf_hash_reset(vcpu);
  2003. return 0;
  2004. }
  2005. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
  2006. sizeof(u32)))
  2007. return 1;
  2008. vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
  2009. vcpu->arch.apf.delivery_as_pf_vmexit = data & KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
  2010. kvm_async_pf_wakeup_all(vcpu);
  2011. return 0;
  2012. }
  2013. static void kvmclock_reset(struct kvm_vcpu *vcpu)
  2014. {
  2015. vcpu->arch.pv_time_enabled = false;
  2016. }
  2017. static void kvm_vcpu_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
  2018. {
  2019. ++vcpu->stat.tlb_flush;
  2020. kvm_x86_ops->tlb_flush(vcpu, invalidate_gpa);
  2021. }
  2022. static void record_steal_time(struct kvm_vcpu *vcpu)
  2023. {
  2024. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  2025. return;
  2026. if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2027. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
  2028. return;
  2029. /*
  2030. * Doing a TLB flush here, on the guest's behalf, can avoid
  2031. * expensive IPIs.
  2032. */
  2033. if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
  2034. kvm_vcpu_flush_tlb(vcpu, false);
  2035. if (vcpu->arch.st.steal.version & 1)
  2036. vcpu->arch.st.steal.version += 1; /* first time write, random junk */
  2037. vcpu->arch.st.steal.version += 1;
  2038. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2039. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  2040. smp_wmb();
  2041. vcpu->arch.st.steal.steal += current->sched_info.run_delay -
  2042. vcpu->arch.st.last_steal;
  2043. vcpu->arch.st.last_steal = current->sched_info.run_delay;
  2044. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2045. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  2046. smp_wmb();
  2047. vcpu->arch.st.steal.version += 1;
  2048. kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2049. &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
  2050. }
  2051. int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  2052. {
  2053. bool pr = false;
  2054. u32 msr = msr_info->index;
  2055. u64 data = msr_info->data;
  2056. switch (msr) {
  2057. case MSR_AMD64_NB_CFG:
  2058. case MSR_IA32_UCODE_WRITE:
  2059. case MSR_VM_HSAVE_PA:
  2060. case MSR_AMD64_PATCH_LOADER:
  2061. case MSR_AMD64_BU_CFG2:
  2062. case MSR_AMD64_DC_CFG:
  2063. break;
  2064. case MSR_IA32_UCODE_REV:
  2065. if (msr_info->host_initiated)
  2066. vcpu->arch.microcode_version = data;
  2067. break;
  2068. case MSR_EFER:
  2069. return set_efer(vcpu, data);
  2070. case MSR_K7_HWCR:
  2071. data &= ~(u64)0x40; /* ignore flush filter disable */
  2072. data &= ~(u64)0x100; /* ignore ignne emulation enable */
  2073. data &= ~(u64)0x8; /* ignore TLB cache disable */
  2074. data &= ~(u64)0x40000; /* ignore Mc status write enable */
  2075. if (data != 0) {
  2076. vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
  2077. data);
  2078. return 1;
  2079. }
  2080. break;
  2081. case MSR_FAM10H_MMIO_CONF_BASE:
  2082. if (data != 0) {
  2083. vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
  2084. "0x%llx\n", data);
  2085. return 1;
  2086. }
  2087. break;
  2088. case MSR_IA32_DEBUGCTLMSR:
  2089. if (!data) {
  2090. /* We support the non-activated case already */
  2091. break;
  2092. } else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
  2093. /* Values other than LBR and BTF are vendor-specific,
  2094. thus reserved and should throw a #GP */
  2095. return 1;
  2096. }
  2097. vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
  2098. __func__, data);
  2099. break;
  2100. case 0x200 ... 0x2ff:
  2101. return kvm_mtrr_set_msr(vcpu, msr, data);
  2102. case MSR_IA32_APICBASE:
  2103. return kvm_set_apic_base(vcpu, msr_info);
  2104. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2105. return kvm_x2apic_msr_write(vcpu, msr, data);
  2106. case MSR_IA32_TSCDEADLINE:
  2107. kvm_set_lapic_tscdeadline_msr(vcpu, data);
  2108. break;
  2109. case MSR_IA32_TSC_ADJUST:
  2110. if (guest_cpuid_has(vcpu, X86_FEATURE_TSC_ADJUST)) {
  2111. if (!msr_info->host_initiated) {
  2112. s64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
  2113. adjust_tsc_offset_guest(vcpu, adj);
  2114. }
  2115. vcpu->arch.ia32_tsc_adjust_msr = data;
  2116. }
  2117. break;
  2118. case MSR_IA32_MISC_ENABLE:
  2119. vcpu->arch.ia32_misc_enable_msr = data;
  2120. break;
  2121. case MSR_IA32_SMBASE:
  2122. if (!msr_info->host_initiated)
  2123. return 1;
  2124. vcpu->arch.smbase = data;
  2125. break;
  2126. case MSR_IA32_TSC:
  2127. kvm_write_tsc(vcpu, msr_info);
  2128. break;
  2129. case MSR_SMI_COUNT:
  2130. if (!msr_info->host_initiated)
  2131. return 1;
  2132. vcpu->arch.smi_count = data;
  2133. break;
  2134. case MSR_KVM_WALL_CLOCK_NEW:
  2135. case MSR_KVM_WALL_CLOCK:
  2136. vcpu->kvm->arch.wall_clock = data;
  2137. kvm_write_wall_clock(vcpu->kvm, data);
  2138. break;
  2139. case MSR_KVM_SYSTEM_TIME_NEW:
  2140. case MSR_KVM_SYSTEM_TIME: {
  2141. struct kvm_arch *ka = &vcpu->kvm->arch;
  2142. kvmclock_reset(vcpu);
  2143. if (vcpu->vcpu_id == 0 && !msr_info->host_initiated) {
  2144. bool tmp = (msr == MSR_KVM_SYSTEM_TIME);
  2145. if (ka->boot_vcpu_runs_old_kvmclock != tmp)
  2146. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  2147. ka->boot_vcpu_runs_old_kvmclock = tmp;
  2148. }
  2149. vcpu->arch.time = data;
  2150. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  2151. /* we verify if the enable bit is set... */
  2152. if (!(data & 1))
  2153. break;
  2154. if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
  2155. &vcpu->arch.pv_time, data & ~1ULL,
  2156. sizeof(struct pvclock_vcpu_time_info)))
  2157. vcpu->arch.pv_time_enabled = false;
  2158. else
  2159. vcpu->arch.pv_time_enabled = true;
  2160. break;
  2161. }
  2162. case MSR_KVM_ASYNC_PF_EN:
  2163. if (kvm_pv_enable_async_pf(vcpu, data))
  2164. return 1;
  2165. break;
  2166. case MSR_KVM_STEAL_TIME:
  2167. if (unlikely(!sched_info_on()))
  2168. return 1;
  2169. if (data & KVM_STEAL_RESERVED_MASK)
  2170. return 1;
  2171. if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
  2172. data & KVM_STEAL_VALID_BITS,
  2173. sizeof(struct kvm_steal_time)))
  2174. return 1;
  2175. vcpu->arch.st.msr_val = data;
  2176. if (!(data & KVM_MSR_ENABLED))
  2177. break;
  2178. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2179. break;
  2180. case MSR_KVM_PV_EOI_EN:
  2181. if (kvm_lapic_enable_pv_eoi(vcpu, data, sizeof(u8)))
  2182. return 1;
  2183. break;
  2184. case MSR_IA32_MCG_CTL:
  2185. case MSR_IA32_MCG_STATUS:
  2186. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2187. return set_msr_mce(vcpu, msr_info);
  2188. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  2189. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  2190. pr = true; /* fall through */
  2191. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  2192. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  2193. if (kvm_pmu_is_valid_msr(vcpu, msr))
  2194. return kvm_pmu_set_msr(vcpu, msr_info);
  2195. if (pr || data != 0)
  2196. vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
  2197. "0x%x data 0x%llx\n", msr, data);
  2198. break;
  2199. case MSR_K7_CLK_CTL:
  2200. /*
  2201. * Ignore all writes to this no longer documented MSR.
  2202. * Writes are only relevant for old K7 processors,
  2203. * all pre-dating SVM, but a recommended workaround from
  2204. * AMD for these chips. It is possible to specify the
  2205. * affected processor models on the command line, hence
  2206. * the need to ignore the workaround.
  2207. */
  2208. break;
  2209. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2210. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  2211. case HV_X64_MSR_CRASH_CTL:
  2212. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  2213. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  2214. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  2215. case HV_X64_MSR_TSC_EMULATION_STATUS:
  2216. return kvm_hv_set_msr_common(vcpu, msr, data,
  2217. msr_info->host_initiated);
  2218. case MSR_IA32_BBL_CR_CTL3:
  2219. /* Drop writes to this legacy MSR -- see rdmsr
  2220. * counterpart for further detail.
  2221. */
  2222. if (report_ignored_msrs)
  2223. vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data 0x%llx\n",
  2224. msr, data);
  2225. break;
  2226. case MSR_AMD64_OSVW_ID_LENGTH:
  2227. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2228. return 1;
  2229. vcpu->arch.osvw.length = data;
  2230. break;
  2231. case MSR_AMD64_OSVW_STATUS:
  2232. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2233. return 1;
  2234. vcpu->arch.osvw.status = data;
  2235. break;
  2236. case MSR_PLATFORM_INFO:
  2237. if (!msr_info->host_initiated ||
  2238. (!(data & MSR_PLATFORM_INFO_CPUID_FAULT) &&
  2239. cpuid_fault_enabled(vcpu)))
  2240. return 1;
  2241. vcpu->arch.msr_platform_info = data;
  2242. break;
  2243. case MSR_MISC_FEATURES_ENABLES:
  2244. if (data & ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT ||
  2245. (data & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
  2246. !supports_cpuid_fault(vcpu)))
  2247. return 1;
  2248. vcpu->arch.msr_misc_features_enables = data;
  2249. break;
  2250. default:
  2251. if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
  2252. return xen_hvm_config(vcpu, data);
  2253. if (kvm_pmu_is_valid_msr(vcpu, msr))
  2254. return kvm_pmu_set_msr(vcpu, msr_info);
  2255. if (!ignore_msrs) {
  2256. vcpu_debug_ratelimited(vcpu, "unhandled wrmsr: 0x%x data 0x%llx\n",
  2257. msr, data);
  2258. return 1;
  2259. } else {
  2260. if (report_ignored_msrs)
  2261. vcpu_unimpl(vcpu,
  2262. "ignored wrmsr: 0x%x data 0x%llx\n",
  2263. msr, data);
  2264. break;
  2265. }
  2266. }
  2267. return 0;
  2268. }
  2269. EXPORT_SYMBOL_GPL(kvm_set_msr_common);
  2270. /*
  2271. * Reads an msr value (of 'msr_index') into 'pdata'.
  2272. * Returns 0 on success, non-0 otherwise.
  2273. * Assumes vcpu_load() was already called.
  2274. */
  2275. int kvm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
  2276. {
  2277. return kvm_x86_ops->get_msr(vcpu, msr);
  2278. }
  2279. EXPORT_SYMBOL_GPL(kvm_get_msr);
  2280. static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
  2281. {
  2282. u64 data;
  2283. u64 mcg_cap = vcpu->arch.mcg_cap;
  2284. unsigned bank_num = mcg_cap & 0xff;
  2285. switch (msr) {
  2286. case MSR_IA32_P5_MC_ADDR:
  2287. case MSR_IA32_P5_MC_TYPE:
  2288. data = 0;
  2289. break;
  2290. case MSR_IA32_MCG_CAP:
  2291. data = vcpu->arch.mcg_cap;
  2292. break;
  2293. case MSR_IA32_MCG_CTL:
  2294. if (!(mcg_cap & MCG_CTL_P) && !host)
  2295. return 1;
  2296. data = vcpu->arch.mcg_ctl;
  2297. break;
  2298. case MSR_IA32_MCG_STATUS:
  2299. data = vcpu->arch.mcg_status;
  2300. break;
  2301. default:
  2302. if (msr >= MSR_IA32_MC0_CTL &&
  2303. msr < MSR_IA32_MCx_CTL(bank_num)) {
  2304. u32 offset = msr - MSR_IA32_MC0_CTL;
  2305. data = vcpu->arch.mce_banks[offset];
  2306. break;
  2307. }
  2308. return 1;
  2309. }
  2310. *pdata = data;
  2311. return 0;
  2312. }
  2313. int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  2314. {
  2315. switch (msr_info->index) {
  2316. case MSR_IA32_PLATFORM_ID:
  2317. case MSR_IA32_EBL_CR_POWERON:
  2318. case MSR_IA32_DEBUGCTLMSR:
  2319. case MSR_IA32_LASTBRANCHFROMIP:
  2320. case MSR_IA32_LASTBRANCHTOIP:
  2321. case MSR_IA32_LASTINTFROMIP:
  2322. case MSR_IA32_LASTINTTOIP:
  2323. case MSR_K8_SYSCFG:
  2324. case MSR_K8_TSEG_ADDR:
  2325. case MSR_K8_TSEG_MASK:
  2326. case MSR_K7_HWCR:
  2327. case MSR_VM_HSAVE_PA:
  2328. case MSR_K8_INT_PENDING_MSG:
  2329. case MSR_AMD64_NB_CFG:
  2330. case MSR_FAM10H_MMIO_CONF_BASE:
  2331. case MSR_AMD64_BU_CFG2:
  2332. case MSR_IA32_PERF_CTL:
  2333. case MSR_AMD64_DC_CFG:
  2334. msr_info->data = 0;
  2335. break;
  2336. case MSR_F15H_PERF_CTL0 ... MSR_F15H_PERF_CTR5:
  2337. case MSR_K7_EVNTSEL0 ... MSR_K7_EVNTSEL3:
  2338. case MSR_K7_PERFCTR0 ... MSR_K7_PERFCTR3:
  2339. case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR1:
  2340. case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL1:
  2341. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2342. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2343. msr_info->data = 0;
  2344. break;
  2345. case MSR_IA32_UCODE_REV:
  2346. msr_info->data = vcpu->arch.microcode_version;
  2347. break;
  2348. case MSR_IA32_TSC:
  2349. msr_info->data = kvm_scale_tsc(vcpu, rdtsc()) + vcpu->arch.tsc_offset;
  2350. break;
  2351. case MSR_MTRRcap:
  2352. case 0x200 ... 0x2ff:
  2353. return kvm_mtrr_get_msr(vcpu, msr_info->index, &msr_info->data);
  2354. case 0xcd: /* fsb frequency */
  2355. msr_info->data = 3;
  2356. break;
  2357. /*
  2358. * MSR_EBC_FREQUENCY_ID
  2359. * Conservative value valid for even the basic CPU models.
  2360. * Models 0,1: 000 in bits 23:21 indicating a bus speed of
  2361. * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
  2362. * and 266MHz for model 3, or 4. Set Core Clock
  2363. * Frequency to System Bus Frequency Ratio to 1 (bits
  2364. * 31:24) even though these are only valid for CPU
  2365. * models > 2, however guests may end up dividing or
  2366. * multiplying by zero otherwise.
  2367. */
  2368. case MSR_EBC_FREQUENCY_ID:
  2369. msr_info->data = 1 << 24;
  2370. break;
  2371. case MSR_IA32_APICBASE:
  2372. msr_info->data = kvm_get_apic_base(vcpu);
  2373. break;
  2374. case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
  2375. return kvm_x2apic_msr_read(vcpu, msr_info->index, &msr_info->data);
  2376. break;
  2377. case MSR_IA32_TSCDEADLINE:
  2378. msr_info->data = kvm_get_lapic_tscdeadline_msr(vcpu);
  2379. break;
  2380. case MSR_IA32_TSC_ADJUST:
  2381. msr_info->data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
  2382. break;
  2383. case MSR_IA32_MISC_ENABLE:
  2384. msr_info->data = vcpu->arch.ia32_misc_enable_msr;
  2385. break;
  2386. case MSR_IA32_SMBASE:
  2387. if (!msr_info->host_initiated)
  2388. return 1;
  2389. msr_info->data = vcpu->arch.smbase;
  2390. break;
  2391. case MSR_SMI_COUNT:
  2392. msr_info->data = vcpu->arch.smi_count;
  2393. break;
  2394. case MSR_IA32_PERF_STATUS:
  2395. /* TSC increment by tick */
  2396. msr_info->data = 1000ULL;
  2397. /* CPU multiplier */
  2398. msr_info->data |= (((uint64_t)4ULL) << 40);
  2399. break;
  2400. case MSR_EFER:
  2401. msr_info->data = vcpu->arch.efer;
  2402. break;
  2403. case MSR_KVM_WALL_CLOCK:
  2404. case MSR_KVM_WALL_CLOCK_NEW:
  2405. msr_info->data = vcpu->kvm->arch.wall_clock;
  2406. break;
  2407. case MSR_KVM_SYSTEM_TIME:
  2408. case MSR_KVM_SYSTEM_TIME_NEW:
  2409. msr_info->data = vcpu->arch.time;
  2410. break;
  2411. case MSR_KVM_ASYNC_PF_EN:
  2412. msr_info->data = vcpu->arch.apf.msr_val;
  2413. break;
  2414. case MSR_KVM_STEAL_TIME:
  2415. msr_info->data = vcpu->arch.st.msr_val;
  2416. break;
  2417. case MSR_KVM_PV_EOI_EN:
  2418. msr_info->data = vcpu->arch.pv_eoi.msr_val;
  2419. break;
  2420. case MSR_IA32_P5_MC_ADDR:
  2421. case MSR_IA32_P5_MC_TYPE:
  2422. case MSR_IA32_MCG_CAP:
  2423. case MSR_IA32_MCG_CTL:
  2424. case MSR_IA32_MCG_STATUS:
  2425. case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
  2426. return get_msr_mce(vcpu, msr_info->index, &msr_info->data,
  2427. msr_info->host_initiated);
  2428. case MSR_K7_CLK_CTL:
  2429. /*
  2430. * Provide expected ramp-up count for K7. All other
  2431. * are set to zero, indicating minimum divisors for
  2432. * every field.
  2433. *
  2434. * This prevents guest kernels on AMD host with CPU
  2435. * type 6, model 8 and higher from exploding due to
  2436. * the rdmsr failing.
  2437. */
  2438. msr_info->data = 0x20000000;
  2439. break;
  2440. case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
  2441. case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
  2442. case HV_X64_MSR_CRASH_CTL:
  2443. case HV_X64_MSR_STIMER0_CONFIG ... HV_X64_MSR_STIMER3_COUNT:
  2444. case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
  2445. case HV_X64_MSR_TSC_EMULATION_CONTROL:
  2446. case HV_X64_MSR_TSC_EMULATION_STATUS:
  2447. return kvm_hv_get_msr_common(vcpu,
  2448. msr_info->index, &msr_info->data,
  2449. msr_info->host_initiated);
  2450. break;
  2451. case MSR_IA32_BBL_CR_CTL3:
  2452. /* This legacy MSR exists but isn't fully documented in current
  2453. * silicon. It is however accessed by winxp in very narrow
  2454. * scenarios where it sets bit #19, itself documented as
  2455. * a "reserved" bit. Best effort attempt to source coherent
  2456. * read data here should the balance of the register be
  2457. * interpreted by the guest:
  2458. *
  2459. * L2 cache control register 3: 64GB range, 256KB size,
  2460. * enabled, latency 0x1, configured
  2461. */
  2462. msr_info->data = 0xbe702111;
  2463. break;
  2464. case MSR_AMD64_OSVW_ID_LENGTH:
  2465. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2466. return 1;
  2467. msr_info->data = vcpu->arch.osvw.length;
  2468. break;
  2469. case MSR_AMD64_OSVW_STATUS:
  2470. if (!guest_cpuid_has(vcpu, X86_FEATURE_OSVW))
  2471. return 1;
  2472. msr_info->data = vcpu->arch.osvw.status;
  2473. break;
  2474. case MSR_PLATFORM_INFO:
  2475. if (!msr_info->host_initiated &&
  2476. !vcpu->kvm->arch.guest_can_read_msr_platform_info)
  2477. return 1;
  2478. msr_info->data = vcpu->arch.msr_platform_info;
  2479. break;
  2480. case MSR_MISC_FEATURES_ENABLES:
  2481. msr_info->data = vcpu->arch.msr_misc_features_enables;
  2482. break;
  2483. default:
  2484. if (kvm_pmu_is_valid_msr(vcpu, msr_info->index))
  2485. return kvm_pmu_get_msr(vcpu, msr_info->index, &msr_info->data);
  2486. if (!ignore_msrs) {
  2487. vcpu_debug_ratelimited(vcpu, "unhandled rdmsr: 0x%x\n",
  2488. msr_info->index);
  2489. return 1;
  2490. } else {
  2491. if (report_ignored_msrs)
  2492. vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n",
  2493. msr_info->index);
  2494. msr_info->data = 0;
  2495. }
  2496. break;
  2497. }
  2498. return 0;
  2499. }
  2500. EXPORT_SYMBOL_GPL(kvm_get_msr_common);
  2501. /*
  2502. * Read or write a bunch of msrs. All parameters are kernel addresses.
  2503. *
  2504. * @return number of msrs set successfully.
  2505. */
  2506. static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
  2507. struct kvm_msr_entry *entries,
  2508. int (*do_msr)(struct kvm_vcpu *vcpu,
  2509. unsigned index, u64 *data))
  2510. {
  2511. int i;
  2512. for (i = 0; i < msrs->nmsrs; ++i)
  2513. if (do_msr(vcpu, entries[i].index, &entries[i].data))
  2514. break;
  2515. return i;
  2516. }
  2517. /*
  2518. * Read or write a bunch of msrs. Parameters are user addresses.
  2519. *
  2520. * @return number of msrs set successfully.
  2521. */
  2522. static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
  2523. int (*do_msr)(struct kvm_vcpu *vcpu,
  2524. unsigned index, u64 *data),
  2525. int writeback)
  2526. {
  2527. struct kvm_msrs msrs;
  2528. struct kvm_msr_entry *entries;
  2529. int r, n;
  2530. unsigned size;
  2531. r = -EFAULT;
  2532. if (copy_from_user(&msrs, user_msrs, sizeof(msrs)))
  2533. goto out;
  2534. r = -E2BIG;
  2535. if (msrs.nmsrs >= MAX_IO_MSRS)
  2536. goto out;
  2537. size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
  2538. entries = memdup_user(user_msrs->entries, size);
  2539. if (IS_ERR(entries)) {
  2540. r = PTR_ERR(entries);
  2541. goto out;
  2542. }
  2543. r = n = __msr_io(vcpu, &msrs, entries, do_msr);
  2544. if (r < 0)
  2545. goto out_free;
  2546. r = -EFAULT;
  2547. if (writeback && copy_to_user(user_msrs->entries, entries, size))
  2548. goto out_free;
  2549. r = n;
  2550. out_free:
  2551. kfree(entries);
  2552. out:
  2553. return r;
  2554. }
  2555. static inline bool kvm_can_mwait_in_guest(void)
  2556. {
  2557. return boot_cpu_has(X86_FEATURE_MWAIT) &&
  2558. !boot_cpu_has_bug(X86_BUG_MONITOR) &&
  2559. boot_cpu_has(X86_FEATURE_ARAT);
  2560. }
  2561. int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
  2562. {
  2563. int r = 0;
  2564. switch (ext) {
  2565. case KVM_CAP_IRQCHIP:
  2566. case KVM_CAP_HLT:
  2567. case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
  2568. case KVM_CAP_SET_TSS_ADDR:
  2569. case KVM_CAP_EXT_CPUID:
  2570. case KVM_CAP_EXT_EMUL_CPUID:
  2571. case KVM_CAP_CLOCKSOURCE:
  2572. case KVM_CAP_PIT:
  2573. case KVM_CAP_NOP_IO_DELAY:
  2574. case KVM_CAP_MP_STATE:
  2575. case KVM_CAP_SYNC_MMU:
  2576. case KVM_CAP_USER_NMI:
  2577. case KVM_CAP_REINJECT_CONTROL:
  2578. case KVM_CAP_IRQ_INJECT_STATUS:
  2579. case KVM_CAP_IOEVENTFD:
  2580. case KVM_CAP_IOEVENTFD_NO_LENGTH:
  2581. case KVM_CAP_PIT2:
  2582. case KVM_CAP_PIT_STATE2:
  2583. case KVM_CAP_SET_IDENTITY_MAP_ADDR:
  2584. case KVM_CAP_XEN_HVM:
  2585. case KVM_CAP_VCPU_EVENTS:
  2586. case KVM_CAP_HYPERV:
  2587. case KVM_CAP_HYPERV_VAPIC:
  2588. case KVM_CAP_HYPERV_SPIN:
  2589. case KVM_CAP_HYPERV_SYNIC:
  2590. case KVM_CAP_HYPERV_SYNIC2:
  2591. case KVM_CAP_HYPERV_VP_INDEX:
  2592. case KVM_CAP_HYPERV_EVENTFD:
  2593. case KVM_CAP_HYPERV_TLBFLUSH:
  2594. case KVM_CAP_HYPERV_SEND_IPI:
  2595. case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
  2596. case KVM_CAP_PCI_SEGMENT:
  2597. case KVM_CAP_DEBUGREGS:
  2598. case KVM_CAP_X86_ROBUST_SINGLESTEP:
  2599. case KVM_CAP_XSAVE:
  2600. case KVM_CAP_ASYNC_PF:
  2601. case KVM_CAP_GET_TSC_KHZ:
  2602. case KVM_CAP_KVMCLOCK_CTRL:
  2603. case KVM_CAP_READONLY_MEM:
  2604. case KVM_CAP_HYPERV_TIME:
  2605. case KVM_CAP_IOAPIC_POLARITY_IGNORED:
  2606. case KVM_CAP_TSC_DEADLINE_TIMER:
  2607. case KVM_CAP_ENABLE_CAP_VM:
  2608. case KVM_CAP_DISABLE_QUIRKS:
  2609. case KVM_CAP_SET_BOOT_CPU_ID:
  2610. case KVM_CAP_SPLIT_IRQCHIP:
  2611. case KVM_CAP_IMMEDIATE_EXIT:
  2612. case KVM_CAP_GET_MSR_FEATURES:
  2613. case KVM_CAP_MSR_PLATFORM_INFO:
  2614. case KVM_CAP_EXCEPTION_PAYLOAD:
  2615. r = 1;
  2616. break;
  2617. case KVM_CAP_SYNC_REGS:
  2618. r = KVM_SYNC_X86_VALID_FIELDS;
  2619. break;
  2620. case KVM_CAP_ADJUST_CLOCK:
  2621. r = KVM_CLOCK_TSC_STABLE;
  2622. break;
  2623. case KVM_CAP_X86_DISABLE_EXITS:
  2624. r |= KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_PAUSE;
  2625. if(kvm_can_mwait_in_guest())
  2626. r |= KVM_X86_DISABLE_EXITS_MWAIT;
  2627. break;
  2628. case KVM_CAP_X86_SMM:
  2629. /* SMBASE is usually relocated above 1M on modern chipsets,
  2630. * and SMM handlers might indeed rely on 4G segment limits,
  2631. * so do not report SMM to be available if real mode is
  2632. * emulated via vm86 mode. Still, do not go to great lengths
  2633. * to avoid userspace's usage of the feature, because it is a
  2634. * fringe case that is not enabled except via specific settings
  2635. * of the module parameters.
  2636. */
  2637. r = kvm_x86_ops->has_emulated_msr(MSR_IA32_SMBASE);
  2638. break;
  2639. case KVM_CAP_VAPIC:
  2640. r = !kvm_x86_ops->cpu_has_accelerated_tpr();
  2641. break;
  2642. case KVM_CAP_NR_VCPUS:
  2643. r = KVM_SOFT_MAX_VCPUS;
  2644. break;
  2645. case KVM_CAP_MAX_VCPUS:
  2646. r = KVM_MAX_VCPUS;
  2647. break;
  2648. case KVM_CAP_NR_MEMSLOTS:
  2649. r = KVM_USER_MEM_SLOTS;
  2650. break;
  2651. case KVM_CAP_PV_MMU: /* obsolete */
  2652. r = 0;
  2653. break;
  2654. case KVM_CAP_MCE:
  2655. r = KVM_MAX_MCE_BANKS;
  2656. break;
  2657. case KVM_CAP_XCRS:
  2658. r = boot_cpu_has(X86_FEATURE_XSAVE);
  2659. break;
  2660. case KVM_CAP_TSC_CONTROL:
  2661. r = kvm_has_tsc_control;
  2662. break;
  2663. case KVM_CAP_X2APIC_API:
  2664. r = KVM_X2APIC_API_VALID_FLAGS;
  2665. break;
  2666. case KVM_CAP_NESTED_STATE:
  2667. r = kvm_x86_ops->get_nested_state ?
  2668. kvm_x86_ops->get_nested_state(NULL, 0, 0) : 0;
  2669. break;
  2670. default:
  2671. break;
  2672. }
  2673. return r;
  2674. }
  2675. long kvm_arch_dev_ioctl(struct file *filp,
  2676. unsigned int ioctl, unsigned long arg)
  2677. {
  2678. void __user *argp = (void __user *)arg;
  2679. long r;
  2680. switch (ioctl) {
  2681. case KVM_GET_MSR_INDEX_LIST: {
  2682. struct kvm_msr_list __user *user_msr_list = argp;
  2683. struct kvm_msr_list msr_list;
  2684. unsigned n;
  2685. r = -EFAULT;
  2686. if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
  2687. goto out;
  2688. n = msr_list.nmsrs;
  2689. msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
  2690. if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
  2691. goto out;
  2692. r = -E2BIG;
  2693. if (n < msr_list.nmsrs)
  2694. goto out;
  2695. r = -EFAULT;
  2696. if (copy_to_user(user_msr_list->indices, &msrs_to_save,
  2697. num_msrs_to_save * sizeof(u32)))
  2698. goto out;
  2699. if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
  2700. &emulated_msrs,
  2701. num_emulated_msrs * sizeof(u32)))
  2702. goto out;
  2703. r = 0;
  2704. break;
  2705. }
  2706. case KVM_GET_SUPPORTED_CPUID:
  2707. case KVM_GET_EMULATED_CPUID: {
  2708. struct kvm_cpuid2 __user *cpuid_arg = argp;
  2709. struct kvm_cpuid2 cpuid;
  2710. r = -EFAULT;
  2711. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  2712. goto out;
  2713. r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
  2714. ioctl);
  2715. if (r)
  2716. goto out;
  2717. r = -EFAULT;
  2718. if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
  2719. goto out;
  2720. r = 0;
  2721. break;
  2722. }
  2723. case KVM_X86_GET_MCE_CAP_SUPPORTED: {
  2724. r = -EFAULT;
  2725. if (copy_to_user(argp, &kvm_mce_cap_supported,
  2726. sizeof(kvm_mce_cap_supported)))
  2727. goto out;
  2728. r = 0;
  2729. break;
  2730. case KVM_GET_MSR_FEATURE_INDEX_LIST: {
  2731. struct kvm_msr_list __user *user_msr_list = argp;
  2732. struct kvm_msr_list msr_list;
  2733. unsigned int n;
  2734. r = -EFAULT;
  2735. if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
  2736. goto out;
  2737. n = msr_list.nmsrs;
  2738. msr_list.nmsrs = num_msr_based_features;
  2739. if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
  2740. goto out;
  2741. r = -E2BIG;
  2742. if (n < msr_list.nmsrs)
  2743. goto out;
  2744. r = -EFAULT;
  2745. if (copy_to_user(user_msr_list->indices, &msr_based_features,
  2746. num_msr_based_features * sizeof(u32)))
  2747. goto out;
  2748. r = 0;
  2749. break;
  2750. }
  2751. case KVM_GET_MSRS:
  2752. r = msr_io(NULL, argp, do_get_msr_feature, 1);
  2753. break;
  2754. }
  2755. default:
  2756. r = -EINVAL;
  2757. }
  2758. out:
  2759. return r;
  2760. }
  2761. static void wbinvd_ipi(void *garbage)
  2762. {
  2763. wbinvd();
  2764. }
  2765. static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
  2766. {
  2767. return kvm_arch_has_noncoherent_dma(vcpu->kvm);
  2768. }
  2769. void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
  2770. {
  2771. /* Address WBINVD may be executed by guest */
  2772. if (need_emulate_wbinvd(vcpu)) {
  2773. if (kvm_x86_ops->has_wbinvd_exit())
  2774. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  2775. else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
  2776. smp_call_function_single(vcpu->cpu,
  2777. wbinvd_ipi, NULL, 1);
  2778. }
  2779. kvm_x86_ops->vcpu_load(vcpu, cpu);
  2780. /* Apply any externally detected TSC adjustments (due to suspend) */
  2781. if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
  2782. adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  2783. vcpu->arch.tsc_offset_adjustment = 0;
  2784. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  2785. }
  2786. if (unlikely(vcpu->cpu != cpu) || kvm_check_tsc_unstable()) {
  2787. s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
  2788. rdtsc() - vcpu->arch.last_host_tsc;
  2789. if (tsc_delta < 0)
  2790. mark_tsc_unstable("KVM discovered backwards TSC");
  2791. if (kvm_check_tsc_unstable()) {
  2792. u64 offset = kvm_compute_tsc_offset(vcpu,
  2793. vcpu->arch.last_guest_tsc);
  2794. kvm_vcpu_write_tsc_offset(vcpu, offset);
  2795. vcpu->arch.tsc_catchup = 1;
  2796. }
  2797. if (kvm_lapic_hv_timer_in_use(vcpu))
  2798. kvm_lapic_restart_hv_timer(vcpu);
  2799. /*
  2800. * On a host with synchronized TSC, there is no need to update
  2801. * kvmclock on vcpu->cpu migration
  2802. */
  2803. if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
  2804. kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
  2805. if (vcpu->cpu != cpu)
  2806. kvm_make_request(KVM_REQ_MIGRATE_TIMER, vcpu);
  2807. vcpu->cpu = cpu;
  2808. }
  2809. kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
  2810. }
  2811. static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
  2812. {
  2813. if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
  2814. return;
  2815. vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
  2816. kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
  2817. &vcpu->arch.st.steal.preempted,
  2818. offsetof(struct kvm_steal_time, preempted),
  2819. sizeof(vcpu->arch.st.steal.preempted));
  2820. }
  2821. void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
  2822. {
  2823. int idx;
  2824. if (vcpu->preempted)
  2825. vcpu->arch.preempted_in_kernel = !kvm_x86_ops->get_cpl(vcpu);
  2826. /*
  2827. * Disable page faults because we're in atomic context here.
  2828. * kvm_write_guest_offset_cached() would call might_fault()
  2829. * that relies on pagefault_disable() to tell if there's a
  2830. * bug. NOTE: the write to guest memory may not go through if
  2831. * during postcopy live migration or if there's heavy guest
  2832. * paging.
  2833. */
  2834. pagefault_disable();
  2835. /*
  2836. * kvm_memslots() will be called by
  2837. * kvm_write_guest_offset_cached() so take the srcu lock.
  2838. */
  2839. idx = srcu_read_lock(&vcpu->kvm->srcu);
  2840. kvm_steal_time_set_preempted(vcpu);
  2841. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  2842. pagefault_enable();
  2843. kvm_x86_ops->vcpu_put(vcpu);
  2844. vcpu->arch.last_host_tsc = rdtsc();
  2845. /*
  2846. * If userspace has set any breakpoints or watchpoints, dr6 is restored
  2847. * on every vmexit, but if not, we might have a stale dr6 from the
  2848. * guest. do_debug expects dr6 to be cleared after it runs, do the same.
  2849. */
  2850. set_debugreg(0, 6);
  2851. }
  2852. static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
  2853. struct kvm_lapic_state *s)
  2854. {
  2855. if (vcpu->arch.apicv_active)
  2856. kvm_x86_ops->sync_pir_to_irr(vcpu);
  2857. return kvm_apic_get_state(vcpu, s);
  2858. }
  2859. static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
  2860. struct kvm_lapic_state *s)
  2861. {
  2862. int r;
  2863. r = kvm_apic_set_state(vcpu, s);
  2864. if (r)
  2865. return r;
  2866. update_cr8_intercept(vcpu);
  2867. return 0;
  2868. }
  2869. static int kvm_cpu_accept_dm_intr(struct kvm_vcpu *vcpu)
  2870. {
  2871. return (!lapic_in_kernel(vcpu) ||
  2872. kvm_apic_accept_pic_intr(vcpu));
  2873. }
  2874. /*
  2875. * if userspace requested an interrupt window, check that the
  2876. * interrupt window is open.
  2877. *
  2878. * No need to exit to userspace if we already have an interrupt queued.
  2879. */
  2880. static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)
  2881. {
  2882. return kvm_arch_interrupt_allowed(vcpu) &&
  2883. !kvm_cpu_has_interrupt(vcpu) &&
  2884. !kvm_event_needs_reinjection(vcpu) &&
  2885. kvm_cpu_accept_dm_intr(vcpu);
  2886. }
  2887. static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
  2888. struct kvm_interrupt *irq)
  2889. {
  2890. if (irq->irq >= KVM_NR_INTERRUPTS)
  2891. return -EINVAL;
  2892. if (!irqchip_in_kernel(vcpu->kvm)) {
  2893. kvm_queue_interrupt(vcpu, irq->irq, false);
  2894. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2895. return 0;
  2896. }
  2897. /*
  2898. * With in-kernel LAPIC, we only use this to inject EXTINT, so
  2899. * fail for in-kernel 8259.
  2900. */
  2901. if (pic_in_kernel(vcpu->kvm))
  2902. return -ENXIO;
  2903. if (vcpu->arch.pending_external_vector != -1)
  2904. return -EEXIST;
  2905. vcpu->arch.pending_external_vector = irq->irq;
  2906. kvm_make_request(KVM_REQ_EVENT, vcpu);
  2907. return 0;
  2908. }
  2909. static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
  2910. {
  2911. kvm_inject_nmi(vcpu);
  2912. return 0;
  2913. }
  2914. static int kvm_vcpu_ioctl_smi(struct kvm_vcpu *vcpu)
  2915. {
  2916. kvm_make_request(KVM_REQ_SMI, vcpu);
  2917. return 0;
  2918. }
  2919. static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
  2920. struct kvm_tpr_access_ctl *tac)
  2921. {
  2922. if (tac->flags)
  2923. return -EINVAL;
  2924. vcpu->arch.tpr_access_reporting = !!tac->enabled;
  2925. return 0;
  2926. }
  2927. static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
  2928. u64 mcg_cap)
  2929. {
  2930. int r;
  2931. unsigned bank_num = mcg_cap & 0xff, bank;
  2932. r = -EINVAL;
  2933. if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
  2934. goto out;
  2935. if (mcg_cap & ~(kvm_mce_cap_supported | 0xff | 0xff0000))
  2936. goto out;
  2937. r = 0;
  2938. vcpu->arch.mcg_cap = mcg_cap;
  2939. /* Init IA32_MCG_CTL to all 1s */
  2940. if (mcg_cap & MCG_CTL_P)
  2941. vcpu->arch.mcg_ctl = ~(u64)0;
  2942. /* Init IA32_MCi_CTL to all 1s */
  2943. for (bank = 0; bank < bank_num; bank++)
  2944. vcpu->arch.mce_banks[bank*4] = ~(u64)0;
  2945. if (kvm_x86_ops->setup_mce)
  2946. kvm_x86_ops->setup_mce(vcpu);
  2947. out:
  2948. return r;
  2949. }
  2950. static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  2951. struct kvm_x86_mce *mce)
  2952. {
  2953. u64 mcg_cap = vcpu->arch.mcg_cap;
  2954. unsigned bank_num = mcg_cap & 0xff;
  2955. u64 *banks = vcpu->arch.mce_banks;
  2956. if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
  2957. return -EINVAL;
  2958. /*
  2959. * if IA32_MCG_CTL is not all 1s, the uncorrected error
  2960. * reporting is disabled
  2961. */
  2962. if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
  2963. vcpu->arch.mcg_ctl != ~(u64)0)
  2964. return 0;
  2965. banks += 4 * mce->bank;
  2966. /*
  2967. * if IA32_MCi_CTL is not all 1s, the uncorrected error
  2968. * reporting is disabled for the bank
  2969. */
  2970. if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
  2971. return 0;
  2972. if (mce->status & MCI_STATUS_UC) {
  2973. if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
  2974. !kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
  2975. kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
  2976. return 0;
  2977. }
  2978. if (banks[1] & MCI_STATUS_VAL)
  2979. mce->status |= MCI_STATUS_OVER;
  2980. banks[2] = mce->addr;
  2981. banks[3] = mce->misc;
  2982. vcpu->arch.mcg_status = mce->mcg_status;
  2983. banks[1] = mce->status;
  2984. kvm_queue_exception(vcpu, MC_VECTOR);
  2985. } else if (!(banks[1] & MCI_STATUS_VAL)
  2986. || !(banks[1] & MCI_STATUS_UC)) {
  2987. if (banks[1] & MCI_STATUS_VAL)
  2988. mce->status |= MCI_STATUS_OVER;
  2989. banks[2] = mce->addr;
  2990. banks[3] = mce->misc;
  2991. banks[1] = mce->status;
  2992. } else
  2993. banks[1] |= MCI_STATUS_OVER;
  2994. return 0;
  2995. }
  2996. static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
  2997. struct kvm_vcpu_events *events)
  2998. {
  2999. process_nmi(vcpu);
  3000. /*
  3001. * The API doesn't provide the instruction length for software
  3002. * exceptions, so don't report them. As long as the guest RIP
  3003. * isn't advanced, we should expect to encounter the exception
  3004. * again.
  3005. */
  3006. if (kvm_exception_is_soft(vcpu->arch.exception.nr)) {
  3007. events->exception.injected = 0;
  3008. events->exception.pending = 0;
  3009. } else {
  3010. events->exception.injected = vcpu->arch.exception.injected;
  3011. events->exception.pending = vcpu->arch.exception.pending;
  3012. /*
  3013. * For ABI compatibility, deliberately conflate
  3014. * pending and injected exceptions when
  3015. * KVM_CAP_EXCEPTION_PAYLOAD isn't enabled.
  3016. */
  3017. if (!vcpu->kvm->arch.exception_payload_enabled)
  3018. events->exception.injected |=
  3019. vcpu->arch.exception.pending;
  3020. }
  3021. events->exception.nr = vcpu->arch.exception.nr;
  3022. events->exception.has_error_code = vcpu->arch.exception.has_error_code;
  3023. events->exception.error_code = vcpu->arch.exception.error_code;
  3024. events->exception_has_payload = vcpu->arch.exception.has_payload;
  3025. events->exception_payload = vcpu->arch.exception.payload;
  3026. events->interrupt.injected =
  3027. vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
  3028. events->interrupt.nr = vcpu->arch.interrupt.nr;
  3029. events->interrupt.soft = 0;
  3030. events->interrupt.shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  3031. events->nmi.injected = vcpu->arch.nmi_injected;
  3032. events->nmi.pending = vcpu->arch.nmi_pending != 0;
  3033. events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
  3034. events->nmi.pad = 0;
  3035. events->sipi_vector = 0; /* never valid when reporting to user space */
  3036. events->smi.smm = is_smm(vcpu);
  3037. events->smi.pending = vcpu->arch.smi_pending;
  3038. events->smi.smm_inside_nmi =
  3039. !!(vcpu->arch.hflags & HF_SMM_INSIDE_NMI_MASK);
  3040. events->smi.latched_init = kvm_lapic_latched_init(vcpu);
  3041. events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
  3042. | KVM_VCPUEVENT_VALID_SHADOW
  3043. | KVM_VCPUEVENT_VALID_SMM);
  3044. if (vcpu->kvm->arch.exception_payload_enabled)
  3045. events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
  3046. memset(&events->reserved, 0, sizeof(events->reserved));
  3047. }
  3048. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags);
  3049. static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
  3050. struct kvm_vcpu_events *events)
  3051. {
  3052. if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
  3053. | KVM_VCPUEVENT_VALID_SIPI_VECTOR
  3054. | KVM_VCPUEVENT_VALID_SHADOW
  3055. | KVM_VCPUEVENT_VALID_SMM
  3056. | KVM_VCPUEVENT_VALID_PAYLOAD))
  3057. return -EINVAL;
  3058. if (events->flags & KVM_VCPUEVENT_VALID_PAYLOAD) {
  3059. if (!vcpu->kvm->arch.exception_payload_enabled)
  3060. return -EINVAL;
  3061. if (events->exception.pending)
  3062. events->exception.injected = 0;
  3063. else
  3064. events->exception_has_payload = 0;
  3065. } else {
  3066. events->exception.pending = 0;
  3067. events->exception_has_payload = 0;
  3068. }
  3069. if ((events->exception.injected || events->exception.pending) &&
  3070. (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
  3071. return -EINVAL;
  3072. /* INITs are latched while in SMM */
  3073. if (events->flags & KVM_VCPUEVENT_VALID_SMM &&
  3074. (events->smi.smm || events->smi.pending) &&
  3075. vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
  3076. return -EINVAL;
  3077. process_nmi(vcpu);
  3078. vcpu->arch.exception.injected = events->exception.injected;
  3079. vcpu->arch.exception.pending = events->exception.pending;
  3080. vcpu->arch.exception.nr = events->exception.nr;
  3081. vcpu->arch.exception.has_error_code = events->exception.has_error_code;
  3082. vcpu->arch.exception.error_code = events->exception.error_code;
  3083. vcpu->arch.exception.has_payload = events->exception_has_payload;
  3084. vcpu->arch.exception.payload = events->exception_payload;
  3085. vcpu->arch.interrupt.injected = events->interrupt.injected;
  3086. vcpu->arch.interrupt.nr = events->interrupt.nr;
  3087. vcpu->arch.interrupt.soft = events->interrupt.soft;
  3088. if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
  3089. kvm_x86_ops->set_interrupt_shadow(vcpu,
  3090. events->interrupt.shadow);
  3091. vcpu->arch.nmi_injected = events->nmi.injected;
  3092. if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
  3093. vcpu->arch.nmi_pending = events->nmi.pending;
  3094. kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
  3095. if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
  3096. lapic_in_kernel(vcpu))
  3097. vcpu->arch.apic->sipi_vector = events->sipi_vector;
  3098. if (events->flags & KVM_VCPUEVENT_VALID_SMM) {
  3099. u32 hflags = vcpu->arch.hflags;
  3100. if (events->smi.smm)
  3101. hflags |= HF_SMM_MASK;
  3102. else
  3103. hflags &= ~HF_SMM_MASK;
  3104. kvm_set_hflags(vcpu, hflags);
  3105. vcpu->arch.smi_pending = events->smi.pending;
  3106. if (events->smi.smm) {
  3107. if (events->smi.smm_inside_nmi)
  3108. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  3109. else
  3110. vcpu->arch.hflags &= ~HF_SMM_INSIDE_NMI_MASK;
  3111. if (lapic_in_kernel(vcpu)) {
  3112. if (events->smi.latched_init)
  3113. set_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  3114. else
  3115. clear_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
  3116. }
  3117. }
  3118. }
  3119. kvm_make_request(KVM_REQ_EVENT, vcpu);
  3120. return 0;
  3121. }
  3122. static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
  3123. struct kvm_debugregs *dbgregs)
  3124. {
  3125. unsigned long val;
  3126. memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
  3127. kvm_get_dr(vcpu, 6, &val);
  3128. dbgregs->dr6 = val;
  3129. dbgregs->dr7 = vcpu->arch.dr7;
  3130. dbgregs->flags = 0;
  3131. memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
  3132. }
  3133. static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
  3134. struct kvm_debugregs *dbgregs)
  3135. {
  3136. if (dbgregs->flags)
  3137. return -EINVAL;
  3138. if (dbgregs->dr6 & ~0xffffffffull)
  3139. return -EINVAL;
  3140. if (dbgregs->dr7 & ~0xffffffffull)
  3141. return -EINVAL;
  3142. memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
  3143. kvm_update_dr0123(vcpu);
  3144. vcpu->arch.dr6 = dbgregs->dr6;
  3145. kvm_update_dr6(vcpu);
  3146. vcpu->arch.dr7 = dbgregs->dr7;
  3147. kvm_update_dr7(vcpu);
  3148. return 0;
  3149. }
  3150. #define XSTATE_COMPACTION_ENABLED (1ULL << 63)
  3151. static void fill_xsave(u8 *dest, struct kvm_vcpu *vcpu)
  3152. {
  3153. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  3154. u64 xstate_bv = xsave->header.xfeatures;
  3155. u64 valid;
  3156. /*
  3157. * Copy legacy XSAVE area, to avoid complications with CPUID
  3158. * leaves 0 and 1 in the loop below.
  3159. */
  3160. memcpy(dest, xsave, XSAVE_HDR_OFFSET);
  3161. /* Set XSTATE_BV */
  3162. xstate_bv &= vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE;
  3163. *(u64 *)(dest + XSAVE_HDR_OFFSET) = xstate_bv;
  3164. /*
  3165. * Copy each region from the possibly compacted offset to the
  3166. * non-compacted offset.
  3167. */
  3168. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  3169. while (valid) {
  3170. u64 feature = valid & -valid;
  3171. int index = fls64(feature) - 1;
  3172. void *src = get_xsave_addr(xsave, feature);
  3173. if (src) {
  3174. u32 size, offset, ecx, edx;
  3175. cpuid_count(XSTATE_CPUID, index,
  3176. &size, &offset, &ecx, &edx);
  3177. if (feature == XFEATURE_MASK_PKRU)
  3178. memcpy(dest + offset, &vcpu->arch.pkru,
  3179. sizeof(vcpu->arch.pkru));
  3180. else
  3181. memcpy(dest + offset, src, size);
  3182. }
  3183. valid -= feature;
  3184. }
  3185. }
  3186. static void load_xsave(struct kvm_vcpu *vcpu, u8 *src)
  3187. {
  3188. struct xregs_state *xsave = &vcpu->arch.guest_fpu.state.xsave;
  3189. u64 xstate_bv = *(u64 *)(src + XSAVE_HDR_OFFSET);
  3190. u64 valid;
  3191. /*
  3192. * Copy legacy XSAVE area, to avoid complications with CPUID
  3193. * leaves 0 and 1 in the loop below.
  3194. */
  3195. memcpy(xsave, src, XSAVE_HDR_OFFSET);
  3196. /* Set XSTATE_BV and possibly XCOMP_BV. */
  3197. xsave->header.xfeatures = xstate_bv;
  3198. if (boot_cpu_has(X86_FEATURE_XSAVES))
  3199. xsave->header.xcomp_bv = host_xcr0 | XSTATE_COMPACTION_ENABLED;
  3200. /*
  3201. * Copy each region from the non-compacted offset to the
  3202. * possibly compacted offset.
  3203. */
  3204. valid = xstate_bv & ~XFEATURE_MASK_FPSSE;
  3205. while (valid) {
  3206. u64 feature = valid & -valid;
  3207. int index = fls64(feature) - 1;
  3208. void *dest = get_xsave_addr(xsave, feature);
  3209. if (dest) {
  3210. u32 size, offset, ecx, edx;
  3211. cpuid_count(XSTATE_CPUID, index,
  3212. &size, &offset, &ecx, &edx);
  3213. if (feature == XFEATURE_MASK_PKRU)
  3214. memcpy(&vcpu->arch.pkru, src + offset,
  3215. sizeof(vcpu->arch.pkru));
  3216. else
  3217. memcpy(dest, src + offset, size);
  3218. }
  3219. valid -= feature;
  3220. }
  3221. }
  3222. static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
  3223. struct kvm_xsave *guest_xsave)
  3224. {
  3225. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  3226. memset(guest_xsave, 0, sizeof(struct kvm_xsave));
  3227. fill_xsave((u8 *) guest_xsave->region, vcpu);
  3228. } else {
  3229. memcpy(guest_xsave->region,
  3230. &vcpu->arch.guest_fpu.state.fxsave,
  3231. sizeof(struct fxregs_state));
  3232. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
  3233. XFEATURE_MASK_FPSSE;
  3234. }
  3235. }
  3236. #define XSAVE_MXCSR_OFFSET 24
  3237. static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
  3238. struct kvm_xsave *guest_xsave)
  3239. {
  3240. u64 xstate_bv =
  3241. *(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
  3242. u32 mxcsr = *(u32 *)&guest_xsave->region[XSAVE_MXCSR_OFFSET / sizeof(u32)];
  3243. if (boot_cpu_has(X86_FEATURE_XSAVE)) {
  3244. /*
  3245. * Here we allow setting states that are not present in
  3246. * CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
  3247. * with old userspace.
  3248. */
  3249. if (xstate_bv & ~kvm_supported_xcr0() ||
  3250. mxcsr & ~mxcsr_feature_mask)
  3251. return -EINVAL;
  3252. load_xsave(vcpu, (u8 *)guest_xsave->region);
  3253. } else {
  3254. if (xstate_bv & ~XFEATURE_MASK_FPSSE ||
  3255. mxcsr & ~mxcsr_feature_mask)
  3256. return -EINVAL;
  3257. memcpy(&vcpu->arch.guest_fpu.state.fxsave,
  3258. guest_xsave->region, sizeof(struct fxregs_state));
  3259. }
  3260. return 0;
  3261. }
  3262. static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
  3263. struct kvm_xcrs *guest_xcrs)
  3264. {
  3265. if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
  3266. guest_xcrs->nr_xcrs = 0;
  3267. return;
  3268. }
  3269. guest_xcrs->nr_xcrs = 1;
  3270. guest_xcrs->flags = 0;
  3271. guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
  3272. guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
  3273. }
  3274. static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
  3275. struct kvm_xcrs *guest_xcrs)
  3276. {
  3277. int i, r = 0;
  3278. if (!boot_cpu_has(X86_FEATURE_XSAVE))
  3279. return -EINVAL;
  3280. if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
  3281. return -EINVAL;
  3282. for (i = 0; i < guest_xcrs->nr_xcrs; i++)
  3283. /* Only support XCR0 currently */
  3284. if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
  3285. r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
  3286. guest_xcrs->xcrs[i].value);
  3287. break;
  3288. }
  3289. if (r)
  3290. r = -EINVAL;
  3291. return r;
  3292. }
  3293. /*
  3294. * kvm_set_guest_paused() indicates to the guest kernel that it has been
  3295. * stopped by the hypervisor. This function will be called from the host only.
  3296. * EINVAL is returned when the host attempts to set the flag for a guest that
  3297. * does not support pv clocks.
  3298. */
  3299. static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
  3300. {
  3301. if (!vcpu->arch.pv_time_enabled)
  3302. return -EINVAL;
  3303. vcpu->arch.pvclock_set_guest_stopped_request = true;
  3304. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  3305. return 0;
  3306. }
  3307. static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
  3308. struct kvm_enable_cap *cap)
  3309. {
  3310. int r;
  3311. uint16_t vmcs_version;
  3312. void __user *user_ptr;
  3313. if (cap->flags)
  3314. return -EINVAL;
  3315. switch (cap->cap) {
  3316. case KVM_CAP_HYPERV_SYNIC2:
  3317. if (cap->args[0])
  3318. return -EINVAL;
  3319. case KVM_CAP_HYPERV_SYNIC:
  3320. if (!irqchip_in_kernel(vcpu->kvm))
  3321. return -EINVAL;
  3322. return kvm_hv_activate_synic(vcpu, cap->cap ==
  3323. KVM_CAP_HYPERV_SYNIC2);
  3324. case KVM_CAP_HYPERV_ENLIGHTENED_VMCS:
  3325. r = kvm_x86_ops->nested_enable_evmcs(vcpu, &vmcs_version);
  3326. if (!r) {
  3327. user_ptr = (void __user *)(uintptr_t)cap->args[0];
  3328. if (copy_to_user(user_ptr, &vmcs_version,
  3329. sizeof(vmcs_version)))
  3330. r = -EFAULT;
  3331. }
  3332. return r;
  3333. default:
  3334. return -EINVAL;
  3335. }
  3336. }
  3337. long kvm_arch_vcpu_ioctl(struct file *filp,
  3338. unsigned int ioctl, unsigned long arg)
  3339. {
  3340. struct kvm_vcpu *vcpu = filp->private_data;
  3341. void __user *argp = (void __user *)arg;
  3342. int r;
  3343. union {
  3344. struct kvm_lapic_state *lapic;
  3345. struct kvm_xsave *xsave;
  3346. struct kvm_xcrs *xcrs;
  3347. void *buffer;
  3348. } u;
  3349. vcpu_load(vcpu);
  3350. u.buffer = NULL;
  3351. switch (ioctl) {
  3352. case KVM_GET_LAPIC: {
  3353. r = -EINVAL;
  3354. if (!lapic_in_kernel(vcpu))
  3355. goto out;
  3356. u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
  3357. r = -ENOMEM;
  3358. if (!u.lapic)
  3359. goto out;
  3360. r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
  3361. if (r)
  3362. goto out;
  3363. r = -EFAULT;
  3364. if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
  3365. goto out;
  3366. r = 0;
  3367. break;
  3368. }
  3369. case KVM_SET_LAPIC: {
  3370. r = -EINVAL;
  3371. if (!lapic_in_kernel(vcpu))
  3372. goto out;
  3373. u.lapic = memdup_user(argp, sizeof(*u.lapic));
  3374. if (IS_ERR(u.lapic)) {
  3375. r = PTR_ERR(u.lapic);
  3376. goto out_nofree;
  3377. }
  3378. r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
  3379. break;
  3380. }
  3381. case KVM_INTERRUPT: {
  3382. struct kvm_interrupt irq;
  3383. r = -EFAULT;
  3384. if (copy_from_user(&irq, argp, sizeof(irq)))
  3385. goto out;
  3386. r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
  3387. break;
  3388. }
  3389. case KVM_NMI: {
  3390. r = kvm_vcpu_ioctl_nmi(vcpu);
  3391. break;
  3392. }
  3393. case KVM_SMI: {
  3394. r = kvm_vcpu_ioctl_smi(vcpu);
  3395. break;
  3396. }
  3397. case KVM_SET_CPUID: {
  3398. struct kvm_cpuid __user *cpuid_arg = argp;
  3399. struct kvm_cpuid cpuid;
  3400. r = -EFAULT;
  3401. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  3402. goto out;
  3403. r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
  3404. break;
  3405. }
  3406. case KVM_SET_CPUID2: {
  3407. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3408. struct kvm_cpuid2 cpuid;
  3409. r = -EFAULT;
  3410. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  3411. goto out;
  3412. r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
  3413. cpuid_arg->entries);
  3414. break;
  3415. }
  3416. case KVM_GET_CPUID2: {
  3417. struct kvm_cpuid2 __user *cpuid_arg = argp;
  3418. struct kvm_cpuid2 cpuid;
  3419. r = -EFAULT;
  3420. if (copy_from_user(&cpuid, cpuid_arg, sizeof(cpuid)))
  3421. goto out;
  3422. r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
  3423. cpuid_arg->entries);
  3424. if (r)
  3425. goto out;
  3426. r = -EFAULT;
  3427. if (copy_to_user(cpuid_arg, &cpuid, sizeof(cpuid)))
  3428. goto out;
  3429. r = 0;
  3430. break;
  3431. }
  3432. case KVM_GET_MSRS: {
  3433. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  3434. r = msr_io(vcpu, argp, do_get_msr, 1);
  3435. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3436. break;
  3437. }
  3438. case KVM_SET_MSRS: {
  3439. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  3440. r = msr_io(vcpu, argp, do_set_msr, 0);
  3441. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3442. break;
  3443. }
  3444. case KVM_TPR_ACCESS_REPORTING: {
  3445. struct kvm_tpr_access_ctl tac;
  3446. r = -EFAULT;
  3447. if (copy_from_user(&tac, argp, sizeof(tac)))
  3448. goto out;
  3449. r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
  3450. if (r)
  3451. goto out;
  3452. r = -EFAULT;
  3453. if (copy_to_user(argp, &tac, sizeof(tac)))
  3454. goto out;
  3455. r = 0;
  3456. break;
  3457. };
  3458. case KVM_SET_VAPIC_ADDR: {
  3459. struct kvm_vapic_addr va;
  3460. int idx;
  3461. r = -EINVAL;
  3462. if (!lapic_in_kernel(vcpu))
  3463. goto out;
  3464. r = -EFAULT;
  3465. if (copy_from_user(&va, argp, sizeof(va)))
  3466. goto out;
  3467. idx = srcu_read_lock(&vcpu->kvm->srcu);
  3468. r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
  3469. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  3470. break;
  3471. }
  3472. case KVM_X86_SETUP_MCE: {
  3473. u64 mcg_cap;
  3474. r = -EFAULT;
  3475. if (copy_from_user(&mcg_cap, argp, sizeof(mcg_cap)))
  3476. goto out;
  3477. r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
  3478. break;
  3479. }
  3480. case KVM_X86_SET_MCE: {
  3481. struct kvm_x86_mce mce;
  3482. r = -EFAULT;
  3483. if (copy_from_user(&mce, argp, sizeof(mce)))
  3484. goto out;
  3485. r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
  3486. break;
  3487. }
  3488. case KVM_GET_VCPU_EVENTS: {
  3489. struct kvm_vcpu_events events;
  3490. kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
  3491. r = -EFAULT;
  3492. if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
  3493. break;
  3494. r = 0;
  3495. break;
  3496. }
  3497. case KVM_SET_VCPU_EVENTS: {
  3498. struct kvm_vcpu_events events;
  3499. r = -EFAULT;
  3500. if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
  3501. break;
  3502. r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
  3503. break;
  3504. }
  3505. case KVM_GET_DEBUGREGS: {
  3506. struct kvm_debugregs dbgregs;
  3507. kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
  3508. r = -EFAULT;
  3509. if (copy_to_user(argp, &dbgregs,
  3510. sizeof(struct kvm_debugregs)))
  3511. break;
  3512. r = 0;
  3513. break;
  3514. }
  3515. case KVM_SET_DEBUGREGS: {
  3516. struct kvm_debugregs dbgregs;
  3517. r = -EFAULT;
  3518. if (copy_from_user(&dbgregs, argp,
  3519. sizeof(struct kvm_debugregs)))
  3520. break;
  3521. r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
  3522. break;
  3523. }
  3524. case KVM_GET_XSAVE: {
  3525. u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
  3526. r = -ENOMEM;
  3527. if (!u.xsave)
  3528. break;
  3529. kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
  3530. r = -EFAULT;
  3531. if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
  3532. break;
  3533. r = 0;
  3534. break;
  3535. }
  3536. case KVM_SET_XSAVE: {
  3537. u.xsave = memdup_user(argp, sizeof(*u.xsave));
  3538. if (IS_ERR(u.xsave)) {
  3539. r = PTR_ERR(u.xsave);
  3540. goto out_nofree;
  3541. }
  3542. r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
  3543. break;
  3544. }
  3545. case KVM_GET_XCRS: {
  3546. u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
  3547. r = -ENOMEM;
  3548. if (!u.xcrs)
  3549. break;
  3550. kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
  3551. r = -EFAULT;
  3552. if (copy_to_user(argp, u.xcrs,
  3553. sizeof(struct kvm_xcrs)))
  3554. break;
  3555. r = 0;
  3556. break;
  3557. }
  3558. case KVM_SET_XCRS: {
  3559. u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
  3560. if (IS_ERR(u.xcrs)) {
  3561. r = PTR_ERR(u.xcrs);
  3562. goto out_nofree;
  3563. }
  3564. r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
  3565. break;
  3566. }
  3567. case KVM_SET_TSC_KHZ: {
  3568. u32 user_tsc_khz;
  3569. r = -EINVAL;
  3570. user_tsc_khz = (u32)arg;
  3571. if (user_tsc_khz >= kvm_max_guest_tsc_khz)
  3572. goto out;
  3573. if (user_tsc_khz == 0)
  3574. user_tsc_khz = tsc_khz;
  3575. if (!kvm_set_tsc_khz(vcpu, user_tsc_khz))
  3576. r = 0;
  3577. goto out;
  3578. }
  3579. case KVM_GET_TSC_KHZ: {
  3580. r = vcpu->arch.virtual_tsc_khz;
  3581. goto out;
  3582. }
  3583. case KVM_KVMCLOCK_CTRL: {
  3584. r = kvm_set_guest_paused(vcpu);
  3585. goto out;
  3586. }
  3587. case KVM_ENABLE_CAP: {
  3588. struct kvm_enable_cap cap;
  3589. r = -EFAULT;
  3590. if (copy_from_user(&cap, argp, sizeof(cap)))
  3591. goto out;
  3592. r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
  3593. break;
  3594. }
  3595. case KVM_GET_NESTED_STATE: {
  3596. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  3597. u32 user_data_size;
  3598. r = -EINVAL;
  3599. if (!kvm_x86_ops->get_nested_state)
  3600. break;
  3601. BUILD_BUG_ON(sizeof(user_data_size) != sizeof(user_kvm_nested_state->size));
  3602. r = -EFAULT;
  3603. if (get_user(user_data_size, &user_kvm_nested_state->size))
  3604. break;
  3605. r = kvm_x86_ops->get_nested_state(vcpu, user_kvm_nested_state,
  3606. user_data_size);
  3607. if (r < 0)
  3608. break;
  3609. if (r > user_data_size) {
  3610. if (put_user(r, &user_kvm_nested_state->size))
  3611. r = -EFAULT;
  3612. else
  3613. r = -E2BIG;
  3614. break;
  3615. }
  3616. r = 0;
  3617. break;
  3618. }
  3619. case KVM_SET_NESTED_STATE: {
  3620. struct kvm_nested_state __user *user_kvm_nested_state = argp;
  3621. struct kvm_nested_state kvm_state;
  3622. r = -EINVAL;
  3623. if (!kvm_x86_ops->set_nested_state)
  3624. break;
  3625. r = -EFAULT;
  3626. if (copy_from_user(&kvm_state, user_kvm_nested_state, sizeof(kvm_state)))
  3627. break;
  3628. r = -EINVAL;
  3629. if (kvm_state.size < sizeof(kvm_state))
  3630. break;
  3631. if (kvm_state.flags &
  3632. ~(KVM_STATE_NESTED_RUN_PENDING | KVM_STATE_NESTED_GUEST_MODE
  3633. | KVM_STATE_NESTED_EVMCS))
  3634. break;
  3635. /* nested_run_pending implies guest_mode. */
  3636. if ((kvm_state.flags & KVM_STATE_NESTED_RUN_PENDING)
  3637. && !(kvm_state.flags & KVM_STATE_NESTED_GUEST_MODE))
  3638. break;
  3639. r = kvm_x86_ops->set_nested_state(vcpu, user_kvm_nested_state, &kvm_state);
  3640. break;
  3641. }
  3642. default:
  3643. r = -EINVAL;
  3644. }
  3645. out:
  3646. kfree(u.buffer);
  3647. out_nofree:
  3648. vcpu_put(vcpu);
  3649. return r;
  3650. }
  3651. vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
  3652. {
  3653. return VM_FAULT_SIGBUS;
  3654. }
  3655. static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
  3656. {
  3657. int ret;
  3658. if (addr > (unsigned int)(-3 * PAGE_SIZE))
  3659. return -EINVAL;
  3660. ret = kvm_x86_ops->set_tss_addr(kvm, addr);
  3661. return ret;
  3662. }
  3663. static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
  3664. u64 ident_addr)
  3665. {
  3666. return kvm_x86_ops->set_identity_map_addr(kvm, ident_addr);
  3667. }
  3668. static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
  3669. u32 kvm_nr_mmu_pages)
  3670. {
  3671. if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
  3672. return -EINVAL;
  3673. mutex_lock(&kvm->slots_lock);
  3674. kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
  3675. kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
  3676. mutex_unlock(&kvm->slots_lock);
  3677. return 0;
  3678. }
  3679. static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
  3680. {
  3681. return kvm->arch.n_max_mmu_pages;
  3682. }
  3683. static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3684. {
  3685. struct kvm_pic *pic = kvm->arch.vpic;
  3686. int r;
  3687. r = 0;
  3688. switch (chip->chip_id) {
  3689. case KVM_IRQCHIP_PIC_MASTER:
  3690. memcpy(&chip->chip.pic, &pic->pics[0],
  3691. sizeof(struct kvm_pic_state));
  3692. break;
  3693. case KVM_IRQCHIP_PIC_SLAVE:
  3694. memcpy(&chip->chip.pic, &pic->pics[1],
  3695. sizeof(struct kvm_pic_state));
  3696. break;
  3697. case KVM_IRQCHIP_IOAPIC:
  3698. kvm_get_ioapic(kvm, &chip->chip.ioapic);
  3699. break;
  3700. default:
  3701. r = -EINVAL;
  3702. break;
  3703. }
  3704. return r;
  3705. }
  3706. static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
  3707. {
  3708. struct kvm_pic *pic = kvm->arch.vpic;
  3709. int r;
  3710. r = 0;
  3711. switch (chip->chip_id) {
  3712. case KVM_IRQCHIP_PIC_MASTER:
  3713. spin_lock(&pic->lock);
  3714. memcpy(&pic->pics[0], &chip->chip.pic,
  3715. sizeof(struct kvm_pic_state));
  3716. spin_unlock(&pic->lock);
  3717. break;
  3718. case KVM_IRQCHIP_PIC_SLAVE:
  3719. spin_lock(&pic->lock);
  3720. memcpy(&pic->pics[1], &chip->chip.pic,
  3721. sizeof(struct kvm_pic_state));
  3722. spin_unlock(&pic->lock);
  3723. break;
  3724. case KVM_IRQCHIP_IOAPIC:
  3725. kvm_set_ioapic(kvm, &chip->chip.ioapic);
  3726. break;
  3727. default:
  3728. r = -EINVAL;
  3729. break;
  3730. }
  3731. kvm_pic_update_irq(pic);
  3732. return r;
  3733. }
  3734. static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3735. {
  3736. struct kvm_kpit_state *kps = &kvm->arch.vpit->pit_state;
  3737. BUILD_BUG_ON(sizeof(*ps) != sizeof(kps->channels));
  3738. mutex_lock(&kps->lock);
  3739. memcpy(ps, &kps->channels, sizeof(*ps));
  3740. mutex_unlock(&kps->lock);
  3741. return 0;
  3742. }
  3743. static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
  3744. {
  3745. int i;
  3746. struct kvm_pit *pit = kvm->arch.vpit;
  3747. mutex_lock(&pit->pit_state.lock);
  3748. memcpy(&pit->pit_state.channels, ps, sizeof(*ps));
  3749. for (i = 0; i < 3; i++)
  3750. kvm_pit_load_count(pit, i, ps->channels[i].count, 0);
  3751. mutex_unlock(&pit->pit_state.lock);
  3752. return 0;
  3753. }
  3754. static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3755. {
  3756. mutex_lock(&kvm->arch.vpit->pit_state.lock);
  3757. memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
  3758. sizeof(ps->channels));
  3759. ps->flags = kvm->arch.vpit->pit_state.flags;
  3760. mutex_unlock(&kvm->arch.vpit->pit_state.lock);
  3761. memset(&ps->reserved, 0, sizeof(ps->reserved));
  3762. return 0;
  3763. }
  3764. static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
  3765. {
  3766. int start = 0;
  3767. int i;
  3768. u32 prev_legacy, cur_legacy;
  3769. struct kvm_pit *pit = kvm->arch.vpit;
  3770. mutex_lock(&pit->pit_state.lock);
  3771. prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3772. cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
  3773. if (!prev_legacy && cur_legacy)
  3774. start = 1;
  3775. memcpy(&pit->pit_state.channels, &ps->channels,
  3776. sizeof(pit->pit_state.channels));
  3777. pit->pit_state.flags = ps->flags;
  3778. for (i = 0; i < 3; i++)
  3779. kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
  3780. start && i == 0);
  3781. mutex_unlock(&pit->pit_state.lock);
  3782. return 0;
  3783. }
  3784. static int kvm_vm_ioctl_reinject(struct kvm *kvm,
  3785. struct kvm_reinject_control *control)
  3786. {
  3787. struct kvm_pit *pit = kvm->arch.vpit;
  3788. if (!pit)
  3789. return -ENXIO;
  3790. /* pit->pit_state.lock was overloaded to prevent userspace from getting
  3791. * an inconsistent state after running multiple KVM_REINJECT_CONTROL
  3792. * ioctls in parallel. Use a separate lock if that ioctl isn't rare.
  3793. */
  3794. mutex_lock(&pit->pit_state.lock);
  3795. kvm_pit_set_reinject(pit, control->pit_reinject);
  3796. mutex_unlock(&pit->pit_state.lock);
  3797. return 0;
  3798. }
  3799. /**
  3800. * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
  3801. * @kvm: kvm instance
  3802. * @log: slot id and address to which we copy the log
  3803. *
  3804. * Steps 1-4 below provide general overview of dirty page logging. See
  3805. * kvm_get_dirty_log_protect() function description for additional details.
  3806. *
  3807. * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
  3808. * always flush the TLB (step 4) even if previous step failed and the dirty
  3809. * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
  3810. * does not preclude user space subsequent dirty log read. Flushing TLB ensures
  3811. * writes will be marked dirty for next log read.
  3812. *
  3813. * 1. Take a snapshot of the bit and clear it if needed.
  3814. * 2. Write protect the corresponding page.
  3815. * 3. Copy the snapshot to the userspace.
  3816. * 4. Flush TLB's if needed.
  3817. */
  3818. int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
  3819. {
  3820. bool is_dirty = false;
  3821. int r;
  3822. mutex_lock(&kvm->slots_lock);
  3823. /*
  3824. * Flush potentially hardware-cached dirty pages to dirty_bitmap.
  3825. */
  3826. if (kvm_x86_ops->flush_log_dirty)
  3827. kvm_x86_ops->flush_log_dirty(kvm);
  3828. r = kvm_get_dirty_log_protect(kvm, log, &is_dirty);
  3829. /*
  3830. * All the TLBs can be flushed out of mmu lock, see the comments in
  3831. * kvm_mmu_slot_remove_write_access().
  3832. */
  3833. lockdep_assert_held(&kvm->slots_lock);
  3834. if (is_dirty)
  3835. kvm_flush_remote_tlbs(kvm);
  3836. mutex_unlock(&kvm->slots_lock);
  3837. return r;
  3838. }
  3839. int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
  3840. bool line_status)
  3841. {
  3842. if (!irqchip_in_kernel(kvm))
  3843. return -ENXIO;
  3844. irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
  3845. irq_event->irq, irq_event->level,
  3846. line_status);
  3847. return 0;
  3848. }
  3849. static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
  3850. struct kvm_enable_cap *cap)
  3851. {
  3852. int r;
  3853. if (cap->flags)
  3854. return -EINVAL;
  3855. switch (cap->cap) {
  3856. case KVM_CAP_DISABLE_QUIRKS:
  3857. kvm->arch.disabled_quirks = cap->args[0];
  3858. r = 0;
  3859. break;
  3860. case KVM_CAP_SPLIT_IRQCHIP: {
  3861. mutex_lock(&kvm->lock);
  3862. r = -EINVAL;
  3863. if (cap->args[0] > MAX_NR_RESERVED_IOAPIC_PINS)
  3864. goto split_irqchip_unlock;
  3865. r = -EEXIST;
  3866. if (irqchip_in_kernel(kvm))
  3867. goto split_irqchip_unlock;
  3868. if (kvm->created_vcpus)
  3869. goto split_irqchip_unlock;
  3870. r = kvm_setup_empty_irq_routing(kvm);
  3871. if (r)
  3872. goto split_irqchip_unlock;
  3873. /* Pairs with irqchip_in_kernel. */
  3874. smp_wmb();
  3875. kvm->arch.irqchip_mode = KVM_IRQCHIP_SPLIT;
  3876. kvm->arch.nr_reserved_ioapic_pins = cap->args[0];
  3877. r = 0;
  3878. split_irqchip_unlock:
  3879. mutex_unlock(&kvm->lock);
  3880. break;
  3881. }
  3882. case KVM_CAP_X2APIC_API:
  3883. r = -EINVAL;
  3884. if (cap->args[0] & ~KVM_X2APIC_API_VALID_FLAGS)
  3885. break;
  3886. if (cap->args[0] & KVM_X2APIC_API_USE_32BIT_IDS)
  3887. kvm->arch.x2apic_format = true;
  3888. if (cap->args[0] & KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK)
  3889. kvm->arch.x2apic_broadcast_quirk_disabled = true;
  3890. r = 0;
  3891. break;
  3892. case KVM_CAP_X86_DISABLE_EXITS:
  3893. r = -EINVAL;
  3894. if (cap->args[0] & ~KVM_X86_DISABLE_VALID_EXITS)
  3895. break;
  3896. if ((cap->args[0] & KVM_X86_DISABLE_EXITS_MWAIT) &&
  3897. kvm_can_mwait_in_guest())
  3898. kvm->arch.mwait_in_guest = true;
  3899. if (cap->args[0] & KVM_X86_DISABLE_EXITS_HLT)
  3900. kvm->arch.hlt_in_guest = true;
  3901. if (cap->args[0] & KVM_X86_DISABLE_EXITS_PAUSE)
  3902. kvm->arch.pause_in_guest = true;
  3903. r = 0;
  3904. break;
  3905. case KVM_CAP_MSR_PLATFORM_INFO:
  3906. kvm->arch.guest_can_read_msr_platform_info = cap->args[0];
  3907. r = 0;
  3908. break;
  3909. case KVM_CAP_EXCEPTION_PAYLOAD:
  3910. kvm->arch.exception_payload_enabled = cap->args[0];
  3911. r = 0;
  3912. break;
  3913. default:
  3914. r = -EINVAL;
  3915. break;
  3916. }
  3917. return r;
  3918. }
  3919. long kvm_arch_vm_ioctl(struct file *filp,
  3920. unsigned int ioctl, unsigned long arg)
  3921. {
  3922. struct kvm *kvm = filp->private_data;
  3923. void __user *argp = (void __user *)arg;
  3924. int r = -ENOTTY;
  3925. /*
  3926. * This union makes it completely explicit to gcc-3.x
  3927. * that these two variables' stack usage should be
  3928. * combined, not added together.
  3929. */
  3930. union {
  3931. struct kvm_pit_state ps;
  3932. struct kvm_pit_state2 ps2;
  3933. struct kvm_pit_config pit_config;
  3934. } u;
  3935. switch (ioctl) {
  3936. case KVM_SET_TSS_ADDR:
  3937. r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
  3938. break;
  3939. case KVM_SET_IDENTITY_MAP_ADDR: {
  3940. u64 ident_addr;
  3941. mutex_lock(&kvm->lock);
  3942. r = -EINVAL;
  3943. if (kvm->created_vcpus)
  3944. goto set_identity_unlock;
  3945. r = -EFAULT;
  3946. if (copy_from_user(&ident_addr, argp, sizeof(ident_addr)))
  3947. goto set_identity_unlock;
  3948. r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
  3949. set_identity_unlock:
  3950. mutex_unlock(&kvm->lock);
  3951. break;
  3952. }
  3953. case KVM_SET_NR_MMU_PAGES:
  3954. r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
  3955. break;
  3956. case KVM_GET_NR_MMU_PAGES:
  3957. r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
  3958. break;
  3959. case KVM_CREATE_IRQCHIP: {
  3960. mutex_lock(&kvm->lock);
  3961. r = -EEXIST;
  3962. if (irqchip_in_kernel(kvm))
  3963. goto create_irqchip_unlock;
  3964. r = -EINVAL;
  3965. if (kvm->created_vcpus)
  3966. goto create_irqchip_unlock;
  3967. r = kvm_pic_init(kvm);
  3968. if (r)
  3969. goto create_irqchip_unlock;
  3970. r = kvm_ioapic_init(kvm);
  3971. if (r) {
  3972. kvm_pic_destroy(kvm);
  3973. goto create_irqchip_unlock;
  3974. }
  3975. r = kvm_setup_default_irq_routing(kvm);
  3976. if (r) {
  3977. kvm_ioapic_destroy(kvm);
  3978. kvm_pic_destroy(kvm);
  3979. goto create_irqchip_unlock;
  3980. }
  3981. /* Write kvm->irq_routing before enabling irqchip_in_kernel. */
  3982. smp_wmb();
  3983. kvm->arch.irqchip_mode = KVM_IRQCHIP_KERNEL;
  3984. create_irqchip_unlock:
  3985. mutex_unlock(&kvm->lock);
  3986. break;
  3987. }
  3988. case KVM_CREATE_PIT:
  3989. u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
  3990. goto create_pit;
  3991. case KVM_CREATE_PIT2:
  3992. r = -EFAULT;
  3993. if (copy_from_user(&u.pit_config, argp,
  3994. sizeof(struct kvm_pit_config)))
  3995. goto out;
  3996. create_pit:
  3997. mutex_lock(&kvm->lock);
  3998. r = -EEXIST;
  3999. if (kvm->arch.vpit)
  4000. goto create_pit_unlock;
  4001. r = -ENOMEM;
  4002. kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
  4003. if (kvm->arch.vpit)
  4004. r = 0;
  4005. create_pit_unlock:
  4006. mutex_unlock(&kvm->lock);
  4007. break;
  4008. case KVM_GET_IRQCHIP: {
  4009. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  4010. struct kvm_irqchip *chip;
  4011. chip = memdup_user(argp, sizeof(*chip));
  4012. if (IS_ERR(chip)) {
  4013. r = PTR_ERR(chip);
  4014. goto out;
  4015. }
  4016. r = -ENXIO;
  4017. if (!irqchip_kernel(kvm))
  4018. goto get_irqchip_out;
  4019. r = kvm_vm_ioctl_get_irqchip(kvm, chip);
  4020. if (r)
  4021. goto get_irqchip_out;
  4022. r = -EFAULT;
  4023. if (copy_to_user(argp, chip, sizeof(*chip)))
  4024. goto get_irqchip_out;
  4025. r = 0;
  4026. get_irqchip_out:
  4027. kfree(chip);
  4028. break;
  4029. }
  4030. case KVM_SET_IRQCHIP: {
  4031. /* 0: PIC master, 1: PIC slave, 2: IOAPIC */
  4032. struct kvm_irqchip *chip;
  4033. chip = memdup_user(argp, sizeof(*chip));
  4034. if (IS_ERR(chip)) {
  4035. r = PTR_ERR(chip);
  4036. goto out;
  4037. }
  4038. r = -ENXIO;
  4039. if (!irqchip_kernel(kvm))
  4040. goto set_irqchip_out;
  4041. r = kvm_vm_ioctl_set_irqchip(kvm, chip);
  4042. if (r)
  4043. goto set_irqchip_out;
  4044. r = 0;
  4045. set_irqchip_out:
  4046. kfree(chip);
  4047. break;
  4048. }
  4049. case KVM_GET_PIT: {
  4050. r = -EFAULT;
  4051. if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
  4052. goto out;
  4053. r = -ENXIO;
  4054. if (!kvm->arch.vpit)
  4055. goto out;
  4056. r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
  4057. if (r)
  4058. goto out;
  4059. r = -EFAULT;
  4060. if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
  4061. goto out;
  4062. r = 0;
  4063. break;
  4064. }
  4065. case KVM_SET_PIT: {
  4066. r = -EFAULT;
  4067. if (copy_from_user(&u.ps, argp, sizeof(u.ps)))
  4068. goto out;
  4069. r = -ENXIO;
  4070. if (!kvm->arch.vpit)
  4071. goto out;
  4072. r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
  4073. break;
  4074. }
  4075. case KVM_GET_PIT2: {
  4076. r = -ENXIO;
  4077. if (!kvm->arch.vpit)
  4078. goto out;
  4079. r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
  4080. if (r)
  4081. goto out;
  4082. r = -EFAULT;
  4083. if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
  4084. goto out;
  4085. r = 0;
  4086. break;
  4087. }
  4088. case KVM_SET_PIT2: {
  4089. r = -EFAULT;
  4090. if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
  4091. goto out;
  4092. r = -ENXIO;
  4093. if (!kvm->arch.vpit)
  4094. goto out;
  4095. r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
  4096. break;
  4097. }
  4098. case KVM_REINJECT_CONTROL: {
  4099. struct kvm_reinject_control control;
  4100. r = -EFAULT;
  4101. if (copy_from_user(&control, argp, sizeof(control)))
  4102. goto out;
  4103. r = kvm_vm_ioctl_reinject(kvm, &control);
  4104. break;
  4105. }
  4106. case KVM_SET_BOOT_CPU_ID:
  4107. r = 0;
  4108. mutex_lock(&kvm->lock);
  4109. if (kvm->created_vcpus)
  4110. r = -EBUSY;
  4111. else
  4112. kvm->arch.bsp_vcpu_id = arg;
  4113. mutex_unlock(&kvm->lock);
  4114. break;
  4115. case KVM_XEN_HVM_CONFIG: {
  4116. struct kvm_xen_hvm_config xhc;
  4117. r = -EFAULT;
  4118. if (copy_from_user(&xhc, argp, sizeof(xhc)))
  4119. goto out;
  4120. r = -EINVAL;
  4121. if (xhc.flags)
  4122. goto out;
  4123. memcpy(&kvm->arch.xen_hvm_config, &xhc, sizeof(xhc));
  4124. r = 0;
  4125. break;
  4126. }
  4127. case KVM_SET_CLOCK: {
  4128. struct kvm_clock_data user_ns;
  4129. u64 now_ns;
  4130. r = -EFAULT;
  4131. if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
  4132. goto out;
  4133. r = -EINVAL;
  4134. if (user_ns.flags)
  4135. goto out;
  4136. r = 0;
  4137. /*
  4138. * TODO: userspace has to take care of races with VCPU_RUN, so
  4139. * kvm_gen_update_masterclock() can be cut down to locked
  4140. * pvclock_update_vm_gtod_copy().
  4141. */
  4142. kvm_gen_update_masterclock(kvm);
  4143. now_ns = get_kvmclock_ns(kvm);
  4144. kvm->arch.kvmclock_offset += user_ns.clock - now_ns;
  4145. kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE);
  4146. break;
  4147. }
  4148. case KVM_GET_CLOCK: {
  4149. struct kvm_clock_data user_ns;
  4150. u64 now_ns;
  4151. now_ns = get_kvmclock_ns(kvm);
  4152. user_ns.clock = now_ns;
  4153. user_ns.flags = kvm->arch.use_master_clock ? KVM_CLOCK_TSC_STABLE : 0;
  4154. memset(&user_ns.pad, 0, sizeof(user_ns.pad));
  4155. r = -EFAULT;
  4156. if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
  4157. goto out;
  4158. r = 0;
  4159. break;
  4160. }
  4161. case KVM_ENABLE_CAP: {
  4162. struct kvm_enable_cap cap;
  4163. r = -EFAULT;
  4164. if (copy_from_user(&cap, argp, sizeof(cap)))
  4165. goto out;
  4166. r = kvm_vm_ioctl_enable_cap(kvm, &cap);
  4167. break;
  4168. }
  4169. case KVM_MEMORY_ENCRYPT_OP: {
  4170. r = -ENOTTY;
  4171. if (kvm_x86_ops->mem_enc_op)
  4172. r = kvm_x86_ops->mem_enc_op(kvm, argp);
  4173. break;
  4174. }
  4175. case KVM_MEMORY_ENCRYPT_REG_REGION: {
  4176. struct kvm_enc_region region;
  4177. r = -EFAULT;
  4178. if (copy_from_user(&region, argp, sizeof(region)))
  4179. goto out;
  4180. r = -ENOTTY;
  4181. if (kvm_x86_ops->mem_enc_reg_region)
  4182. r = kvm_x86_ops->mem_enc_reg_region(kvm, &region);
  4183. break;
  4184. }
  4185. case KVM_MEMORY_ENCRYPT_UNREG_REGION: {
  4186. struct kvm_enc_region region;
  4187. r = -EFAULT;
  4188. if (copy_from_user(&region, argp, sizeof(region)))
  4189. goto out;
  4190. r = -ENOTTY;
  4191. if (kvm_x86_ops->mem_enc_unreg_region)
  4192. r = kvm_x86_ops->mem_enc_unreg_region(kvm, &region);
  4193. break;
  4194. }
  4195. case KVM_HYPERV_EVENTFD: {
  4196. struct kvm_hyperv_eventfd hvevfd;
  4197. r = -EFAULT;
  4198. if (copy_from_user(&hvevfd, argp, sizeof(hvevfd)))
  4199. goto out;
  4200. r = kvm_vm_ioctl_hv_eventfd(kvm, &hvevfd);
  4201. break;
  4202. }
  4203. default:
  4204. r = -ENOTTY;
  4205. }
  4206. out:
  4207. return r;
  4208. }
  4209. static void kvm_init_msr_list(void)
  4210. {
  4211. u32 dummy[2];
  4212. unsigned i, j;
  4213. for (i = j = 0; i < ARRAY_SIZE(msrs_to_save); i++) {
  4214. if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
  4215. continue;
  4216. /*
  4217. * Even MSRs that are valid in the host may not be exposed
  4218. * to the guests in some cases.
  4219. */
  4220. switch (msrs_to_save[i]) {
  4221. case MSR_IA32_BNDCFGS:
  4222. if (!kvm_mpx_supported())
  4223. continue;
  4224. break;
  4225. case MSR_TSC_AUX:
  4226. if (!kvm_x86_ops->rdtscp_supported())
  4227. continue;
  4228. break;
  4229. default:
  4230. break;
  4231. }
  4232. if (j < i)
  4233. msrs_to_save[j] = msrs_to_save[i];
  4234. j++;
  4235. }
  4236. num_msrs_to_save = j;
  4237. for (i = j = 0; i < ARRAY_SIZE(emulated_msrs); i++) {
  4238. if (!kvm_x86_ops->has_emulated_msr(emulated_msrs[i]))
  4239. continue;
  4240. if (j < i)
  4241. emulated_msrs[j] = emulated_msrs[i];
  4242. j++;
  4243. }
  4244. num_emulated_msrs = j;
  4245. for (i = j = 0; i < ARRAY_SIZE(msr_based_features); i++) {
  4246. struct kvm_msr_entry msr;
  4247. msr.index = msr_based_features[i];
  4248. if (kvm_get_msr_feature(&msr))
  4249. continue;
  4250. if (j < i)
  4251. msr_based_features[j] = msr_based_features[i];
  4252. j++;
  4253. }
  4254. num_msr_based_features = j;
  4255. }
  4256. static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
  4257. const void *v)
  4258. {
  4259. int handled = 0;
  4260. int n;
  4261. do {
  4262. n = min(len, 8);
  4263. if (!(lapic_in_kernel(vcpu) &&
  4264. !kvm_iodevice_write(vcpu, &vcpu->arch.apic->dev, addr, n, v))
  4265. && kvm_io_bus_write(vcpu, KVM_MMIO_BUS, addr, n, v))
  4266. break;
  4267. handled += n;
  4268. addr += n;
  4269. len -= n;
  4270. v += n;
  4271. } while (len);
  4272. return handled;
  4273. }
  4274. static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
  4275. {
  4276. int handled = 0;
  4277. int n;
  4278. do {
  4279. n = min(len, 8);
  4280. if (!(lapic_in_kernel(vcpu) &&
  4281. !kvm_iodevice_read(vcpu, &vcpu->arch.apic->dev,
  4282. addr, n, v))
  4283. && kvm_io_bus_read(vcpu, KVM_MMIO_BUS, addr, n, v))
  4284. break;
  4285. trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, v);
  4286. handled += n;
  4287. addr += n;
  4288. len -= n;
  4289. v += n;
  4290. } while (len);
  4291. return handled;
  4292. }
  4293. static void kvm_set_segment(struct kvm_vcpu *vcpu,
  4294. struct kvm_segment *var, int seg)
  4295. {
  4296. kvm_x86_ops->set_segment(vcpu, var, seg);
  4297. }
  4298. void kvm_get_segment(struct kvm_vcpu *vcpu,
  4299. struct kvm_segment *var, int seg)
  4300. {
  4301. kvm_x86_ops->get_segment(vcpu, var, seg);
  4302. }
  4303. gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
  4304. struct x86_exception *exception)
  4305. {
  4306. gpa_t t_gpa;
  4307. BUG_ON(!mmu_is_nested(vcpu));
  4308. /* NPT walks are always user-walks */
  4309. access |= PFERR_USER_MASK;
  4310. t_gpa = vcpu->arch.mmu->gva_to_gpa(vcpu, gpa, access, exception);
  4311. return t_gpa;
  4312. }
  4313. gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
  4314. struct x86_exception *exception)
  4315. {
  4316. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4317. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4318. }
  4319. gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
  4320. struct x86_exception *exception)
  4321. {
  4322. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4323. access |= PFERR_FETCH_MASK;
  4324. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4325. }
  4326. gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
  4327. struct x86_exception *exception)
  4328. {
  4329. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4330. access |= PFERR_WRITE_MASK;
  4331. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4332. }
  4333. /* uses this to access any guest's mapped memory without checking CPL */
  4334. gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
  4335. struct x86_exception *exception)
  4336. {
  4337. return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
  4338. }
  4339. static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  4340. struct kvm_vcpu *vcpu, u32 access,
  4341. struct x86_exception *exception)
  4342. {
  4343. void *data = val;
  4344. int r = X86EMUL_CONTINUE;
  4345. while (bytes) {
  4346. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
  4347. exception);
  4348. unsigned offset = addr & (PAGE_SIZE-1);
  4349. unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
  4350. int ret;
  4351. if (gpa == UNMAPPED_GVA)
  4352. return X86EMUL_PROPAGATE_FAULT;
  4353. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, data,
  4354. offset, toread);
  4355. if (ret < 0) {
  4356. r = X86EMUL_IO_NEEDED;
  4357. goto out;
  4358. }
  4359. bytes -= toread;
  4360. data += toread;
  4361. addr += toread;
  4362. }
  4363. out:
  4364. return r;
  4365. }
  4366. /* used for instruction fetching */
  4367. static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
  4368. gva_t addr, void *val, unsigned int bytes,
  4369. struct x86_exception *exception)
  4370. {
  4371. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4372. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4373. unsigned offset;
  4374. int ret;
  4375. /* Inline kvm_read_guest_virt_helper for speed. */
  4376. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access|PFERR_FETCH_MASK,
  4377. exception);
  4378. if (unlikely(gpa == UNMAPPED_GVA))
  4379. return X86EMUL_PROPAGATE_FAULT;
  4380. offset = addr & (PAGE_SIZE-1);
  4381. if (WARN_ON(offset + bytes > PAGE_SIZE))
  4382. bytes = (unsigned)PAGE_SIZE - offset;
  4383. ret = kvm_vcpu_read_guest_page(vcpu, gpa >> PAGE_SHIFT, val,
  4384. offset, bytes);
  4385. if (unlikely(ret < 0))
  4386. return X86EMUL_IO_NEEDED;
  4387. return X86EMUL_CONTINUE;
  4388. }
  4389. int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
  4390. gva_t addr, void *val, unsigned int bytes,
  4391. struct x86_exception *exception)
  4392. {
  4393. u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
  4394. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
  4395. exception);
  4396. }
  4397. EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
  4398. static int emulator_read_std(struct x86_emulate_ctxt *ctxt,
  4399. gva_t addr, void *val, unsigned int bytes,
  4400. struct x86_exception *exception, bool system)
  4401. {
  4402. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4403. u32 access = 0;
  4404. if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
  4405. access |= PFERR_USER_MASK;
  4406. return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access, exception);
  4407. }
  4408. static int kvm_read_guest_phys_system(struct x86_emulate_ctxt *ctxt,
  4409. unsigned long addr, void *val, unsigned int bytes)
  4410. {
  4411. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4412. int r = kvm_vcpu_read_guest(vcpu, addr, val, bytes);
  4413. return r < 0 ? X86EMUL_IO_NEEDED : X86EMUL_CONTINUE;
  4414. }
  4415. static int kvm_write_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
  4416. struct kvm_vcpu *vcpu, u32 access,
  4417. struct x86_exception *exception)
  4418. {
  4419. void *data = val;
  4420. int r = X86EMUL_CONTINUE;
  4421. while (bytes) {
  4422. gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
  4423. access,
  4424. exception);
  4425. unsigned offset = addr & (PAGE_SIZE-1);
  4426. unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
  4427. int ret;
  4428. if (gpa == UNMAPPED_GVA)
  4429. return X86EMUL_PROPAGATE_FAULT;
  4430. ret = kvm_vcpu_write_guest(vcpu, gpa, data, towrite);
  4431. if (ret < 0) {
  4432. r = X86EMUL_IO_NEEDED;
  4433. goto out;
  4434. }
  4435. bytes -= towrite;
  4436. data += towrite;
  4437. addr += towrite;
  4438. }
  4439. out:
  4440. return r;
  4441. }
  4442. static int emulator_write_std(struct x86_emulate_ctxt *ctxt, gva_t addr, void *val,
  4443. unsigned int bytes, struct x86_exception *exception,
  4444. bool system)
  4445. {
  4446. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4447. u32 access = PFERR_WRITE_MASK;
  4448. if (!system && kvm_x86_ops->get_cpl(vcpu) == 3)
  4449. access |= PFERR_USER_MASK;
  4450. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  4451. access, exception);
  4452. }
  4453. int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu, gva_t addr, void *val,
  4454. unsigned int bytes, struct x86_exception *exception)
  4455. {
  4456. /* kvm_write_guest_virt_system can pull in tons of pages. */
  4457. vcpu->arch.l1tf_flush_l1d = true;
  4458. return kvm_write_guest_virt_helper(addr, val, bytes, vcpu,
  4459. PFERR_WRITE_MASK, exception);
  4460. }
  4461. EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
  4462. int handle_ud(struct kvm_vcpu *vcpu)
  4463. {
  4464. int emul_type = EMULTYPE_TRAP_UD;
  4465. enum emulation_result er;
  4466. char sig[5]; /* ud2; .ascii "kvm" */
  4467. struct x86_exception e;
  4468. if (force_emulation_prefix &&
  4469. kvm_read_guest_virt(vcpu, kvm_get_linear_rip(vcpu),
  4470. sig, sizeof(sig), &e) == 0 &&
  4471. memcmp(sig, "\xf\xbkvm", sizeof(sig)) == 0) {
  4472. kvm_rip_write(vcpu, kvm_rip_read(vcpu) + sizeof(sig));
  4473. emul_type = 0;
  4474. }
  4475. er = kvm_emulate_instruction(vcpu, emul_type);
  4476. if (er == EMULATE_USER_EXIT)
  4477. return 0;
  4478. if (er != EMULATE_DONE)
  4479. kvm_queue_exception(vcpu, UD_VECTOR);
  4480. return 1;
  4481. }
  4482. EXPORT_SYMBOL_GPL(handle_ud);
  4483. static int vcpu_is_mmio_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  4484. gpa_t gpa, bool write)
  4485. {
  4486. /* For APIC access vmexit */
  4487. if ((gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  4488. return 1;
  4489. if (vcpu_match_mmio_gpa(vcpu, gpa)) {
  4490. trace_vcpu_match_mmio(gva, gpa, write, true);
  4491. return 1;
  4492. }
  4493. return 0;
  4494. }
  4495. static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
  4496. gpa_t *gpa, struct x86_exception *exception,
  4497. bool write)
  4498. {
  4499. u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
  4500. | (write ? PFERR_WRITE_MASK : 0);
  4501. /*
  4502. * currently PKRU is only applied to ept enabled guest so
  4503. * there is no pkey in EPT page table for L1 guest or EPT
  4504. * shadow page table for L2 guest.
  4505. */
  4506. if (vcpu_match_mmio_gva(vcpu, gva)
  4507. && !permission_fault(vcpu, vcpu->arch.walk_mmu,
  4508. vcpu->arch.access, 0, access)) {
  4509. *gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
  4510. (gva & (PAGE_SIZE - 1));
  4511. trace_vcpu_match_mmio(gva, *gpa, write, false);
  4512. return 1;
  4513. }
  4514. *gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
  4515. if (*gpa == UNMAPPED_GVA)
  4516. return -1;
  4517. return vcpu_is_mmio_gpa(vcpu, gva, *gpa, write);
  4518. }
  4519. int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
  4520. const void *val, int bytes)
  4521. {
  4522. int ret;
  4523. ret = kvm_vcpu_write_guest(vcpu, gpa, val, bytes);
  4524. if (ret < 0)
  4525. return 0;
  4526. kvm_page_track_write(vcpu, gpa, val, bytes);
  4527. return 1;
  4528. }
  4529. struct read_write_emulator_ops {
  4530. int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
  4531. int bytes);
  4532. int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4533. void *val, int bytes);
  4534. int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4535. int bytes, void *val);
  4536. int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
  4537. void *val, int bytes);
  4538. bool write;
  4539. };
  4540. static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
  4541. {
  4542. if (vcpu->mmio_read_completed) {
  4543. trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
  4544. vcpu->mmio_fragments[0].gpa, val);
  4545. vcpu->mmio_read_completed = 0;
  4546. return 1;
  4547. }
  4548. return 0;
  4549. }
  4550. static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  4551. void *val, int bytes)
  4552. {
  4553. return !kvm_vcpu_read_guest(vcpu, gpa, val, bytes);
  4554. }
  4555. static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
  4556. void *val, int bytes)
  4557. {
  4558. return emulator_write_phys(vcpu, gpa, val, bytes);
  4559. }
  4560. static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
  4561. {
  4562. trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, val);
  4563. return vcpu_mmio_write(vcpu, gpa, bytes, val);
  4564. }
  4565. static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  4566. void *val, int bytes)
  4567. {
  4568. trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, NULL);
  4569. return X86EMUL_IO_NEEDED;
  4570. }
  4571. static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
  4572. void *val, int bytes)
  4573. {
  4574. struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
  4575. memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
  4576. return X86EMUL_CONTINUE;
  4577. }
  4578. static const struct read_write_emulator_ops read_emultor = {
  4579. .read_write_prepare = read_prepare,
  4580. .read_write_emulate = read_emulate,
  4581. .read_write_mmio = vcpu_mmio_read,
  4582. .read_write_exit_mmio = read_exit_mmio,
  4583. };
  4584. static const struct read_write_emulator_ops write_emultor = {
  4585. .read_write_emulate = write_emulate,
  4586. .read_write_mmio = write_mmio,
  4587. .read_write_exit_mmio = write_exit_mmio,
  4588. .write = true,
  4589. };
  4590. static int emulator_read_write_onepage(unsigned long addr, void *val,
  4591. unsigned int bytes,
  4592. struct x86_exception *exception,
  4593. struct kvm_vcpu *vcpu,
  4594. const struct read_write_emulator_ops *ops)
  4595. {
  4596. gpa_t gpa;
  4597. int handled, ret;
  4598. bool write = ops->write;
  4599. struct kvm_mmio_fragment *frag;
  4600. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  4601. /*
  4602. * If the exit was due to a NPF we may already have a GPA.
  4603. * If the GPA is present, use it to avoid the GVA to GPA table walk.
  4604. * Note, this cannot be used on string operations since string
  4605. * operation using rep will only have the initial GPA from the NPF
  4606. * occurred.
  4607. */
  4608. if (vcpu->arch.gpa_available &&
  4609. emulator_can_use_gpa(ctxt) &&
  4610. (addr & ~PAGE_MASK) == (vcpu->arch.gpa_val & ~PAGE_MASK)) {
  4611. gpa = vcpu->arch.gpa_val;
  4612. ret = vcpu_is_mmio_gpa(vcpu, addr, gpa, write);
  4613. } else {
  4614. ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
  4615. if (ret < 0)
  4616. return X86EMUL_PROPAGATE_FAULT;
  4617. }
  4618. if (!ret && ops->read_write_emulate(vcpu, gpa, val, bytes))
  4619. return X86EMUL_CONTINUE;
  4620. /*
  4621. * Is this MMIO handled locally?
  4622. */
  4623. handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
  4624. if (handled == bytes)
  4625. return X86EMUL_CONTINUE;
  4626. gpa += handled;
  4627. bytes -= handled;
  4628. val += handled;
  4629. WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
  4630. frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
  4631. frag->gpa = gpa;
  4632. frag->data = val;
  4633. frag->len = bytes;
  4634. return X86EMUL_CONTINUE;
  4635. }
  4636. static int emulator_read_write(struct x86_emulate_ctxt *ctxt,
  4637. unsigned long addr,
  4638. void *val, unsigned int bytes,
  4639. struct x86_exception *exception,
  4640. const struct read_write_emulator_ops *ops)
  4641. {
  4642. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4643. gpa_t gpa;
  4644. int rc;
  4645. if (ops->read_write_prepare &&
  4646. ops->read_write_prepare(vcpu, val, bytes))
  4647. return X86EMUL_CONTINUE;
  4648. vcpu->mmio_nr_fragments = 0;
  4649. /* Crossing a page boundary? */
  4650. if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
  4651. int now;
  4652. now = -addr & ~PAGE_MASK;
  4653. rc = emulator_read_write_onepage(addr, val, now, exception,
  4654. vcpu, ops);
  4655. if (rc != X86EMUL_CONTINUE)
  4656. return rc;
  4657. addr += now;
  4658. if (ctxt->mode != X86EMUL_MODE_PROT64)
  4659. addr = (u32)addr;
  4660. val += now;
  4661. bytes -= now;
  4662. }
  4663. rc = emulator_read_write_onepage(addr, val, bytes, exception,
  4664. vcpu, ops);
  4665. if (rc != X86EMUL_CONTINUE)
  4666. return rc;
  4667. if (!vcpu->mmio_nr_fragments)
  4668. return rc;
  4669. gpa = vcpu->mmio_fragments[0].gpa;
  4670. vcpu->mmio_needed = 1;
  4671. vcpu->mmio_cur_fragment = 0;
  4672. vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
  4673. vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
  4674. vcpu->run->exit_reason = KVM_EXIT_MMIO;
  4675. vcpu->run->mmio.phys_addr = gpa;
  4676. return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
  4677. }
  4678. static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
  4679. unsigned long addr,
  4680. void *val,
  4681. unsigned int bytes,
  4682. struct x86_exception *exception)
  4683. {
  4684. return emulator_read_write(ctxt, addr, val, bytes,
  4685. exception, &read_emultor);
  4686. }
  4687. static int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
  4688. unsigned long addr,
  4689. const void *val,
  4690. unsigned int bytes,
  4691. struct x86_exception *exception)
  4692. {
  4693. return emulator_read_write(ctxt, addr, (void *)val, bytes,
  4694. exception, &write_emultor);
  4695. }
  4696. #define CMPXCHG_TYPE(t, ptr, old, new) \
  4697. (cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
  4698. #ifdef CONFIG_X86_64
  4699. # define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
  4700. #else
  4701. # define CMPXCHG64(ptr, old, new) \
  4702. (cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
  4703. #endif
  4704. static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
  4705. unsigned long addr,
  4706. const void *old,
  4707. const void *new,
  4708. unsigned int bytes,
  4709. struct x86_exception *exception)
  4710. {
  4711. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4712. gpa_t gpa;
  4713. struct page *page;
  4714. char *kaddr;
  4715. bool exchanged;
  4716. /* guests cmpxchg8b have to be emulated atomically */
  4717. if (bytes > 8 || (bytes & (bytes - 1)))
  4718. goto emul_write;
  4719. gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
  4720. if (gpa == UNMAPPED_GVA ||
  4721. (gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
  4722. goto emul_write;
  4723. if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
  4724. goto emul_write;
  4725. page = kvm_vcpu_gfn_to_page(vcpu, gpa >> PAGE_SHIFT);
  4726. if (is_error_page(page))
  4727. goto emul_write;
  4728. kaddr = kmap_atomic(page);
  4729. kaddr += offset_in_page(gpa);
  4730. switch (bytes) {
  4731. case 1:
  4732. exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
  4733. break;
  4734. case 2:
  4735. exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
  4736. break;
  4737. case 4:
  4738. exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
  4739. break;
  4740. case 8:
  4741. exchanged = CMPXCHG64(kaddr, old, new);
  4742. break;
  4743. default:
  4744. BUG();
  4745. }
  4746. kunmap_atomic(kaddr);
  4747. kvm_release_page_dirty(page);
  4748. if (!exchanged)
  4749. return X86EMUL_CMPXCHG_FAILED;
  4750. kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
  4751. kvm_page_track_write(vcpu, gpa, new, bytes);
  4752. return X86EMUL_CONTINUE;
  4753. emul_write:
  4754. printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
  4755. return emulator_write_emulated(ctxt, addr, new, bytes, exception);
  4756. }
  4757. static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
  4758. {
  4759. int r = 0, i;
  4760. for (i = 0; i < vcpu->arch.pio.count; i++) {
  4761. if (vcpu->arch.pio.in)
  4762. r = kvm_io_bus_read(vcpu, KVM_PIO_BUS, vcpu->arch.pio.port,
  4763. vcpu->arch.pio.size, pd);
  4764. else
  4765. r = kvm_io_bus_write(vcpu, KVM_PIO_BUS,
  4766. vcpu->arch.pio.port, vcpu->arch.pio.size,
  4767. pd);
  4768. if (r)
  4769. break;
  4770. pd += vcpu->arch.pio.size;
  4771. }
  4772. return r;
  4773. }
  4774. static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
  4775. unsigned short port, void *val,
  4776. unsigned int count, bool in)
  4777. {
  4778. vcpu->arch.pio.port = port;
  4779. vcpu->arch.pio.in = in;
  4780. vcpu->arch.pio.count = count;
  4781. vcpu->arch.pio.size = size;
  4782. if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
  4783. vcpu->arch.pio.count = 0;
  4784. return 1;
  4785. }
  4786. vcpu->run->exit_reason = KVM_EXIT_IO;
  4787. vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
  4788. vcpu->run->io.size = size;
  4789. vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
  4790. vcpu->run->io.count = count;
  4791. vcpu->run->io.port = port;
  4792. return 0;
  4793. }
  4794. static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
  4795. int size, unsigned short port, void *val,
  4796. unsigned int count)
  4797. {
  4798. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4799. int ret;
  4800. if (vcpu->arch.pio.count)
  4801. goto data_avail;
  4802. memset(vcpu->arch.pio_data, 0, size * count);
  4803. ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
  4804. if (ret) {
  4805. data_avail:
  4806. memcpy(val, vcpu->arch.pio_data, size * count);
  4807. trace_kvm_pio(KVM_PIO_IN, port, size, count, vcpu->arch.pio_data);
  4808. vcpu->arch.pio.count = 0;
  4809. return 1;
  4810. }
  4811. return 0;
  4812. }
  4813. static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
  4814. int size, unsigned short port,
  4815. const void *val, unsigned int count)
  4816. {
  4817. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4818. memcpy(vcpu->arch.pio_data, val, size * count);
  4819. trace_kvm_pio(KVM_PIO_OUT, port, size, count, vcpu->arch.pio_data);
  4820. return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
  4821. }
  4822. static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
  4823. {
  4824. return kvm_x86_ops->get_segment_base(vcpu, seg);
  4825. }
  4826. static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
  4827. {
  4828. kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
  4829. }
  4830. static int kvm_emulate_wbinvd_noskip(struct kvm_vcpu *vcpu)
  4831. {
  4832. if (!need_emulate_wbinvd(vcpu))
  4833. return X86EMUL_CONTINUE;
  4834. if (kvm_x86_ops->has_wbinvd_exit()) {
  4835. int cpu = get_cpu();
  4836. cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
  4837. smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
  4838. wbinvd_ipi, NULL, 1);
  4839. put_cpu();
  4840. cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
  4841. } else
  4842. wbinvd();
  4843. return X86EMUL_CONTINUE;
  4844. }
  4845. int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
  4846. {
  4847. kvm_emulate_wbinvd_noskip(vcpu);
  4848. return kvm_skip_emulated_instruction(vcpu);
  4849. }
  4850. EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
  4851. static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
  4852. {
  4853. kvm_emulate_wbinvd_noskip(emul_to_vcpu(ctxt));
  4854. }
  4855. static int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4856. unsigned long *dest)
  4857. {
  4858. return kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
  4859. }
  4860. static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
  4861. unsigned long value)
  4862. {
  4863. return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
  4864. }
  4865. static u64 mk_cr_64(u64 curr_cr, u32 new_val)
  4866. {
  4867. return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
  4868. }
  4869. static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
  4870. {
  4871. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4872. unsigned long value;
  4873. switch (cr) {
  4874. case 0:
  4875. value = kvm_read_cr0(vcpu);
  4876. break;
  4877. case 2:
  4878. value = vcpu->arch.cr2;
  4879. break;
  4880. case 3:
  4881. value = kvm_read_cr3(vcpu);
  4882. break;
  4883. case 4:
  4884. value = kvm_read_cr4(vcpu);
  4885. break;
  4886. case 8:
  4887. value = kvm_get_cr8(vcpu);
  4888. break;
  4889. default:
  4890. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4891. return 0;
  4892. }
  4893. return value;
  4894. }
  4895. static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
  4896. {
  4897. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4898. int res = 0;
  4899. switch (cr) {
  4900. case 0:
  4901. res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
  4902. break;
  4903. case 2:
  4904. vcpu->arch.cr2 = val;
  4905. break;
  4906. case 3:
  4907. res = kvm_set_cr3(vcpu, val);
  4908. break;
  4909. case 4:
  4910. res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
  4911. break;
  4912. case 8:
  4913. res = kvm_set_cr8(vcpu, val);
  4914. break;
  4915. default:
  4916. kvm_err("%s: unexpected cr %u\n", __func__, cr);
  4917. res = -1;
  4918. }
  4919. return res;
  4920. }
  4921. static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
  4922. {
  4923. return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
  4924. }
  4925. static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4926. {
  4927. kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
  4928. }
  4929. static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4930. {
  4931. kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
  4932. }
  4933. static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4934. {
  4935. kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
  4936. }
  4937. static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
  4938. {
  4939. kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
  4940. }
  4941. static unsigned long emulator_get_cached_segment_base(
  4942. struct x86_emulate_ctxt *ctxt, int seg)
  4943. {
  4944. return get_segment_base(emul_to_vcpu(ctxt), seg);
  4945. }
  4946. static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
  4947. struct desc_struct *desc, u32 *base3,
  4948. int seg)
  4949. {
  4950. struct kvm_segment var;
  4951. kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
  4952. *selector = var.selector;
  4953. if (var.unusable) {
  4954. memset(desc, 0, sizeof(*desc));
  4955. if (base3)
  4956. *base3 = 0;
  4957. return false;
  4958. }
  4959. if (var.g)
  4960. var.limit >>= 12;
  4961. set_desc_limit(desc, var.limit);
  4962. set_desc_base(desc, (unsigned long)var.base);
  4963. #ifdef CONFIG_X86_64
  4964. if (base3)
  4965. *base3 = var.base >> 32;
  4966. #endif
  4967. desc->type = var.type;
  4968. desc->s = var.s;
  4969. desc->dpl = var.dpl;
  4970. desc->p = var.present;
  4971. desc->avl = var.avl;
  4972. desc->l = var.l;
  4973. desc->d = var.db;
  4974. desc->g = var.g;
  4975. return true;
  4976. }
  4977. static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
  4978. struct desc_struct *desc, u32 base3,
  4979. int seg)
  4980. {
  4981. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  4982. struct kvm_segment var;
  4983. var.selector = selector;
  4984. var.base = get_desc_base(desc);
  4985. #ifdef CONFIG_X86_64
  4986. var.base |= ((u64)base3) << 32;
  4987. #endif
  4988. var.limit = get_desc_limit(desc);
  4989. if (desc->g)
  4990. var.limit = (var.limit << 12) | 0xfff;
  4991. var.type = desc->type;
  4992. var.dpl = desc->dpl;
  4993. var.db = desc->d;
  4994. var.s = desc->s;
  4995. var.l = desc->l;
  4996. var.g = desc->g;
  4997. var.avl = desc->avl;
  4998. var.present = desc->p;
  4999. var.unusable = !var.present;
  5000. var.padding = 0;
  5001. kvm_set_segment(vcpu, &var, seg);
  5002. return;
  5003. }
  5004. static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
  5005. u32 msr_index, u64 *pdata)
  5006. {
  5007. struct msr_data msr;
  5008. int r;
  5009. msr.index = msr_index;
  5010. msr.host_initiated = false;
  5011. r = kvm_get_msr(emul_to_vcpu(ctxt), &msr);
  5012. if (r)
  5013. return r;
  5014. *pdata = msr.data;
  5015. return 0;
  5016. }
  5017. static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
  5018. u32 msr_index, u64 data)
  5019. {
  5020. struct msr_data msr;
  5021. msr.data = data;
  5022. msr.index = msr_index;
  5023. msr.host_initiated = false;
  5024. return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
  5025. }
  5026. static u64 emulator_get_smbase(struct x86_emulate_ctxt *ctxt)
  5027. {
  5028. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5029. return vcpu->arch.smbase;
  5030. }
  5031. static void emulator_set_smbase(struct x86_emulate_ctxt *ctxt, u64 smbase)
  5032. {
  5033. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5034. vcpu->arch.smbase = smbase;
  5035. }
  5036. static int emulator_check_pmc(struct x86_emulate_ctxt *ctxt,
  5037. u32 pmc)
  5038. {
  5039. return kvm_pmu_is_valid_msr_idx(emul_to_vcpu(ctxt), pmc);
  5040. }
  5041. static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
  5042. u32 pmc, u64 *pdata)
  5043. {
  5044. return kvm_pmu_rdpmc(emul_to_vcpu(ctxt), pmc, pdata);
  5045. }
  5046. static void emulator_halt(struct x86_emulate_ctxt *ctxt)
  5047. {
  5048. emul_to_vcpu(ctxt)->arch.halt_request = 1;
  5049. }
  5050. static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
  5051. struct x86_instruction_info *info,
  5052. enum x86_intercept_stage stage)
  5053. {
  5054. return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
  5055. }
  5056. static bool emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
  5057. u32 *eax, u32 *ebx, u32 *ecx, u32 *edx, bool check_limit)
  5058. {
  5059. return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
  5060. }
  5061. static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  5062. {
  5063. return kvm_register_read(emul_to_vcpu(ctxt), reg);
  5064. }
  5065. static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
  5066. {
  5067. kvm_register_write(emul_to_vcpu(ctxt), reg, val);
  5068. }
  5069. static void emulator_set_nmi_mask(struct x86_emulate_ctxt *ctxt, bool masked)
  5070. {
  5071. kvm_x86_ops->set_nmi_mask(emul_to_vcpu(ctxt), masked);
  5072. }
  5073. static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
  5074. {
  5075. return emul_to_vcpu(ctxt)->arch.hflags;
  5076. }
  5077. static void emulator_set_hflags(struct x86_emulate_ctxt *ctxt, unsigned emul_flags)
  5078. {
  5079. kvm_set_hflags(emul_to_vcpu(ctxt), emul_flags);
  5080. }
  5081. static int emulator_pre_leave_smm(struct x86_emulate_ctxt *ctxt, u64 smbase)
  5082. {
  5083. return kvm_x86_ops->pre_leave_smm(emul_to_vcpu(ctxt), smbase);
  5084. }
  5085. static const struct x86_emulate_ops emulate_ops = {
  5086. .read_gpr = emulator_read_gpr,
  5087. .write_gpr = emulator_write_gpr,
  5088. .read_std = emulator_read_std,
  5089. .write_std = emulator_write_std,
  5090. .read_phys = kvm_read_guest_phys_system,
  5091. .fetch = kvm_fetch_guest_virt,
  5092. .read_emulated = emulator_read_emulated,
  5093. .write_emulated = emulator_write_emulated,
  5094. .cmpxchg_emulated = emulator_cmpxchg_emulated,
  5095. .invlpg = emulator_invlpg,
  5096. .pio_in_emulated = emulator_pio_in_emulated,
  5097. .pio_out_emulated = emulator_pio_out_emulated,
  5098. .get_segment = emulator_get_segment,
  5099. .set_segment = emulator_set_segment,
  5100. .get_cached_segment_base = emulator_get_cached_segment_base,
  5101. .get_gdt = emulator_get_gdt,
  5102. .get_idt = emulator_get_idt,
  5103. .set_gdt = emulator_set_gdt,
  5104. .set_idt = emulator_set_idt,
  5105. .get_cr = emulator_get_cr,
  5106. .set_cr = emulator_set_cr,
  5107. .cpl = emulator_get_cpl,
  5108. .get_dr = emulator_get_dr,
  5109. .set_dr = emulator_set_dr,
  5110. .get_smbase = emulator_get_smbase,
  5111. .set_smbase = emulator_set_smbase,
  5112. .set_msr = emulator_set_msr,
  5113. .get_msr = emulator_get_msr,
  5114. .check_pmc = emulator_check_pmc,
  5115. .read_pmc = emulator_read_pmc,
  5116. .halt = emulator_halt,
  5117. .wbinvd = emulator_wbinvd,
  5118. .fix_hypercall = emulator_fix_hypercall,
  5119. .intercept = emulator_intercept,
  5120. .get_cpuid = emulator_get_cpuid,
  5121. .set_nmi_mask = emulator_set_nmi_mask,
  5122. .get_hflags = emulator_get_hflags,
  5123. .set_hflags = emulator_set_hflags,
  5124. .pre_leave_smm = emulator_pre_leave_smm,
  5125. };
  5126. static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
  5127. {
  5128. u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu);
  5129. /*
  5130. * an sti; sti; sequence only disable interrupts for the first
  5131. * instruction. So, if the last instruction, be it emulated or
  5132. * not, left the system with the INT_STI flag enabled, it
  5133. * means that the last instruction is an sti. We should not
  5134. * leave the flag on in this case. The same goes for mov ss
  5135. */
  5136. if (int_shadow & mask)
  5137. mask = 0;
  5138. if (unlikely(int_shadow || mask)) {
  5139. kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
  5140. if (!mask)
  5141. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5142. }
  5143. }
  5144. static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
  5145. {
  5146. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5147. if (ctxt->exception.vector == PF_VECTOR)
  5148. return kvm_propagate_fault(vcpu, &ctxt->exception);
  5149. if (ctxt->exception.error_code_valid)
  5150. kvm_queue_exception_e(vcpu, ctxt->exception.vector,
  5151. ctxt->exception.error_code);
  5152. else
  5153. kvm_queue_exception(vcpu, ctxt->exception.vector);
  5154. return false;
  5155. }
  5156. static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
  5157. {
  5158. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5159. int cs_db, cs_l;
  5160. kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
  5161. ctxt->eflags = kvm_get_rflags(vcpu);
  5162. ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
  5163. ctxt->eip = kvm_rip_read(vcpu);
  5164. ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
  5165. (ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
  5166. (cs_l && is_long_mode(vcpu)) ? X86EMUL_MODE_PROT64 :
  5167. cs_db ? X86EMUL_MODE_PROT32 :
  5168. X86EMUL_MODE_PROT16;
  5169. BUILD_BUG_ON(HF_GUEST_MASK != X86EMUL_GUEST_MASK);
  5170. BUILD_BUG_ON(HF_SMM_MASK != X86EMUL_SMM_MASK);
  5171. BUILD_BUG_ON(HF_SMM_INSIDE_NMI_MASK != X86EMUL_SMM_INSIDE_NMI_MASK);
  5172. init_decode_cache(ctxt);
  5173. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  5174. }
  5175. int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
  5176. {
  5177. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5178. int ret;
  5179. init_emulate_ctxt(vcpu);
  5180. ctxt->op_bytes = 2;
  5181. ctxt->ad_bytes = 2;
  5182. ctxt->_eip = ctxt->eip + inc_eip;
  5183. ret = emulate_int_real(ctxt, irq);
  5184. if (ret != X86EMUL_CONTINUE)
  5185. return EMULATE_FAIL;
  5186. ctxt->eip = ctxt->_eip;
  5187. kvm_rip_write(vcpu, ctxt->eip);
  5188. kvm_set_rflags(vcpu, ctxt->eflags);
  5189. return EMULATE_DONE;
  5190. }
  5191. EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
  5192. static int handle_emulation_failure(struct kvm_vcpu *vcpu, int emulation_type)
  5193. {
  5194. int r = EMULATE_DONE;
  5195. ++vcpu->stat.insn_emulation_fail;
  5196. trace_kvm_emulate_insn_failed(vcpu);
  5197. if (emulation_type & EMULTYPE_NO_UD_ON_FAIL)
  5198. return EMULATE_FAIL;
  5199. if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) {
  5200. vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
  5201. vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
  5202. vcpu->run->internal.ndata = 0;
  5203. r = EMULATE_USER_EXIT;
  5204. }
  5205. kvm_queue_exception(vcpu, UD_VECTOR);
  5206. return r;
  5207. }
  5208. static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
  5209. bool write_fault_to_shadow_pgtable,
  5210. int emulation_type)
  5211. {
  5212. gpa_t gpa = cr2;
  5213. kvm_pfn_t pfn;
  5214. if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
  5215. return false;
  5216. if (WARN_ON_ONCE(is_guest_mode(vcpu)))
  5217. return false;
  5218. if (!vcpu->arch.mmu->direct_map) {
  5219. /*
  5220. * Write permission should be allowed since only
  5221. * write access need to be emulated.
  5222. */
  5223. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  5224. /*
  5225. * If the mapping is invalid in guest, let cpu retry
  5226. * it to generate fault.
  5227. */
  5228. if (gpa == UNMAPPED_GVA)
  5229. return true;
  5230. }
  5231. /*
  5232. * Do not retry the unhandleable instruction if it faults on the
  5233. * readonly host memory, otherwise it will goto a infinite loop:
  5234. * retry instruction -> write #PF -> emulation fail -> retry
  5235. * instruction -> ...
  5236. */
  5237. pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
  5238. /*
  5239. * If the instruction failed on the error pfn, it can not be fixed,
  5240. * report the error to userspace.
  5241. */
  5242. if (is_error_noslot_pfn(pfn))
  5243. return false;
  5244. kvm_release_pfn_clean(pfn);
  5245. /* The instructions are well-emulated on direct mmu. */
  5246. if (vcpu->arch.mmu->direct_map) {
  5247. unsigned int indirect_shadow_pages;
  5248. spin_lock(&vcpu->kvm->mmu_lock);
  5249. indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
  5250. spin_unlock(&vcpu->kvm->mmu_lock);
  5251. if (indirect_shadow_pages)
  5252. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5253. return true;
  5254. }
  5255. /*
  5256. * if emulation was due to access to shadowed page table
  5257. * and it failed try to unshadow page and re-enter the
  5258. * guest to let CPU execute the instruction.
  5259. */
  5260. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5261. /*
  5262. * If the access faults on its page table, it can not
  5263. * be fixed by unprotecting shadow page and it should
  5264. * be reported to userspace.
  5265. */
  5266. return !write_fault_to_shadow_pgtable;
  5267. }
  5268. static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
  5269. unsigned long cr2, int emulation_type)
  5270. {
  5271. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  5272. unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
  5273. last_retry_eip = vcpu->arch.last_retry_eip;
  5274. last_retry_addr = vcpu->arch.last_retry_addr;
  5275. /*
  5276. * If the emulation is caused by #PF and it is non-page_table
  5277. * writing instruction, it means the VM-EXIT is caused by shadow
  5278. * page protected, we can zap the shadow page and retry this
  5279. * instruction directly.
  5280. *
  5281. * Note: if the guest uses a non-page-table modifying instruction
  5282. * on the PDE that points to the instruction, then we will unmap
  5283. * the instruction and go to an infinite loop. So, we cache the
  5284. * last retried eip and the last fault address, if we meet the eip
  5285. * and the address again, we can break out of the potential infinite
  5286. * loop.
  5287. */
  5288. vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
  5289. if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
  5290. return false;
  5291. if (WARN_ON_ONCE(is_guest_mode(vcpu)))
  5292. return false;
  5293. if (x86_page_table_writing_insn(ctxt))
  5294. return false;
  5295. if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
  5296. return false;
  5297. vcpu->arch.last_retry_eip = ctxt->eip;
  5298. vcpu->arch.last_retry_addr = cr2;
  5299. if (!vcpu->arch.mmu->direct_map)
  5300. gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
  5301. kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  5302. return true;
  5303. }
  5304. static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
  5305. static int complete_emulated_pio(struct kvm_vcpu *vcpu);
  5306. static void kvm_smm_changed(struct kvm_vcpu *vcpu)
  5307. {
  5308. if (!(vcpu->arch.hflags & HF_SMM_MASK)) {
  5309. /* This is a good place to trace that we are exiting SMM. */
  5310. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, false);
  5311. /* Process a latched INIT or SMI, if any. */
  5312. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5313. }
  5314. kvm_mmu_reset_context(vcpu);
  5315. }
  5316. static void kvm_set_hflags(struct kvm_vcpu *vcpu, unsigned emul_flags)
  5317. {
  5318. unsigned changed = vcpu->arch.hflags ^ emul_flags;
  5319. vcpu->arch.hflags = emul_flags;
  5320. if (changed & HF_SMM_MASK)
  5321. kvm_smm_changed(vcpu);
  5322. }
  5323. static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
  5324. unsigned long *db)
  5325. {
  5326. u32 dr6 = 0;
  5327. int i;
  5328. u32 enable, rwlen;
  5329. enable = dr7;
  5330. rwlen = dr7 >> 16;
  5331. for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
  5332. if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
  5333. dr6 |= (1 << i);
  5334. return dr6;
  5335. }
  5336. static void kvm_vcpu_do_singlestep(struct kvm_vcpu *vcpu, int *r)
  5337. {
  5338. struct kvm_run *kvm_run = vcpu->run;
  5339. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
  5340. kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM;
  5341. kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
  5342. kvm_run->debug.arch.exception = DB_VECTOR;
  5343. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  5344. *r = EMULATE_USER_EXIT;
  5345. } else {
  5346. kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BS);
  5347. }
  5348. }
  5349. int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
  5350. {
  5351. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  5352. int r = EMULATE_DONE;
  5353. kvm_x86_ops->skip_emulated_instruction(vcpu);
  5354. /*
  5355. * rflags is the old, "raw" value of the flags. The new value has
  5356. * not been saved yet.
  5357. *
  5358. * This is correct even for TF set by the guest, because "the
  5359. * processor will not generate this exception after the instruction
  5360. * that sets the TF flag".
  5361. */
  5362. if (unlikely(rflags & X86_EFLAGS_TF))
  5363. kvm_vcpu_do_singlestep(vcpu, &r);
  5364. return r == EMULATE_DONE;
  5365. }
  5366. EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
  5367. static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
  5368. {
  5369. if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
  5370. (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
  5371. struct kvm_run *kvm_run = vcpu->run;
  5372. unsigned long eip = kvm_get_linear_rip(vcpu);
  5373. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  5374. vcpu->arch.guest_debug_dr7,
  5375. vcpu->arch.eff_db);
  5376. if (dr6 != 0) {
  5377. kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
  5378. kvm_run->debug.arch.pc = eip;
  5379. kvm_run->debug.arch.exception = DB_VECTOR;
  5380. kvm_run->exit_reason = KVM_EXIT_DEBUG;
  5381. *r = EMULATE_USER_EXIT;
  5382. return true;
  5383. }
  5384. }
  5385. if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK) &&
  5386. !(kvm_get_rflags(vcpu) & X86_EFLAGS_RF)) {
  5387. unsigned long eip = kvm_get_linear_rip(vcpu);
  5388. u32 dr6 = kvm_vcpu_check_hw_bp(eip, 0,
  5389. vcpu->arch.dr7,
  5390. vcpu->arch.db);
  5391. if (dr6 != 0) {
  5392. vcpu->arch.dr6 &= ~15;
  5393. vcpu->arch.dr6 |= dr6 | DR6_RTM;
  5394. kvm_queue_exception(vcpu, DB_VECTOR);
  5395. *r = EMULATE_DONE;
  5396. return true;
  5397. }
  5398. }
  5399. return false;
  5400. }
  5401. static bool is_vmware_backdoor_opcode(struct x86_emulate_ctxt *ctxt)
  5402. {
  5403. switch (ctxt->opcode_len) {
  5404. case 1:
  5405. switch (ctxt->b) {
  5406. case 0xe4: /* IN */
  5407. case 0xe5:
  5408. case 0xec:
  5409. case 0xed:
  5410. case 0xe6: /* OUT */
  5411. case 0xe7:
  5412. case 0xee:
  5413. case 0xef:
  5414. case 0x6c: /* INS */
  5415. case 0x6d:
  5416. case 0x6e: /* OUTS */
  5417. case 0x6f:
  5418. return true;
  5419. }
  5420. break;
  5421. case 2:
  5422. switch (ctxt->b) {
  5423. case 0x33: /* RDPMC */
  5424. return true;
  5425. }
  5426. break;
  5427. }
  5428. return false;
  5429. }
  5430. int x86_emulate_instruction(struct kvm_vcpu *vcpu,
  5431. unsigned long cr2,
  5432. int emulation_type,
  5433. void *insn,
  5434. int insn_len)
  5435. {
  5436. int r;
  5437. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  5438. bool writeback = true;
  5439. bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
  5440. vcpu->arch.l1tf_flush_l1d = true;
  5441. /*
  5442. * Clear write_fault_to_shadow_pgtable here to ensure it is
  5443. * never reused.
  5444. */
  5445. vcpu->arch.write_fault_to_shadow_pgtable = false;
  5446. kvm_clear_exception_queue(vcpu);
  5447. if (!(emulation_type & EMULTYPE_NO_DECODE)) {
  5448. init_emulate_ctxt(vcpu);
  5449. /*
  5450. * We will reenter on the same instruction since
  5451. * we do not set complete_userspace_io. This does not
  5452. * handle watchpoints yet, those would be handled in
  5453. * the emulate_ops.
  5454. */
  5455. if (!(emulation_type & EMULTYPE_SKIP) &&
  5456. kvm_vcpu_check_breakpoint(vcpu, &r))
  5457. return r;
  5458. ctxt->interruptibility = 0;
  5459. ctxt->have_exception = false;
  5460. ctxt->exception.vector = -1;
  5461. ctxt->perm_ok = false;
  5462. ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
  5463. r = x86_decode_insn(ctxt, insn, insn_len);
  5464. trace_kvm_emulate_insn_start(vcpu);
  5465. ++vcpu->stat.insn_emulation;
  5466. if (r != EMULATION_OK) {
  5467. if (emulation_type & EMULTYPE_TRAP_UD)
  5468. return EMULATE_FAIL;
  5469. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  5470. emulation_type))
  5471. return EMULATE_DONE;
  5472. if (ctxt->have_exception && inject_emulated_exception(vcpu))
  5473. return EMULATE_DONE;
  5474. if (emulation_type & EMULTYPE_SKIP)
  5475. return EMULATE_FAIL;
  5476. return handle_emulation_failure(vcpu, emulation_type);
  5477. }
  5478. }
  5479. if ((emulation_type & EMULTYPE_VMWARE) &&
  5480. !is_vmware_backdoor_opcode(ctxt))
  5481. return EMULATE_FAIL;
  5482. if (emulation_type & EMULTYPE_SKIP) {
  5483. kvm_rip_write(vcpu, ctxt->_eip);
  5484. if (ctxt->eflags & X86_EFLAGS_RF)
  5485. kvm_set_rflags(vcpu, ctxt->eflags & ~X86_EFLAGS_RF);
  5486. return EMULATE_DONE;
  5487. }
  5488. if (retry_instruction(ctxt, cr2, emulation_type))
  5489. return EMULATE_DONE;
  5490. /* this is needed for vmware backdoor interface to work since it
  5491. changes registers values during IO operation */
  5492. if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
  5493. vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
  5494. emulator_invalidate_register_cache(ctxt);
  5495. }
  5496. restart:
  5497. /* Save the faulting GPA (cr2) in the address field */
  5498. ctxt->exception.address = cr2;
  5499. r = x86_emulate_insn(ctxt);
  5500. if (r == EMULATION_INTERCEPTED)
  5501. return EMULATE_DONE;
  5502. if (r == EMULATION_FAILED) {
  5503. if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
  5504. emulation_type))
  5505. return EMULATE_DONE;
  5506. return handle_emulation_failure(vcpu, emulation_type);
  5507. }
  5508. if (ctxt->have_exception) {
  5509. r = EMULATE_DONE;
  5510. if (inject_emulated_exception(vcpu))
  5511. return r;
  5512. } else if (vcpu->arch.pio.count) {
  5513. if (!vcpu->arch.pio.in) {
  5514. /* FIXME: return into emulator if single-stepping. */
  5515. vcpu->arch.pio.count = 0;
  5516. } else {
  5517. writeback = false;
  5518. vcpu->arch.complete_userspace_io = complete_emulated_pio;
  5519. }
  5520. r = EMULATE_USER_EXIT;
  5521. } else if (vcpu->mmio_needed) {
  5522. if (!vcpu->mmio_is_write)
  5523. writeback = false;
  5524. r = EMULATE_USER_EXIT;
  5525. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  5526. } else if (r == EMULATION_RESTART)
  5527. goto restart;
  5528. else
  5529. r = EMULATE_DONE;
  5530. if (writeback) {
  5531. unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
  5532. toggle_interruptibility(vcpu, ctxt->interruptibility);
  5533. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  5534. kvm_rip_write(vcpu, ctxt->eip);
  5535. if (r == EMULATE_DONE &&
  5536. (ctxt->tf || (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)))
  5537. kvm_vcpu_do_singlestep(vcpu, &r);
  5538. if (!ctxt->have_exception ||
  5539. exception_type(ctxt->exception.vector) == EXCPT_TRAP)
  5540. __kvm_set_rflags(vcpu, ctxt->eflags);
  5541. /*
  5542. * For STI, interrupts are shadowed; so KVM_REQ_EVENT will
  5543. * do nothing, and it will be requested again as soon as
  5544. * the shadow expires. But we still need to check here,
  5545. * because POPF has no interrupt shadow.
  5546. */
  5547. if (unlikely((ctxt->eflags & ~rflags) & X86_EFLAGS_IF))
  5548. kvm_make_request(KVM_REQ_EVENT, vcpu);
  5549. } else
  5550. vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
  5551. return r;
  5552. }
  5553. int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type)
  5554. {
  5555. return x86_emulate_instruction(vcpu, 0, emulation_type, NULL, 0);
  5556. }
  5557. EXPORT_SYMBOL_GPL(kvm_emulate_instruction);
  5558. int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
  5559. void *insn, int insn_len)
  5560. {
  5561. return x86_emulate_instruction(vcpu, 0, 0, insn, insn_len);
  5562. }
  5563. EXPORT_SYMBOL_GPL(kvm_emulate_instruction_from_buffer);
  5564. static int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size,
  5565. unsigned short port)
  5566. {
  5567. unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5568. int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
  5569. size, port, &val, 1);
  5570. /* do not return to emulator after return from userspace */
  5571. vcpu->arch.pio.count = 0;
  5572. return ret;
  5573. }
  5574. static int complete_fast_pio_in(struct kvm_vcpu *vcpu)
  5575. {
  5576. unsigned long val;
  5577. /* We should only ever be called with arch.pio.count equal to 1 */
  5578. BUG_ON(vcpu->arch.pio.count != 1);
  5579. /* For size less than 4 we merge, else we zero extend */
  5580. val = (vcpu->arch.pio.size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX)
  5581. : 0;
  5582. /*
  5583. * Since vcpu->arch.pio.count == 1 let emulator_pio_in_emulated perform
  5584. * the copy and tracing
  5585. */
  5586. emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, vcpu->arch.pio.size,
  5587. vcpu->arch.pio.port, &val, 1);
  5588. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  5589. return 1;
  5590. }
  5591. static int kvm_fast_pio_in(struct kvm_vcpu *vcpu, int size,
  5592. unsigned short port)
  5593. {
  5594. unsigned long val;
  5595. int ret;
  5596. /* For size less than 4 we merge, else we zero extend */
  5597. val = (size < 4) ? kvm_register_read(vcpu, VCPU_REGS_RAX) : 0;
  5598. ret = emulator_pio_in_emulated(&vcpu->arch.emulate_ctxt, size, port,
  5599. &val, 1);
  5600. if (ret) {
  5601. kvm_register_write(vcpu, VCPU_REGS_RAX, val);
  5602. return ret;
  5603. }
  5604. vcpu->arch.complete_userspace_io = complete_fast_pio_in;
  5605. return 0;
  5606. }
  5607. int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in)
  5608. {
  5609. int ret = kvm_skip_emulated_instruction(vcpu);
  5610. /*
  5611. * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
  5612. * KVM_EXIT_DEBUG here.
  5613. */
  5614. if (in)
  5615. return kvm_fast_pio_in(vcpu, size, port) && ret;
  5616. else
  5617. return kvm_fast_pio_out(vcpu, size, port) && ret;
  5618. }
  5619. EXPORT_SYMBOL_GPL(kvm_fast_pio);
  5620. static int kvmclock_cpu_down_prep(unsigned int cpu)
  5621. {
  5622. __this_cpu_write(cpu_tsc_khz, 0);
  5623. return 0;
  5624. }
  5625. static void tsc_khz_changed(void *data)
  5626. {
  5627. struct cpufreq_freqs *freq = data;
  5628. unsigned long khz = 0;
  5629. if (data)
  5630. khz = freq->new;
  5631. else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5632. khz = cpufreq_quick_get(raw_smp_processor_id());
  5633. if (!khz)
  5634. khz = tsc_khz;
  5635. __this_cpu_write(cpu_tsc_khz, khz);
  5636. }
  5637. #ifdef CONFIG_X86_64
  5638. static void kvm_hyperv_tsc_notifier(void)
  5639. {
  5640. struct kvm *kvm;
  5641. struct kvm_vcpu *vcpu;
  5642. int cpu;
  5643. spin_lock(&kvm_lock);
  5644. list_for_each_entry(kvm, &vm_list, vm_list)
  5645. kvm_make_mclock_inprogress_request(kvm);
  5646. hyperv_stop_tsc_emulation();
  5647. /* TSC frequency always matches when on Hyper-V */
  5648. for_each_present_cpu(cpu)
  5649. per_cpu(cpu_tsc_khz, cpu) = tsc_khz;
  5650. kvm_max_guest_tsc_khz = tsc_khz;
  5651. list_for_each_entry(kvm, &vm_list, vm_list) {
  5652. struct kvm_arch *ka = &kvm->arch;
  5653. spin_lock(&ka->pvclock_gtod_sync_lock);
  5654. pvclock_update_vm_gtod_copy(kvm);
  5655. kvm_for_each_vcpu(cpu, vcpu, kvm)
  5656. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5657. kvm_for_each_vcpu(cpu, vcpu, kvm)
  5658. kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu);
  5659. spin_unlock(&ka->pvclock_gtod_sync_lock);
  5660. }
  5661. spin_unlock(&kvm_lock);
  5662. }
  5663. #endif
  5664. static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  5665. void *data)
  5666. {
  5667. struct cpufreq_freqs *freq = data;
  5668. struct kvm *kvm;
  5669. struct kvm_vcpu *vcpu;
  5670. int i, send_ipi = 0;
  5671. /*
  5672. * We allow guests to temporarily run on slowing clocks,
  5673. * provided we notify them after, or to run on accelerating
  5674. * clocks, provided we notify them before. Thus time never
  5675. * goes backwards.
  5676. *
  5677. * However, we have a problem. We can't atomically update
  5678. * the frequency of a given CPU from this function; it is
  5679. * merely a notifier, which can be called from any CPU.
  5680. * Changing the TSC frequency at arbitrary points in time
  5681. * requires a recomputation of local variables related to
  5682. * the TSC for each VCPU. We must flag these local variables
  5683. * to be updated and be sure the update takes place with the
  5684. * new frequency before any guests proceed.
  5685. *
  5686. * Unfortunately, the combination of hotplug CPU and frequency
  5687. * change creates an intractable locking scenario; the order
  5688. * of when these callouts happen is undefined with respect to
  5689. * CPU hotplug, and they can race with each other. As such,
  5690. * merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
  5691. * undefined; you can actually have a CPU frequency change take
  5692. * place in between the computation of X and the setting of the
  5693. * variable. To protect against this problem, all updates of
  5694. * the per_cpu tsc_khz variable are done in an interrupt
  5695. * protected IPI, and all callers wishing to update the value
  5696. * must wait for a synchronous IPI to complete (which is trivial
  5697. * if the caller is on the CPU already). This establishes the
  5698. * necessary total order on variable updates.
  5699. *
  5700. * Note that because a guest time update may take place
  5701. * anytime after the setting of the VCPU's request bit, the
  5702. * correct TSC value must be set before the request. However,
  5703. * to ensure the update actually makes it to any guest which
  5704. * starts running in hardware virtualization between the set
  5705. * and the acquisition of the spinlock, we must also ping the
  5706. * CPU after setting the request bit.
  5707. *
  5708. */
  5709. if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
  5710. return 0;
  5711. if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
  5712. return 0;
  5713. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5714. spin_lock(&kvm_lock);
  5715. list_for_each_entry(kvm, &vm_list, vm_list) {
  5716. kvm_for_each_vcpu(i, vcpu, kvm) {
  5717. if (vcpu->cpu != freq->cpu)
  5718. continue;
  5719. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  5720. if (vcpu->cpu != smp_processor_id())
  5721. send_ipi = 1;
  5722. }
  5723. }
  5724. spin_unlock(&kvm_lock);
  5725. if (freq->old < freq->new && send_ipi) {
  5726. /*
  5727. * We upscale the frequency. Must make the guest
  5728. * doesn't see old kvmclock values while running with
  5729. * the new frequency, otherwise we risk the guest sees
  5730. * time go backwards.
  5731. *
  5732. * In case we update the frequency for another cpu
  5733. * (which might be in guest context) send an interrupt
  5734. * to kick the cpu out of guest context. Next time
  5735. * guest context is entered kvmclock will be updated,
  5736. * so the guest will not see stale values.
  5737. */
  5738. smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
  5739. }
  5740. return 0;
  5741. }
  5742. static struct notifier_block kvmclock_cpufreq_notifier_block = {
  5743. .notifier_call = kvmclock_cpufreq_notifier
  5744. };
  5745. static int kvmclock_cpu_online(unsigned int cpu)
  5746. {
  5747. tsc_khz_changed(NULL);
  5748. return 0;
  5749. }
  5750. static void kvm_timer_init(void)
  5751. {
  5752. max_tsc_khz = tsc_khz;
  5753. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
  5754. #ifdef CONFIG_CPU_FREQ
  5755. struct cpufreq_policy policy;
  5756. int cpu;
  5757. memset(&policy, 0, sizeof(policy));
  5758. cpu = get_cpu();
  5759. cpufreq_get_policy(&policy, cpu);
  5760. if (policy.cpuinfo.max_freq)
  5761. max_tsc_khz = policy.cpuinfo.max_freq;
  5762. put_cpu();
  5763. #endif
  5764. cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
  5765. CPUFREQ_TRANSITION_NOTIFIER);
  5766. }
  5767. pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
  5768. cpuhp_setup_state(CPUHP_AP_X86_KVM_CLK_ONLINE, "x86/kvm/clk:online",
  5769. kvmclock_cpu_online, kvmclock_cpu_down_prep);
  5770. }
  5771. DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
  5772. EXPORT_PER_CPU_SYMBOL_GPL(current_vcpu);
  5773. int kvm_is_in_guest(void)
  5774. {
  5775. return __this_cpu_read(current_vcpu) != NULL;
  5776. }
  5777. static int kvm_is_user_mode(void)
  5778. {
  5779. int user_mode = 3;
  5780. if (__this_cpu_read(current_vcpu))
  5781. user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
  5782. return user_mode != 0;
  5783. }
  5784. static unsigned long kvm_get_guest_ip(void)
  5785. {
  5786. unsigned long ip = 0;
  5787. if (__this_cpu_read(current_vcpu))
  5788. ip = kvm_rip_read(__this_cpu_read(current_vcpu));
  5789. return ip;
  5790. }
  5791. static struct perf_guest_info_callbacks kvm_guest_cbs = {
  5792. .is_in_guest = kvm_is_in_guest,
  5793. .is_user_mode = kvm_is_user_mode,
  5794. .get_guest_ip = kvm_get_guest_ip,
  5795. };
  5796. static void kvm_set_mmio_spte_mask(void)
  5797. {
  5798. u64 mask;
  5799. int maxphyaddr = boot_cpu_data.x86_phys_bits;
  5800. /*
  5801. * Set the reserved bits and the present bit of an paging-structure
  5802. * entry to generate page fault with PFER.RSV = 1.
  5803. */
  5804. /*
  5805. * Mask the uppermost physical address bit, which would be reserved as
  5806. * long as the supported physical address width is less than 52.
  5807. */
  5808. mask = 1ull << 51;
  5809. /* Set the present bit. */
  5810. mask |= 1ull;
  5811. /*
  5812. * If reserved bit is not supported, clear the present bit to disable
  5813. * mmio page fault.
  5814. */
  5815. if (IS_ENABLED(CONFIG_X86_64) && maxphyaddr == 52)
  5816. mask &= ~1ull;
  5817. kvm_mmu_set_mmio_spte_mask(mask, mask);
  5818. }
  5819. #ifdef CONFIG_X86_64
  5820. static void pvclock_gtod_update_fn(struct work_struct *work)
  5821. {
  5822. struct kvm *kvm;
  5823. struct kvm_vcpu *vcpu;
  5824. int i;
  5825. spin_lock(&kvm_lock);
  5826. list_for_each_entry(kvm, &vm_list, vm_list)
  5827. kvm_for_each_vcpu(i, vcpu, kvm)
  5828. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  5829. atomic_set(&kvm_guest_has_master_clock, 0);
  5830. spin_unlock(&kvm_lock);
  5831. }
  5832. static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
  5833. /*
  5834. * Notification about pvclock gtod data update.
  5835. */
  5836. static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
  5837. void *priv)
  5838. {
  5839. struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
  5840. struct timekeeper *tk = priv;
  5841. update_pvclock_gtod(tk);
  5842. /* disable master clock if host does not trust, or does not
  5843. * use, TSC based clocksource.
  5844. */
  5845. if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) &&
  5846. atomic_read(&kvm_guest_has_master_clock) != 0)
  5847. queue_work(system_long_wq, &pvclock_gtod_work);
  5848. return 0;
  5849. }
  5850. static struct notifier_block pvclock_gtod_notifier = {
  5851. .notifier_call = pvclock_gtod_notify,
  5852. };
  5853. #endif
  5854. int kvm_arch_init(void *opaque)
  5855. {
  5856. int r;
  5857. struct kvm_x86_ops *ops = opaque;
  5858. if (kvm_x86_ops) {
  5859. printk(KERN_ERR "kvm: already loaded the other module\n");
  5860. r = -EEXIST;
  5861. goto out;
  5862. }
  5863. if (!ops->cpu_has_kvm_support()) {
  5864. printk(KERN_ERR "kvm: no hardware support\n");
  5865. r = -EOPNOTSUPP;
  5866. goto out;
  5867. }
  5868. if (ops->disabled_by_bios()) {
  5869. printk(KERN_ERR "kvm: disabled by bios\n");
  5870. r = -EOPNOTSUPP;
  5871. goto out;
  5872. }
  5873. r = -ENOMEM;
  5874. shared_msrs = alloc_percpu(struct kvm_shared_msrs);
  5875. if (!shared_msrs) {
  5876. printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
  5877. goto out;
  5878. }
  5879. r = kvm_mmu_module_init();
  5880. if (r)
  5881. goto out_free_percpu;
  5882. kvm_set_mmio_spte_mask();
  5883. kvm_x86_ops = ops;
  5884. kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
  5885. PT_DIRTY_MASK, PT64_NX_MASK, 0,
  5886. PT_PRESENT_MASK, 0, sme_me_mask);
  5887. kvm_timer_init();
  5888. perf_register_guest_info_callbacks(&kvm_guest_cbs);
  5889. if (boot_cpu_has(X86_FEATURE_XSAVE))
  5890. host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
  5891. kvm_lapic_init();
  5892. #ifdef CONFIG_X86_64
  5893. pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
  5894. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  5895. set_hv_tscchange_cb(kvm_hyperv_tsc_notifier);
  5896. #endif
  5897. return 0;
  5898. out_free_percpu:
  5899. free_percpu(shared_msrs);
  5900. out:
  5901. return r;
  5902. }
  5903. void kvm_arch_exit(void)
  5904. {
  5905. #ifdef CONFIG_X86_64
  5906. if (hypervisor_is_type(X86_HYPER_MS_HYPERV))
  5907. clear_hv_tscchange_cb();
  5908. #endif
  5909. kvm_lapic_exit();
  5910. perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
  5911. if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  5912. cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
  5913. CPUFREQ_TRANSITION_NOTIFIER);
  5914. cpuhp_remove_state_nocalls(CPUHP_AP_X86_KVM_CLK_ONLINE);
  5915. #ifdef CONFIG_X86_64
  5916. pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
  5917. #endif
  5918. kvm_x86_ops = NULL;
  5919. kvm_mmu_module_exit();
  5920. free_percpu(shared_msrs);
  5921. }
  5922. int kvm_vcpu_halt(struct kvm_vcpu *vcpu)
  5923. {
  5924. ++vcpu->stat.halt_exits;
  5925. if (lapic_in_kernel(vcpu)) {
  5926. vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
  5927. return 1;
  5928. } else {
  5929. vcpu->run->exit_reason = KVM_EXIT_HLT;
  5930. return 0;
  5931. }
  5932. }
  5933. EXPORT_SYMBOL_GPL(kvm_vcpu_halt);
  5934. int kvm_emulate_halt(struct kvm_vcpu *vcpu)
  5935. {
  5936. int ret = kvm_skip_emulated_instruction(vcpu);
  5937. /*
  5938. * TODO: we might be squashing a GUESTDBG_SINGLESTEP-triggered
  5939. * KVM_EXIT_DEBUG here.
  5940. */
  5941. return kvm_vcpu_halt(vcpu) && ret;
  5942. }
  5943. EXPORT_SYMBOL_GPL(kvm_emulate_halt);
  5944. #ifdef CONFIG_X86_64
  5945. static int kvm_pv_clock_pairing(struct kvm_vcpu *vcpu, gpa_t paddr,
  5946. unsigned long clock_type)
  5947. {
  5948. struct kvm_clock_pairing clock_pairing;
  5949. struct timespec64 ts;
  5950. u64 cycle;
  5951. int ret;
  5952. if (clock_type != KVM_CLOCK_PAIRING_WALLCLOCK)
  5953. return -KVM_EOPNOTSUPP;
  5954. if (kvm_get_walltime_and_clockread(&ts, &cycle) == false)
  5955. return -KVM_EOPNOTSUPP;
  5956. clock_pairing.sec = ts.tv_sec;
  5957. clock_pairing.nsec = ts.tv_nsec;
  5958. clock_pairing.tsc = kvm_read_l1_tsc(vcpu, cycle);
  5959. clock_pairing.flags = 0;
  5960. memset(&clock_pairing.pad, 0, sizeof(clock_pairing.pad));
  5961. ret = 0;
  5962. if (kvm_write_guest(vcpu->kvm, paddr, &clock_pairing,
  5963. sizeof(struct kvm_clock_pairing)))
  5964. ret = -KVM_EFAULT;
  5965. return ret;
  5966. }
  5967. #endif
  5968. /*
  5969. * kvm_pv_kick_cpu_op: Kick a vcpu.
  5970. *
  5971. * @apicid - apicid of vcpu to be kicked.
  5972. */
  5973. static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
  5974. {
  5975. struct kvm_lapic_irq lapic_irq;
  5976. lapic_irq.shorthand = 0;
  5977. lapic_irq.dest_mode = 0;
  5978. lapic_irq.level = 0;
  5979. lapic_irq.dest_id = apicid;
  5980. lapic_irq.msi_redir_hint = false;
  5981. lapic_irq.delivery_mode = APIC_DM_REMRD;
  5982. kvm_irq_delivery_to_apic(kvm, NULL, &lapic_irq, NULL);
  5983. }
  5984. void kvm_vcpu_deactivate_apicv(struct kvm_vcpu *vcpu)
  5985. {
  5986. vcpu->arch.apicv_active = false;
  5987. kvm_x86_ops->refresh_apicv_exec_ctrl(vcpu);
  5988. }
  5989. int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
  5990. {
  5991. unsigned long nr, a0, a1, a2, a3, ret;
  5992. int op_64_bit;
  5993. if (kvm_hv_hypercall_enabled(vcpu->kvm))
  5994. return kvm_hv_hypercall(vcpu);
  5995. nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
  5996. a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
  5997. a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
  5998. a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
  5999. a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
  6000. trace_kvm_hypercall(nr, a0, a1, a2, a3);
  6001. op_64_bit = is_64_bit_mode(vcpu);
  6002. if (!op_64_bit) {
  6003. nr &= 0xFFFFFFFF;
  6004. a0 &= 0xFFFFFFFF;
  6005. a1 &= 0xFFFFFFFF;
  6006. a2 &= 0xFFFFFFFF;
  6007. a3 &= 0xFFFFFFFF;
  6008. }
  6009. if (kvm_x86_ops->get_cpl(vcpu) != 0) {
  6010. ret = -KVM_EPERM;
  6011. goto out;
  6012. }
  6013. switch (nr) {
  6014. case KVM_HC_VAPIC_POLL_IRQ:
  6015. ret = 0;
  6016. break;
  6017. case KVM_HC_KICK_CPU:
  6018. kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
  6019. ret = 0;
  6020. break;
  6021. #ifdef CONFIG_X86_64
  6022. case KVM_HC_CLOCK_PAIRING:
  6023. ret = kvm_pv_clock_pairing(vcpu, a0, a1);
  6024. break;
  6025. case KVM_HC_SEND_IPI:
  6026. ret = kvm_pv_send_ipi(vcpu->kvm, a0, a1, a2, a3, op_64_bit);
  6027. break;
  6028. #endif
  6029. default:
  6030. ret = -KVM_ENOSYS;
  6031. break;
  6032. }
  6033. out:
  6034. if (!op_64_bit)
  6035. ret = (u32)ret;
  6036. kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
  6037. ++vcpu->stat.hypercalls;
  6038. return kvm_skip_emulated_instruction(vcpu);
  6039. }
  6040. EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
  6041. static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
  6042. {
  6043. struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
  6044. char instruction[3];
  6045. unsigned long rip = kvm_rip_read(vcpu);
  6046. kvm_x86_ops->patch_hypercall(vcpu, instruction);
  6047. return emulator_write_emulated(ctxt, rip, instruction, 3,
  6048. &ctxt->exception);
  6049. }
  6050. static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
  6051. {
  6052. return vcpu->run->request_interrupt_window &&
  6053. likely(!pic_in_kernel(vcpu->kvm));
  6054. }
  6055. static void post_kvm_run_save(struct kvm_vcpu *vcpu)
  6056. {
  6057. struct kvm_run *kvm_run = vcpu->run;
  6058. kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
  6059. kvm_run->flags = is_smm(vcpu) ? KVM_RUN_X86_SMM : 0;
  6060. kvm_run->cr8 = kvm_get_cr8(vcpu);
  6061. kvm_run->apic_base = kvm_get_apic_base(vcpu);
  6062. kvm_run->ready_for_interrupt_injection =
  6063. pic_in_kernel(vcpu->kvm) ||
  6064. kvm_vcpu_ready_for_interrupt_injection(vcpu);
  6065. }
  6066. static void update_cr8_intercept(struct kvm_vcpu *vcpu)
  6067. {
  6068. int max_irr, tpr;
  6069. if (!kvm_x86_ops->update_cr8_intercept)
  6070. return;
  6071. if (!lapic_in_kernel(vcpu))
  6072. return;
  6073. if (vcpu->arch.apicv_active)
  6074. return;
  6075. if (!vcpu->arch.apic->vapic_addr)
  6076. max_irr = kvm_lapic_find_highest_irr(vcpu);
  6077. else
  6078. max_irr = -1;
  6079. if (max_irr != -1)
  6080. max_irr >>= 4;
  6081. tpr = kvm_lapic_get_cr8(vcpu);
  6082. kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
  6083. }
  6084. static int inject_pending_event(struct kvm_vcpu *vcpu, bool req_int_win)
  6085. {
  6086. int r;
  6087. /* try to reinject previous events if any */
  6088. if (vcpu->arch.exception.injected)
  6089. kvm_x86_ops->queue_exception(vcpu);
  6090. /*
  6091. * Do not inject an NMI or interrupt if there is a pending
  6092. * exception. Exceptions and interrupts are recognized at
  6093. * instruction boundaries, i.e. the start of an instruction.
  6094. * Trap-like exceptions, e.g. #DB, have higher priority than
  6095. * NMIs and interrupts, i.e. traps are recognized before an
  6096. * NMI/interrupt that's pending on the same instruction.
  6097. * Fault-like exceptions, e.g. #GP and #PF, are the lowest
  6098. * priority, but are only generated (pended) during instruction
  6099. * execution, i.e. a pending fault-like exception means the
  6100. * fault occurred on the *previous* instruction and must be
  6101. * serviced prior to recognizing any new events in order to
  6102. * fully complete the previous instruction.
  6103. */
  6104. else if (!vcpu->arch.exception.pending) {
  6105. if (vcpu->arch.nmi_injected)
  6106. kvm_x86_ops->set_nmi(vcpu);
  6107. else if (vcpu->arch.interrupt.injected)
  6108. kvm_x86_ops->set_irq(vcpu);
  6109. }
  6110. /*
  6111. * Call check_nested_events() even if we reinjected a previous event
  6112. * in order for caller to determine if it should require immediate-exit
  6113. * from L2 to L1 due to pending L1 events which require exit
  6114. * from L2 to L1.
  6115. */
  6116. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  6117. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  6118. if (r != 0)
  6119. return r;
  6120. }
  6121. /* try to inject new event if pending */
  6122. if (vcpu->arch.exception.pending) {
  6123. trace_kvm_inj_exception(vcpu->arch.exception.nr,
  6124. vcpu->arch.exception.has_error_code,
  6125. vcpu->arch.exception.error_code);
  6126. WARN_ON_ONCE(vcpu->arch.exception.injected);
  6127. vcpu->arch.exception.pending = false;
  6128. vcpu->arch.exception.injected = true;
  6129. if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
  6130. __kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
  6131. X86_EFLAGS_RF);
  6132. if (vcpu->arch.exception.nr == DB_VECTOR) {
  6133. /*
  6134. * This code assumes that nSVM doesn't use
  6135. * check_nested_events(). If it does, the
  6136. * DR6/DR7 changes should happen before L1
  6137. * gets a #VMEXIT for an intercepted #DB in
  6138. * L2. (Under VMX, on the other hand, the
  6139. * DR6/DR7 changes should not happen in the
  6140. * event of a VM-exit to L1 for an intercepted
  6141. * #DB in L2.)
  6142. */
  6143. kvm_deliver_exception_payload(vcpu);
  6144. if (vcpu->arch.dr7 & DR7_GD) {
  6145. vcpu->arch.dr7 &= ~DR7_GD;
  6146. kvm_update_dr7(vcpu);
  6147. }
  6148. }
  6149. kvm_x86_ops->queue_exception(vcpu);
  6150. }
  6151. /* Don't consider new event if we re-injected an event */
  6152. if (kvm_event_needs_reinjection(vcpu))
  6153. return 0;
  6154. if (vcpu->arch.smi_pending && !is_smm(vcpu) &&
  6155. kvm_x86_ops->smi_allowed(vcpu)) {
  6156. vcpu->arch.smi_pending = false;
  6157. ++vcpu->arch.smi_count;
  6158. enter_smm(vcpu);
  6159. } else if (vcpu->arch.nmi_pending && kvm_x86_ops->nmi_allowed(vcpu)) {
  6160. --vcpu->arch.nmi_pending;
  6161. vcpu->arch.nmi_injected = true;
  6162. kvm_x86_ops->set_nmi(vcpu);
  6163. } else if (kvm_cpu_has_injectable_intr(vcpu)) {
  6164. /*
  6165. * Because interrupts can be injected asynchronously, we are
  6166. * calling check_nested_events again here to avoid a race condition.
  6167. * See https://lkml.org/lkml/2014/7/2/60 for discussion about this
  6168. * proposal and current concerns. Perhaps we should be setting
  6169. * KVM_REQ_EVENT only on certain events and not unconditionally?
  6170. */
  6171. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events) {
  6172. r = kvm_x86_ops->check_nested_events(vcpu, req_int_win);
  6173. if (r != 0)
  6174. return r;
  6175. }
  6176. if (kvm_x86_ops->interrupt_allowed(vcpu)) {
  6177. kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
  6178. false);
  6179. kvm_x86_ops->set_irq(vcpu);
  6180. }
  6181. }
  6182. return 0;
  6183. }
  6184. static void process_nmi(struct kvm_vcpu *vcpu)
  6185. {
  6186. unsigned limit = 2;
  6187. /*
  6188. * x86 is limited to one NMI running, and one NMI pending after it.
  6189. * If an NMI is already in progress, limit further NMIs to just one.
  6190. * Otherwise, allow two (and we'll inject the first one immediately).
  6191. */
  6192. if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
  6193. limit = 1;
  6194. vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
  6195. vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
  6196. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6197. }
  6198. static u32 enter_smm_get_segment_flags(struct kvm_segment *seg)
  6199. {
  6200. u32 flags = 0;
  6201. flags |= seg->g << 23;
  6202. flags |= seg->db << 22;
  6203. flags |= seg->l << 21;
  6204. flags |= seg->avl << 20;
  6205. flags |= seg->present << 15;
  6206. flags |= seg->dpl << 13;
  6207. flags |= seg->s << 12;
  6208. flags |= seg->type << 8;
  6209. return flags;
  6210. }
  6211. static void enter_smm_save_seg_32(struct kvm_vcpu *vcpu, char *buf, int n)
  6212. {
  6213. struct kvm_segment seg;
  6214. int offset;
  6215. kvm_get_segment(vcpu, &seg, n);
  6216. put_smstate(u32, buf, 0x7fa8 + n * 4, seg.selector);
  6217. if (n < 3)
  6218. offset = 0x7f84 + n * 12;
  6219. else
  6220. offset = 0x7f2c + (n - 3) * 12;
  6221. put_smstate(u32, buf, offset + 8, seg.base);
  6222. put_smstate(u32, buf, offset + 4, seg.limit);
  6223. put_smstate(u32, buf, offset, enter_smm_get_segment_flags(&seg));
  6224. }
  6225. #ifdef CONFIG_X86_64
  6226. static void enter_smm_save_seg_64(struct kvm_vcpu *vcpu, char *buf, int n)
  6227. {
  6228. struct kvm_segment seg;
  6229. int offset;
  6230. u16 flags;
  6231. kvm_get_segment(vcpu, &seg, n);
  6232. offset = 0x7e00 + n * 16;
  6233. flags = enter_smm_get_segment_flags(&seg) >> 8;
  6234. put_smstate(u16, buf, offset, seg.selector);
  6235. put_smstate(u16, buf, offset + 2, flags);
  6236. put_smstate(u32, buf, offset + 4, seg.limit);
  6237. put_smstate(u64, buf, offset + 8, seg.base);
  6238. }
  6239. #endif
  6240. static void enter_smm_save_state_32(struct kvm_vcpu *vcpu, char *buf)
  6241. {
  6242. struct desc_ptr dt;
  6243. struct kvm_segment seg;
  6244. unsigned long val;
  6245. int i;
  6246. put_smstate(u32, buf, 0x7ffc, kvm_read_cr0(vcpu));
  6247. put_smstate(u32, buf, 0x7ff8, kvm_read_cr3(vcpu));
  6248. put_smstate(u32, buf, 0x7ff4, kvm_get_rflags(vcpu));
  6249. put_smstate(u32, buf, 0x7ff0, kvm_rip_read(vcpu));
  6250. for (i = 0; i < 8; i++)
  6251. put_smstate(u32, buf, 0x7fd0 + i * 4, kvm_register_read(vcpu, i));
  6252. kvm_get_dr(vcpu, 6, &val);
  6253. put_smstate(u32, buf, 0x7fcc, (u32)val);
  6254. kvm_get_dr(vcpu, 7, &val);
  6255. put_smstate(u32, buf, 0x7fc8, (u32)val);
  6256. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  6257. put_smstate(u32, buf, 0x7fc4, seg.selector);
  6258. put_smstate(u32, buf, 0x7f64, seg.base);
  6259. put_smstate(u32, buf, 0x7f60, seg.limit);
  6260. put_smstate(u32, buf, 0x7f5c, enter_smm_get_segment_flags(&seg));
  6261. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  6262. put_smstate(u32, buf, 0x7fc0, seg.selector);
  6263. put_smstate(u32, buf, 0x7f80, seg.base);
  6264. put_smstate(u32, buf, 0x7f7c, seg.limit);
  6265. put_smstate(u32, buf, 0x7f78, enter_smm_get_segment_flags(&seg));
  6266. kvm_x86_ops->get_gdt(vcpu, &dt);
  6267. put_smstate(u32, buf, 0x7f74, dt.address);
  6268. put_smstate(u32, buf, 0x7f70, dt.size);
  6269. kvm_x86_ops->get_idt(vcpu, &dt);
  6270. put_smstate(u32, buf, 0x7f58, dt.address);
  6271. put_smstate(u32, buf, 0x7f54, dt.size);
  6272. for (i = 0; i < 6; i++)
  6273. enter_smm_save_seg_32(vcpu, buf, i);
  6274. put_smstate(u32, buf, 0x7f14, kvm_read_cr4(vcpu));
  6275. /* revision id */
  6276. put_smstate(u32, buf, 0x7efc, 0x00020000);
  6277. put_smstate(u32, buf, 0x7ef8, vcpu->arch.smbase);
  6278. }
  6279. static void enter_smm_save_state_64(struct kvm_vcpu *vcpu, char *buf)
  6280. {
  6281. #ifdef CONFIG_X86_64
  6282. struct desc_ptr dt;
  6283. struct kvm_segment seg;
  6284. unsigned long val;
  6285. int i;
  6286. for (i = 0; i < 16; i++)
  6287. put_smstate(u64, buf, 0x7ff8 - i * 8, kvm_register_read(vcpu, i));
  6288. put_smstate(u64, buf, 0x7f78, kvm_rip_read(vcpu));
  6289. put_smstate(u32, buf, 0x7f70, kvm_get_rflags(vcpu));
  6290. kvm_get_dr(vcpu, 6, &val);
  6291. put_smstate(u64, buf, 0x7f68, val);
  6292. kvm_get_dr(vcpu, 7, &val);
  6293. put_smstate(u64, buf, 0x7f60, val);
  6294. put_smstate(u64, buf, 0x7f58, kvm_read_cr0(vcpu));
  6295. put_smstate(u64, buf, 0x7f50, kvm_read_cr3(vcpu));
  6296. put_smstate(u64, buf, 0x7f48, kvm_read_cr4(vcpu));
  6297. put_smstate(u32, buf, 0x7f00, vcpu->arch.smbase);
  6298. /* revision id */
  6299. put_smstate(u32, buf, 0x7efc, 0x00020064);
  6300. put_smstate(u64, buf, 0x7ed0, vcpu->arch.efer);
  6301. kvm_get_segment(vcpu, &seg, VCPU_SREG_TR);
  6302. put_smstate(u16, buf, 0x7e90, seg.selector);
  6303. put_smstate(u16, buf, 0x7e92, enter_smm_get_segment_flags(&seg) >> 8);
  6304. put_smstate(u32, buf, 0x7e94, seg.limit);
  6305. put_smstate(u64, buf, 0x7e98, seg.base);
  6306. kvm_x86_ops->get_idt(vcpu, &dt);
  6307. put_smstate(u32, buf, 0x7e84, dt.size);
  6308. put_smstate(u64, buf, 0x7e88, dt.address);
  6309. kvm_get_segment(vcpu, &seg, VCPU_SREG_LDTR);
  6310. put_smstate(u16, buf, 0x7e70, seg.selector);
  6311. put_smstate(u16, buf, 0x7e72, enter_smm_get_segment_flags(&seg) >> 8);
  6312. put_smstate(u32, buf, 0x7e74, seg.limit);
  6313. put_smstate(u64, buf, 0x7e78, seg.base);
  6314. kvm_x86_ops->get_gdt(vcpu, &dt);
  6315. put_smstate(u32, buf, 0x7e64, dt.size);
  6316. put_smstate(u64, buf, 0x7e68, dt.address);
  6317. for (i = 0; i < 6; i++)
  6318. enter_smm_save_seg_64(vcpu, buf, i);
  6319. #else
  6320. WARN_ON_ONCE(1);
  6321. #endif
  6322. }
  6323. static void enter_smm(struct kvm_vcpu *vcpu)
  6324. {
  6325. struct kvm_segment cs, ds;
  6326. struct desc_ptr dt;
  6327. char buf[512];
  6328. u32 cr0;
  6329. trace_kvm_enter_smm(vcpu->vcpu_id, vcpu->arch.smbase, true);
  6330. memset(buf, 0, 512);
  6331. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  6332. enter_smm_save_state_64(vcpu, buf);
  6333. else
  6334. enter_smm_save_state_32(vcpu, buf);
  6335. /*
  6336. * Give pre_enter_smm() a chance to make ISA-specific changes to the
  6337. * vCPU state (e.g. leave guest mode) after we've saved the state into
  6338. * the SMM state-save area.
  6339. */
  6340. kvm_x86_ops->pre_enter_smm(vcpu, buf);
  6341. vcpu->arch.hflags |= HF_SMM_MASK;
  6342. kvm_vcpu_write_guest(vcpu, vcpu->arch.smbase + 0xfe00, buf, sizeof(buf));
  6343. if (kvm_x86_ops->get_nmi_mask(vcpu))
  6344. vcpu->arch.hflags |= HF_SMM_INSIDE_NMI_MASK;
  6345. else
  6346. kvm_x86_ops->set_nmi_mask(vcpu, true);
  6347. kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
  6348. kvm_rip_write(vcpu, 0x8000);
  6349. cr0 = vcpu->arch.cr0 & ~(X86_CR0_PE | X86_CR0_EM | X86_CR0_TS | X86_CR0_PG);
  6350. kvm_x86_ops->set_cr0(vcpu, cr0);
  6351. vcpu->arch.cr0 = cr0;
  6352. kvm_x86_ops->set_cr4(vcpu, 0);
  6353. /* Undocumented: IDT limit is set to zero on entry to SMM. */
  6354. dt.address = dt.size = 0;
  6355. kvm_x86_ops->set_idt(vcpu, &dt);
  6356. __kvm_set_dr(vcpu, 7, DR7_FIXED_1);
  6357. cs.selector = (vcpu->arch.smbase >> 4) & 0xffff;
  6358. cs.base = vcpu->arch.smbase;
  6359. ds.selector = 0;
  6360. ds.base = 0;
  6361. cs.limit = ds.limit = 0xffffffff;
  6362. cs.type = ds.type = 0x3;
  6363. cs.dpl = ds.dpl = 0;
  6364. cs.db = ds.db = 0;
  6365. cs.s = ds.s = 1;
  6366. cs.l = ds.l = 0;
  6367. cs.g = ds.g = 1;
  6368. cs.avl = ds.avl = 0;
  6369. cs.present = ds.present = 1;
  6370. cs.unusable = ds.unusable = 0;
  6371. cs.padding = ds.padding = 0;
  6372. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  6373. kvm_set_segment(vcpu, &ds, VCPU_SREG_DS);
  6374. kvm_set_segment(vcpu, &ds, VCPU_SREG_ES);
  6375. kvm_set_segment(vcpu, &ds, VCPU_SREG_FS);
  6376. kvm_set_segment(vcpu, &ds, VCPU_SREG_GS);
  6377. kvm_set_segment(vcpu, &ds, VCPU_SREG_SS);
  6378. if (guest_cpuid_has(vcpu, X86_FEATURE_LM))
  6379. kvm_x86_ops->set_efer(vcpu, 0);
  6380. kvm_update_cpuid(vcpu);
  6381. kvm_mmu_reset_context(vcpu);
  6382. }
  6383. static void process_smi(struct kvm_vcpu *vcpu)
  6384. {
  6385. vcpu->arch.smi_pending = true;
  6386. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6387. }
  6388. void kvm_make_scan_ioapic_request(struct kvm *kvm)
  6389. {
  6390. kvm_make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
  6391. }
  6392. static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
  6393. {
  6394. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  6395. return;
  6396. bitmap_zero(vcpu->arch.ioapic_handled_vectors, 256);
  6397. if (irqchip_split(vcpu->kvm))
  6398. kvm_scan_ioapic_routes(vcpu, vcpu->arch.ioapic_handled_vectors);
  6399. else {
  6400. if (vcpu->arch.apicv_active)
  6401. kvm_x86_ops->sync_pir_to_irr(vcpu);
  6402. if (ioapic_in_kernel(vcpu->kvm))
  6403. kvm_ioapic_scan_entry(vcpu, vcpu->arch.ioapic_handled_vectors);
  6404. }
  6405. if (is_guest_mode(vcpu))
  6406. vcpu->arch.load_eoi_exitmap_pending = true;
  6407. else
  6408. kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
  6409. }
  6410. static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
  6411. {
  6412. u64 eoi_exit_bitmap[4];
  6413. if (!kvm_apic_hw_enabled(vcpu->arch.apic))
  6414. return;
  6415. bitmap_or((ulong *)eoi_exit_bitmap, vcpu->arch.ioapic_handled_vectors,
  6416. vcpu_to_synic(vcpu)->vec_bitmap, 256);
  6417. kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
  6418. }
  6419. int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
  6420. unsigned long start, unsigned long end,
  6421. bool blockable)
  6422. {
  6423. unsigned long apic_address;
  6424. /*
  6425. * The physical address of apic access page is stored in the VMCS.
  6426. * Update it when it becomes invalid.
  6427. */
  6428. apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  6429. if (start <= apic_address && apic_address < end)
  6430. kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
  6431. return 0;
  6432. }
  6433. void kvm_vcpu_reload_apic_access_page(struct kvm_vcpu *vcpu)
  6434. {
  6435. struct page *page = NULL;
  6436. if (!lapic_in_kernel(vcpu))
  6437. return;
  6438. if (!kvm_x86_ops->set_apic_access_page_addr)
  6439. return;
  6440. page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
  6441. if (is_error_page(page))
  6442. return;
  6443. kvm_x86_ops->set_apic_access_page_addr(vcpu, page_to_phys(page));
  6444. /*
  6445. * Do not pin apic access page in memory, the MMU notifier
  6446. * will call us again if it is migrated or swapped out.
  6447. */
  6448. put_page(page);
  6449. }
  6450. EXPORT_SYMBOL_GPL(kvm_vcpu_reload_apic_access_page);
  6451. void __kvm_request_immediate_exit(struct kvm_vcpu *vcpu)
  6452. {
  6453. smp_send_reschedule(vcpu->cpu);
  6454. }
  6455. EXPORT_SYMBOL_GPL(__kvm_request_immediate_exit);
  6456. /*
  6457. * Returns 1 to let vcpu_run() continue the guest execution loop without
  6458. * exiting to the userspace. Otherwise, the value will be returned to the
  6459. * userspace.
  6460. */
  6461. static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
  6462. {
  6463. int r;
  6464. bool req_int_win =
  6465. dm_request_for_irq_injection(vcpu) &&
  6466. kvm_cpu_accept_dm_intr(vcpu);
  6467. bool req_immediate_exit = false;
  6468. if (kvm_request_pending(vcpu)) {
  6469. if (kvm_check_request(KVM_REQ_GET_VMCS12_PAGES, vcpu))
  6470. kvm_x86_ops->get_vmcs12_pages(vcpu);
  6471. if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
  6472. kvm_mmu_unload(vcpu);
  6473. if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
  6474. __kvm_migrate_timers(vcpu);
  6475. if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
  6476. kvm_gen_update_masterclock(vcpu->kvm);
  6477. if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
  6478. kvm_gen_kvmclock_update(vcpu);
  6479. if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
  6480. r = kvm_guest_time_update(vcpu);
  6481. if (unlikely(r))
  6482. goto out;
  6483. }
  6484. if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
  6485. kvm_mmu_sync_roots(vcpu);
  6486. if (kvm_check_request(KVM_REQ_LOAD_CR3, vcpu))
  6487. kvm_mmu_load_cr3(vcpu);
  6488. if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
  6489. kvm_vcpu_flush_tlb(vcpu, true);
  6490. if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
  6491. vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
  6492. r = 0;
  6493. goto out;
  6494. }
  6495. if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
  6496. vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
  6497. vcpu->mmio_needed = 0;
  6498. r = 0;
  6499. goto out;
  6500. }
  6501. if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
  6502. /* Page is swapped out. Do synthetic halt */
  6503. vcpu->arch.apf.halted = true;
  6504. r = 1;
  6505. goto out;
  6506. }
  6507. if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
  6508. record_steal_time(vcpu);
  6509. if (kvm_check_request(KVM_REQ_SMI, vcpu))
  6510. process_smi(vcpu);
  6511. if (kvm_check_request(KVM_REQ_NMI, vcpu))
  6512. process_nmi(vcpu);
  6513. if (kvm_check_request(KVM_REQ_PMU, vcpu))
  6514. kvm_pmu_handle_event(vcpu);
  6515. if (kvm_check_request(KVM_REQ_PMI, vcpu))
  6516. kvm_pmu_deliver_pmi(vcpu);
  6517. if (kvm_check_request(KVM_REQ_IOAPIC_EOI_EXIT, vcpu)) {
  6518. BUG_ON(vcpu->arch.pending_ioapic_eoi > 255);
  6519. if (test_bit(vcpu->arch.pending_ioapic_eoi,
  6520. vcpu->arch.ioapic_handled_vectors)) {
  6521. vcpu->run->exit_reason = KVM_EXIT_IOAPIC_EOI;
  6522. vcpu->run->eoi.vector =
  6523. vcpu->arch.pending_ioapic_eoi;
  6524. r = 0;
  6525. goto out;
  6526. }
  6527. }
  6528. if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
  6529. vcpu_scan_ioapic(vcpu);
  6530. if (kvm_check_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu))
  6531. vcpu_load_eoi_exitmap(vcpu);
  6532. if (kvm_check_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu))
  6533. kvm_vcpu_reload_apic_access_page(vcpu);
  6534. if (kvm_check_request(KVM_REQ_HV_CRASH, vcpu)) {
  6535. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  6536. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_CRASH;
  6537. r = 0;
  6538. goto out;
  6539. }
  6540. if (kvm_check_request(KVM_REQ_HV_RESET, vcpu)) {
  6541. vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
  6542. vcpu->run->system_event.type = KVM_SYSTEM_EVENT_RESET;
  6543. r = 0;
  6544. goto out;
  6545. }
  6546. if (kvm_check_request(KVM_REQ_HV_EXIT, vcpu)) {
  6547. vcpu->run->exit_reason = KVM_EXIT_HYPERV;
  6548. vcpu->run->hyperv = vcpu->arch.hyperv.exit;
  6549. r = 0;
  6550. goto out;
  6551. }
  6552. /*
  6553. * KVM_REQ_HV_STIMER has to be processed after
  6554. * KVM_REQ_CLOCK_UPDATE, because Hyper-V SynIC timers
  6555. * depend on the guest clock being up-to-date
  6556. */
  6557. if (kvm_check_request(KVM_REQ_HV_STIMER, vcpu))
  6558. kvm_hv_process_stimers(vcpu);
  6559. }
  6560. if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
  6561. ++vcpu->stat.req_event;
  6562. kvm_apic_accept_events(vcpu);
  6563. if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
  6564. r = 1;
  6565. goto out;
  6566. }
  6567. if (inject_pending_event(vcpu, req_int_win) != 0)
  6568. req_immediate_exit = true;
  6569. else {
  6570. /* Enable SMI/NMI/IRQ window open exits if needed.
  6571. *
  6572. * SMIs have three cases:
  6573. * 1) They can be nested, and then there is nothing to
  6574. * do here because RSM will cause a vmexit anyway.
  6575. * 2) There is an ISA-specific reason why SMI cannot be
  6576. * injected, and the moment when this changes can be
  6577. * intercepted.
  6578. * 3) Or the SMI can be pending because
  6579. * inject_pending_event has completed the injection
  6580. * of an IRQ or NMI from the previous vmexit, and
  6581. * then we request an immediate exit to inject the
  6582. * SMI.
  6583. */
  6584. if (vcpu->arch.smi_pending && !is_smm(vcpu))
  6585. if (!kvm_x86_ops->enable_smi_window(vcpu))
  6586. req_immediate_exit = true;
  6587. if (vcpu->arch.nmi_pending)
  6588. kvm_x86_ops->enable_nmi_window(vcpu);
  6589. if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
  6590. kvm_x86_ops->enable_irq_window(vcpu);
  6591. WARN_ON(vcpu->arch.exception.pending);
  6592. }
  6593. if (kvm_lapic_enabled(vcpu)) {
  6594. update_cr8_intercept(vcpu);
  6595. kvm_lapic_sync_to_vapic(vcpu);
  6596. }
  6597. }
  6598. r = kvm_mmu_reload(vcpu);
  6599. if (unlikely(r)) {
  6600. goto cancel_injection;
  6601. }
  6602. preempt_disable();
  6603. kvm_x86_ops->prepare_guest_switch(vcpu);
  6604. /*
  6605. * Disable IRQs before setting IN_GUEST_MODE. Posted interrupt
  6606. * IPI are then delayed after guest entry, which ensures that they
  6607. * result in virtual interrupt delivery.
  6608. */
  6609. local_irq_disable();
  6610. vcpu->mode = IN_GUEST_MODE;
  6611. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  6612. /*
  6613. * 1) We should set ->mode before checking ->requests. Please see
  6614. * the comment in kvm_vcpu_exiting_guest_mode().
  6615. *
  6616. * 2) For APICv, we should set ->mode before checking PIR.ON. This
  6617. * pairs with the memory barrier implicit in pi_test_and_set_on
  6618. * (see vmx_deliver_posted_interrupt).
  6619. *
  6620. * 3) This also orders the write to mode from any reads to the page
  6621. * tables done while the VCPU is running. Please see the comment
  6622. * in kvm_flush_remote_tlbs.
  6623. */
  6624. smp_mb__after_srcu_read_unlock();
  6625. /*
  6626. * This handles the case where a posted interrupt was
  6627. * notified with kvm_vcpu_kick.
  6628. */
  6629. if (kvm_lapic_enabled(vcpu) && vcpu->arch.apicv_active)
  6630. kvm_x86_ops->sync_pir_to_irr(vcpu);
  6631. if (vcpu->mode == EXITING_GUEST_MODE || kvm_request_pending(vcpu)
  6632. || need_resched() || signal_pending(current)) {
  6633. vcpu->mode = OUTSIDE_GUEST_MODE;
  6634. smp_wmb();
  6635. local_irq_enable();
  6636. preempt_enable();
  6637. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6638. r = 1;
  6639. goto cancel_injection;
  6640. }
  6641. kvm_load_guest_xcr0(vcpu);
  6642. if (req_immediate_exit) {
  6643. kvm_make_request(KVM_REQ_EVENT, vcpu);
  6644. kvm_x86_ops->request_immediate_exit(vcpu);
  6645. }
  6646. trace_kvm_entry(vcpu->vcpu_id);
  6647. if (lapic_timer_advance_ns)
  6648. wait_lapic_expire(vcpu);
  6649. guest_enter_irqoff();
  6650. if (unlikely(vcpu->arch.switch_db_regs)) {
  6651. set_debugreg(0, 7);
  6652. set_debugreg(vcpu->arch.eff_db[0], 0);
  6653. set_debugreg(vcpu->arch.eff_db[1], 1);
  6654. set_debugreg(vcpu->arch.eff_db[2], 2);
  6655. set_debugreg(vcpu->arch.eff_db[3], 3);
  6656. set_debugreg(vcpu->arch.dr6, 6);
  6657. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  6658. }
  6659. kvm_x86_ops->run(vcpu);
  6660. /*
  6661. * Do this here before restoring debug registers on the host. And
  6662. * since we do this before handling the vmexit, a DR access vmexit
  6663. * can (a) read the correct value of the debug registers, (b) set
  6664. * KVM_DEBUGREG_WONT_EXIT again.
  6665. */
  6666. if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)) {
  6667. WARN_ON(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP);
  6668. kvm_x86_ops->sync_dirty_debug_regs(vcpu);
  6669. kvm_update_dr0123(vcpu);
  6670. kvm_update_dr6(vcpu);
  6671. kvm_update_dr7(vcpu);
  6672. vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_RELOAD;
  6673. }
  6674. /*
  6675. * If the guest has used debug registers, at least dr7
  6676. * will be disabled while returning to the host.
  6677. * If we don't have active breakpoints in the host, we don't
  6678. * care about the messed up debug address registers. But if
  6679. * we have some of them active, restore the old state.
  6680. */
  6681. if (hw_breakpoint_active())
  6682. hw_breakpoint_restore();
  6683. vcpu->arch.last_guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
  6684. vcpu->mode = OUTSIDE_GUEST_MODE;
  6685. smp_wmb();
  6686. kvm_put_guest_xcr0(vcpu);
  6687. kvm_before_interrupt(vcpu);
  6688. kvm_x86_ops->handle_external_intr(vcpu);
  6689. kvm_after_interrupt(vcpu);
  6690. ++vcpu->stat.exits;
  6691. guest_exit_irqoff();
  6692. local_irq_enable();
  6693. preempt_enable();
  6694. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6695. /*
  6696. * Profile KVM exit RIPs:
  6697. */
  6698. if (unlikely(prof_on == KVM_PROFILING)) {
  6699. unsigned long rip = kvm_rip_read(vcpu);
  6700. profile_hit(KVM_PROFILING, (void *)rip);
  6701. }
  6702. if (unlikely(vcpu->arch.tsc_always_catchup))
  6703. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  6704. if (vcpu->arch.apic_attention)
  6705. kvm_lapic_sync_from_vapic(vcpu);
  6706. vcpu->arch.gpa_available = false;
  6707. r = kvm_x86_ops->handle_exit(vcpu);
  6708. return r;
  6709. cancel_injection:
  6710. kvm_x86_ops->cancel_injection(vcpu);
  6711. if (unlikely(vcpu->arch.apic_attention))
  6712. kvm_lapic_sync_from_vapic(vcpu);
  6713. out:
  6714. return r;
  6715. }
  6716. static inline int vcpu_block(struct kvm *kvm, struct kvm_vcpu *vcpu)
  6717. {
  6718. if (!kvm_arch_vcpu_runnable(vcpu) &&
  6719. (!kvm_x86_ops->pre_block || kvm_x86_ops->pre_block(vcpu) == 0)) {
  6720. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6721. kvm_vcpu_block(vcpu);
  6722. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6723. if (kvm_x86_ops->post_block)
  6724. kvm_x86_ops->post_block(vcpu);
  6725. if (!kvm_check_request(KVM_REQ_UNHALT, vcpu))
  6726. return 1;
  6727. }
  6728. kvm_apic_accept_events(vcpu);
  6729. switch(vcpu->arch.mp_state) {
  6730. case KVM_MP_STATE_HALTED:
  6731. vcpu->arch.pv.pv_unhalted = false;
  6732. vcpu->arch.mp_state =
  6733. KVM_MP_STATE_RUNNABLE;
  6734. case KVM_MP_STATE_RUNNABLE:
  6735. vcpu->arch.apf.halted = false;
  6736. break;
  6737. case KVM_MP_STATE_INIT_RECEIVED:
  6738. break;
  6739. default:
  6740. return -EINTR;
  6741. break;
  6742. }
  6743. return 1;
  6744. }
  6745. static inline bool kvm_vcpu_running(struct kvm_vcpu *vcpu)
  6746. {
  6747. if (is_guest_mode(vcpu) && kvm_x86_ops->check_nested_events)
  6748. kvm_x86_ops->check_nested_events(vcpu, false);
  6749. return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
  6750. !vcpu->arch.apf.halted);
  6751. }
  6752. static int vcpu_run(struct kvm_vcpu *vcpu)
  6753. {
  6754. int r;
  6755. struct kvm *kvm = vcpu->kvm;
  6756. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6757. vcpu->arch.l1tf_flush_l1d = true;
  6758. for (;;) {
  6759. if (kvm_vcpu_running(vcpu)) {
  6760. r = vcpu_enter_guest(vcpu);
  6761. } else {
  6762. r = vcpu_block(kvm, vcpu);
  6763. }
  6764. if (r <= 0)
  6765. break;
  6766. kvm_clear_request(KVM_REQ_PENDING_TIMER, vcpu);
  6767. if (kvm_cpu_has_pending_timer(vcpu))
  6768. kvm_inject_pending_timer_irqs(vcpu);
  6769. if (dm_request_for_irq_injection(vcpu) &&
  6770. kvm_vcpu_ready_for_interrupt_injection(vcpu)) {
  6771. r = 0;
  6772. vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN;
  6773. ++vcpu->stat.request_irq_exits;
  6774. break;
  6775. }
  6776. kvm_check_async_pf_completion(vcpu);
  6777. if (signal_pending(current)) {
  6778. r = -EINTR;
  6779. vcpu->run->exit_reason = KVM_EXIT_INTR;
  6780. ++vcpu->stat.signal_exits;
  6781. break;
  6782. }
  6783. if (need_resched()) {
  6784. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6785. cond_resched();
  6786. vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
  6787. }
  6788. }
  6789. srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
  6790. return r;
  6791. }
  6792. static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
  6793. {
  6794. int r;
  6795. vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
  6796. r = kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
  6797. srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
  6798. if (r != EMULATE_DONE)
  6799. return 0;
  6800. return 1;
  6801. }
  6802. static int complete_emulated_pio(struct kvm_vcpu *vcpu)
  6803. {
  6804. BUG_ON(!vcpu->arch.pio.count);
  6805. return complete_emulated_io(vcpu);
  6806. }
  6807. /*
  6808. * Implements the following, as a state machine:
  6809. *
  6810. * read:
  6811. * for each fragment
  6812. * for each mmio piece in the fragment
  6813. * write gpa, len
  6814. * exit
  6815. * copy data
  6816. * execute insn
  6817. *
  6818. * write:
  6819. * for each fragment
  6820. * for each mmio piece in the fragment
  6821. * write gpa, len
  6822. * copy data
  6823. * exit
  6824. */
  6825. static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
  6826. {
  6827. struct kvm_run *run = vcpu->run;
  6828. struct kvm_mmio_fragment *frag;
  6829. unsigned len;
  6830. BUG_ON(!vcpu->mmio_needed);
  6831. /* Complete previous fragment */
  6832. frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
  6833. len = min(8u, frag->len);
  6834. if (!vcpu->mmio_is_write)
  6835. memcpy(frag->data, run->mmio.data, len);
  6836. if (frag->len <= 8) {
  6837. /* Switch to the next fragment. */
  6838. frag++;
  6839. vcpu->mmio_cur_fragment++;
  6840. } else {
  6841. /* Go forward to the next mmio piece. */
  6842. frag->data += len;
  6843. frag->gpa += len;
  6844. frag->len -= len;
  6845. }
  6846. if (vcpu->mmio_cur_fragment >= vcpu->mmio_nr_fragments) {
  6847. vcpu->mmio_needed = 0;
  6848. /* FIXME: return into emulator if single-stepping. */
  6849. if (vcpu->mmio_is_write)
  6850. return 1;
  6851. vcpu->mmio_read_completed = 1;
  6852. return complete_emulated_io(vcpu);
  6853. }
  6854. run->exit_reason = KVM_EXIT_MMIO;
  6855. run->mmio.phys_addr = frag->gpa;
  6856. if (vcpu->mmio_is_write)
  6857. memcpy(run->mmio.data, frag->data, min(8u, frag->len));
  6858. run->mmio.len = min(8u, frag->len);
  6859. run->mmio.is_write = vcpu->mmio_is_write;
  6860. vcpu->arch.complete_userspace_io = complete_emulated_mmio;
  6861. return 0;
  6862. }
  6863. /* Swap (qemu) user FPU context for the guest FPU context. */
  6864. static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  6865. {
  6866. preempt_disable();
  6867. copy_fpregs_to_fpstate(&vcpu->arch.user_fpu);
  6868. /* PKRU is separately restored in kvm_x86_ops->run. */
  6869. __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu.state,
  6870. ~XFEATURE_MASK_PKRU);
  6871. preempt_enable();
  6872. trace_kvm_fpu(1);
  6873. }
  6874. /* When vcpu_run ends, restore user space FPU context. */
  6875. static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
  6876. {
  6877. preempt_disable();
  6878. copy_fpregs_to_fpstate(&vcpu->arch.guest_fpu);
  6879. copy_kernel_to_fpregs(&vcpu->arch.user_fpu.state);
  6880. preempt_enable();
  6881. ++vcpu->stat.fpu_reload;
  6882. trace_kvm_fpu(0);
  6883. }
  6884. int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
  6885. {
  6886. int r;
  6887. vcpu_load(vcpu);
  6888. kvm_sigset_activate(vcpu);
  6889. kvm_load_guest_fpu(vcpu);
  6890. if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
  6891. if (kvm_run->immediate_exit) {
  6892. r = -EINTR;
  6893. goto out;
  6894. }
  6895. kvm_vcpu_block(vcpu);
  6896. kvm_apic_accept_events(vcpu);
  6897. kvm_clear_request(KVM_REQ_UNHALT, vcpu);
  6898. r = -EAGAIN;
  6899. if (signal_pending(current)) {
  6900. r = -EINTR;
  6901. vcpu->run->exit_reason = KVM_EXIT_INTR;
  6902. ++vcpu->stat.signal_exits;
  6903. }
  6904. goto out;
  6905. }
  6906. if (vcpu->run->kvm_valid_regs & ~KVM_SYNC_X86_VALID_FIELDS) {
  6907. r = -EINVAL;
  6908. goto out;
  6909. }
  6910. if (vcpu->run->kvm_dirty_regs) {
  6911. r = sync_regs(vcpu);
  6912. if (r != 0)
  6913. goto out;
  6914. }
  6915. /* re-sync apic's tpr */
  6916. if (!lapic_in_kernel(vcpu)) {
  6917. if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
  6918. r = -EINVAL;
  6919. goto out;
  6920. }
  6921. }
  6922. if (unlikely(vcpu->arch.complete_userspace_io)) {
  6923. int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
  6924. vcpu->arch.complete_userspace_io = NULL;
  6925. r = cui(vcpu);
  6926. if (r <= 0)
  6927. goto out;
  6928. } else
  6929. WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
  6930. if (kvm_run->immediate_exit)
  6931. r = -EINTR;
  6932. else
  6933. r = vcpu_run(vcpu);
  6934. out:
  6935. kvm_put_guest_fpu(vcpu);
  6936. if (vcpu->run->kvm_valid_regs)
  6937. store_regs(vcpu);
  6938. post_kvm_run_save(vcpu);
  6939. kvm_sigset_deactivate(vcpu);
  6940. vcpu_put(vcpu);
  6941. return r;
  6942. }
  6943. static void __get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6944. {
  6945. if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
  6946. /*
  6947. * We are here if userspace calls get_regs() in the middle of
  6948. * instruction emulation. Registers state needs to be copied
  6949. * back from emulation context to vcpu. Userspace shouldn't do
  6950. * that usually, but some bad designed PV devices (vmware
  6951. * backdoor interface) need this to work
  6952. */
  6953. emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
  6954. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6955. }
  6956. regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
  6957. regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
  6958. regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
  6959. regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
  6960. regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
  6961. regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
  6962. regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
  6963. regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
  6964. #ifdef CONFIG_X86_64
  6965. regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
  6966. regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
  6967. regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
  6968. regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
  6969. regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
  6970. regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
  6971. regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
  6972. regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
  6973. #endif
  6974. regs->rip = kvm_rip_read(vcpu);
  6975. regs->rflags = kvm_get_rflags(vcpu);
  6976. }
  6977. int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6978. {
  6979. vcpu_load(vcpu);
  6980. __get_regs(vcpu, regs);
  6981. vcpu_put(vcpu);
  6982. return 0;
  6983. }
  6984. static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  6985. {
  6986. vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
  6987. vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
  6988. kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
  6989. kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
  6990. kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
  6991. kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
  6992. kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
  6993. kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
  6994. kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
  6995. kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
  6996. #ifdef CONFIG_X86_64
  6997. kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
  6998. kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
  6999. kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
  7000. kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
  7001. kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
  7002. kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
  7003. kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
  7004. kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
  7005. #endif
  7006. kvm_rip_write(vcpu, regs->rip);
  7007. kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);
  7008. vcpu->arch.exception.pending = false;
  7009. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7010. }
  7011. int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
  7012. {
  7013. vcpu_load(vcpu);
  7014. __set_regs(vcpu, regs);
  7015. vcpu_put(vcpu);
  7016. return 0;
  7017. }
  7018. void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
  7019. {
  7020. struct kvm_segment cs;
  7021. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  7022. *db = cs.db;
  7023. *l = cs.l;
  7024. }
  7025. EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
  7026. static void __get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  7027. {
  7028. struct desc_ptr dt;
  7029. kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  7030. kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  7031. kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  7032. kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  7033. kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  7034. kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  7035. kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  7036. kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  7037. kvm_x86_ops->get_idt(vcpu, &dt);
  7038. sregs->idt.limit = dt.size;
  7039. sregs->idt.base = dt.address;
  7040. kvm_x86_ops->get_gdt(vcpu, &dt);
  7041. sregs->gdt.limit = dt.size;
  7042. sregs->gdt.base = dt.address;
  7043. sregs->cr0 = kvm_read_cr0(vcpu);
  7044. sregs->cr2 = vcpu->arch.cr2;
  7045. sregs->cr3 = kvm_read_cr3(vcpu);
  7046. sregs->cr4 = kvm_read_cr4(vcpu);
  7047. sregs->cr8 = kvm_get_cr8(vcpu);
  7048. sregs->efer = vcpu->arch.efer;
  7049. sregs->apic_base = kvm_get_apic_base(vcpu);
  7050. memset(sregs->interrupt_bitmap, 0, sizeof(sregs->interrupt_bitmap));
  7051. if (vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft)
  7052. set_bit(vcpu->arch.interrupt.nr,
  7053. (unsigned long *)sregs->interrupt_bitmap);
  7054. }
  7055. int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
  7056. struct kvm_sregs *sregs)
  7057. {
  7058. vcpu_load(vcpu);
  7059. __get_sregs(vcpu, sregs);
  7060. vcpu_put(vcpu);
  7061. return 0;
  7062. }
  7063. int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
  7064. struct kvm_mp_state *mp_state)
  7065. {
  7066. vcpu_load(vcpu);
  7067. kvm_apic_accept_events(vcpu);
  7068. if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
  7069. vcpu->arch.pv.pv_unhalted)
  7070. mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
  7071. else
  7072. mp_state->mp_state = vcpu->arch.mp_state;
  7073. vcpu_put(vcpu);
  7074. return 0;
  7075. }
  7076. int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
  7077. struct kvm_mp_state *mp_state)
  7078. {
  7079. int ret = -EINVAL;
  7080. vcpu_load(vcpu);
  7081. if (!lapic_in_kernel(vcpu) &&
  7082. mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
  7083. goto out;
  7084. /* INITs are latched while in SMM */
  7085. if ((is_smm(vcpu) || vcpu->arch.smi_pending) &&
  7086. (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED ||
  7087. mp_state->mp_state == KVM_MP_STATE_INIT_RECEIVED))
  7088. goto out;
  7089. if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
  7090. vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
  7091. set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
  7092. } else
  7093. vcpu->arch.mp_state = mp_state->mp_state;
  7094. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7095. ret = 0;
  7096. out:
  7097. vcpu_put(vcpu);
  7098. return ret;
  7099. }
  7100. int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
  7101. int reason, bool has_error_code, u32 error_code)
  7102. {
  7103. struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
  7104. int ret;
  7105. init_emulate_ctxt(vcpu);
  7106. ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
  7107. has_error_code, error_code);
  7108. if (ret)
  7109. return EMULATE_FAIL;
  7110. kvm_rip_write(vcpu, ctxt->eip);
  7111. kvm_set_rflags(vcpu, ctxt->eflags);
  7112. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7113. return EMULATE_DONE;
  7114. }
  7115. EXPORT_SYMBOL_GPL(kvm_task_switch);
  7116. static int kvm_valid_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  7117. {
  7118. if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
  7119. (sregs->cr4 & X86_CR4_OSXSAVE))
  7120. return -EINVAL;
  7121. if ((sregs->efer & EFER_LME) && (sregs->cr0 & X86_CR0_PG)) {
  7122. /*
  7123. * When EFER.LME and CR0.PG are set, the processor is in
  7124. * 64-bit mode (though maybe in a 32-bit code segment).
  7125. * CR4.PAE and EFER.LMA must be set.
  7126. */
  7127. if (!(sregs->cr4 & X86_CR4_PAE)
  7128. || !(sregs->efer & EFER_LMA))
  7129. return -EINVAL;
  7130. } else {
  7131. /*
  7132. * Not in 64-bit mode: EFER.LMA is clear and the code
  7133. * segment cannot be 64-bit.
  7134. */
  7135. if (sregs->efer & EFER_LMA || sregs->cs.l)
  7136. return -EINVAL;
  7137. }
  7138. return 0;
  7139. }
  7140. static int __set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
  7141. {
  7142. struct msr_data apic_base_msr;
  7143. int mmu_reset_needed = 0;
  7144. int cpuid_update_needed = 0;
  7145. int pending_vec, max_bits, idx;
  7146. struct desc_ptr dt;
  7147. int ret = -EINVAL;
  7148. if (kvm_valid_sregs(vcpu, sregs))
  7149. goto out;
  7150. apic_base_msr.data = sregs->apic_base;
  7151. apic_base_msr.host_initiated = true;
  7152. if (kvm_set_apic_base(vcpu, &apic_base_msr))
  7153. goto out;
  7154. dt.size = sregs->idt.limit;
  7155. dt.address = sregs->idt.base;
  7156. kvm_x86_ops->set_idt(vcpu, &dt);
  7157. dt.size = sregs->gdt.limit;
  7158. dt.address = sregs->gdt.base;
  7159. kvm_x86_ops->set_gdt(vcpu, &dt);
  7160. vcpu->arch.cr2 = sregs->cr2;
  7161. mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
  7162. vcpu->arch.cr3 = sregs->cr3;
  7163. __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
  7164. kvm_set_cr8(vcpu, sregs->cr8);
  7165. mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
  7166. kvm_x86_ops->set_efer(vcpu, sregs->efer);
  7167. mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
  7168. kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
  7169. vcpu->arch.cr0 = sregs->cr0;
  7170. mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
  7171. cpuid_update_needed |= ((kvm_read_cr4(vcpu) ^ sregs->cr4) &
  7172. (X86_CR4_OSXSAVE | X86_CR4_PKE));
  7173. kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
  7174. if (cpuid_update_needed)
  7175. kvm_update_cpuid(vcpu);
  7176. idx = srcu_read_lock(&vcpu->kvm->srcu);
  7177. if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu)) {
  7178. load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
  7179. mmu_reset_needed = 1;
  7180. }
  7181. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  7182. if (mmu_reset_needed)
  7183. kvm_mmu_reset_context(vcpu);
  7184. max_bits = KVM_NR_INTERRUPTS;
  7185. pending_vec = find_first_bit(
  7186. (const unsigned long *)sregs->interrupt_bitmap, max_bits);
  7187. if (pending_vec < max_bits) {
  7188. kvm_queue_interrupt(vcpu, pending_vec, false);
  7189. pr_debug("Set back pending irq %d\n", pending_vec);
  7190. }
  7191. kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
  7192. kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
  7193. kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
  7194. kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
  7195. kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
  7196. kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
  7197. kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
  7198. kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
  7199. update_cr8_intercept(vcpu);
  7200. /* Older userspace won't unhalt the vcpu on reset. */
  7201. if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
  7202. sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
  7203. !is_protmode(vcpu))
  7204. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  7205. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7206. ret = 0;
  7207. out:
  7208. return ret;
  7209. }
  7210. int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
  7211. struct kvm_sregs *sregs)
  7212. {
  7213. int ret;
  7214. vcpu_load(vcpu);
  7215. ret = __set_sregs(vcpu, sregs);
  7216. vcpu_put(vcpu);
  7217. return ret;
  7218. }
  7219. int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
  7220. struct kvm_guest_debug *dbg)
  7221. {
  7222. unsigned long rflags;
  7223. int i, r;
  7224. vcpu_load(vcpu);
  7225. if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
  7226. r = -EBUSY;
  7227. if (vcpu->arch.exception.pending)
  7228. goto out;
  7229. if (dbg->control & KVM_GUESTDBG_INJECT_DB)
  7230. kvm_queue_exception(vcpu, DB_VECTOR);
  7231. else
  7232. kvm_queue_exception(vcpu, BP_VECTOR);
  7233. }
  7234. /*
  7235. * Read rflags as long as potentially injected trace flags are still
  7236. * filtered out.
  7237. */
  7238. rflags = kvm_get_rflags(vcpu);
  7239. vcpu->guest_debug = dbg->control;
  7240. if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
  7241. vcpu->guest_debug = 0;
  7242. if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
  7243. for (i = 0; i < KVM_NR_DB_REGS; ++i)
  7244. vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
  7245. vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
  7246. } else {
  7247. for (i = 0; i < KVM_NR_DB_REGS; i++)
  7248. vcpu->arch.eff_db[i] = vcpu->arch.db[i];
  7249. }
  7250. kvm_update_dr7(vcpu);
  7251. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  7252. vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
  7253. get_segment_base(vcpu, VCPU_SREG_CS);
  7254. /*
  7255. * Trigger an rflags update that will inject or remove the trace
  7256. * flags.
  7257. */
  7258. kvm_set_rflags(vcpu, rflags);
  7259. kvm_x86_ops->update_bp_intercept(vcpu);
  7260. r = 0;
  7261. out:
  7262. vcpu_put(vcpu);
  7263. return r;
  7264. }
  7265. /*
  7266. * Translate a guest virtual address to a guest physical address.
  7267. */
  7268. int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
  7269. struct kvm_translation *tr)
  7270. {
  7271. unsigned long vaddr = tr->linear_address;
  7272. gpa_t gpa;
  7273. int idx;
  7274. vcpu_load(vcpu);
  7275. idx = srcu_read_lock(&vcpu->kvm->srcu);
  7276. gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
  7277. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  7278. tr->physical_address = gpa;
  7279. tr->valid = gpa != UNMAPPED_GVA;
  7280. tr->writeable = 1;
  7281. tr->usermode = 0;
  7282. vcpu_put(vcpu);
  7283. return 0;
  7284. }
  7285. int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  7286. {
  7287. struct fxregs_state *fxsave;
  7288. vcpu_load(vcpu);
  7289. fxsave = &vcpu->arch.guest_fpu.state.fxsave;
  7290. memcpy(fpu->fpr, fxsave->st_space, 128);
  7291. fpu->fcw = fxsave->cwd;
  7292. fpu->fsw = fxsave->swd;
  7293. fpu->ftwx = fxsave->twd;
  7294. fpu->last_opcode = fxsave->fop;
  7295. fpu->last_ip = fxsave->rip;
  7296. fpu->last_dp = fxsave->rdp;
  7297. memcpy(fpu->xmm, fxsave->xmm_space, sizeof(fxsave->xmm_space));
  7298. vcpu_put(vcpu);
  7299. return 0;
  7300. }
  7301. int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
  7302. {
  7303. struct fxregs_state *fxsave;
  7304. vcpu_load(vcpu);
  7305. fxsave = &vcpu->arch.guest_fpu.state.fxsave;
  7306. memcpy(fxsave->st_space, fpu->fpr, 128);
  7307. fxsave->cwd = fpu->fcw;
  7308. fxsave->swd = fpu->fsw;
  7309. fxsave->twd = fpu->ftwx;
  7310. fxsave->fop = fpu->last_opcode;
  7311. fxsave->rip = fpu->last_ip;
  7312. fxsave->rdp = fpu->last_dp;
  7313. memcpy(fxsave->xmm_space, fpu->xmm, sizeof(fxsave->xmm_space));
  7314. vcpu_put(vcpu);
  7315. return 0;
  7316. }
  7317. static void store_regs(struct kvm_vcpu *vcpu)
  7318. {
  7319. BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);
  7320. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_REGS)
  7321. __get_regs(vcpu, &vcpu->run->s.regs.regs);
  7322. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_SREGS)
  7323. __get_sregs(vcpu, &vcpu->run->s.regs.sregs);
  7324. if (vcpu->run->kvm_valid_regs & KVM_SYNC_X86_EVENTS)
  7325. kvm_vcpu_ioctl_x86_get_vcpu_events(
  7326. vcpu, &vcpu->run->s.regs.events);
  7327. }
  7328. static int sync_regs(struct kvm_vcpu *vcpu)
  7329. {
  7330. if (vcpu->run->kvm_dirty_regs & ~KVM_SYNC_X86_VALID_FIELDS)
  7331. return -EINVAL;
  7332. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_REGS) {
  7333. __set_regs(vcpu, &vcpu->run->s.regs.regs);
  7334. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_REGS;
  7335. }
  7336. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_SREGS) {
  7337. if (__set_sregs(vcpu, &vcpu->run->s.regs.sregs))
  7338. return -EINVAL;
  7339. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS;
  7340. }
  7341. if (vcpu->run->kvm_dirty_regs & KVM_SYNC_X86_EVENTS) {
  7342. if (kvm_vcpu_ioctl_x86_set_vcpu_events(
  7343. vcpu, &vcpu->run->s.regs.events))
  7344. return -EINVAL;
  7345. vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_EVENTS;
  7346. }
  7347. return 0;
  7348. }
  7349. static void fx_init(struct kvm_vcpu *vcpu)
  7350. {
  7351. fpstate_init(&vcpu->arch.guest_fpu.state);
  7352. if (boot_cpu_has(X86_FEATURE_XSAVES))
  7353. vcpu->arch.guest_fpu.state.xsave.header.xcomp_bv =
  7354. host_xcr0 | XSTATE_COMPACTION_ENABLED;
  7355. /*
  7356. * Ensure guest xcr0 is valid for loading
  7357. */
  7358. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  7359. vcpu->arch.cr0 |= X86_CR0_ET;
  7360. }
  7361. void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
  7362. {
  7363. void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
  7364. kvmclock_reset(vcpu);
  7365. kvm_x86_ops->vcpu_free(vcpu);
  7366. free_cpumask_var(wbinvd_dirty_mask);
  7367. }
  7368. struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
  7369. unsigned int id)
  7370. {
  7371. struct kvm_vcpu *vcpu;
  7372. if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
  7373. printk_once(KERN_WARNING
  7374. "kvm: SMP vm created on host with unstable TSC; "
  7375. "guest TSC will not be reliable\n");
  7376. vcpu = kvm_x86_ops->vcpu_create(kvm, id);
  7377. return vcpu;
  7378. }
  7379. int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
  7380. {
  7381. kvm_vcpu_mtrr_init(vcpu);
  7382. vcpu_load(vcpu);
  7383. kvm_vcpu_reset(vcpu, false);
  7384. kvm_init_mmu(vcpu, false);
  7385. vcpu_put(vcpu);
  7386. return 0;
  7387. }
  7388. void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  7389. {
  7390. struct msr_data msr;
  7391. struct kvm *kvm = vcpu->kvm;
  7392. kvm_hv_vcpu_postcreate(vcpu);
  7393. if (mutex_lock_killable(&vcpu->mutex))
  7394. return;
  7395. vcpu_load(vcpu);
  7396. msr.data = 0x0;
  7397. msr.index = MSR_IA32_TSC;
  7398. msr.host_initiated = true;
  7399. kvm_write_tsc(vcpu, &msr);
  7400. vcpu_put(vcpu);
  7401. mutex_unlock(&vcpu->mutex);
  7402. if (!kvmclock_periodic_sync)
  7403. return;
  7404. schedule_delayed_work(&kvm->arch.kvmclock_sync_work,
  7405. KVMCLOCK_SYNC_PERIOD);
  7406. }
  7407. void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  7408. {
  7409. vcpu->arch.apf.msr_val = 0;
  7410. vcpu_load(vcpu);
  7411. kvm_mmu_unload(vcpu);
  7412. vcpu_put(vcpu);
  7413. kvm_x86_ops->vcpu_free(vcpu);
  7414. }
  7415. void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
  7416. {
  7417. kvm_lapic_reset(vcpu, init_event);
  7418. vcpu->arch.hflags = 0;
  7419. vcpu->arch.smi_pending = 0;
  7420. vcpu->arch.smi_count = 0;
  7421. atomic_set(&vcpu->arch.nmi_queued, 0);
  7422. vcpu->arch.nmi_pending = 0;
  7423. vcpu->arch.nmi_injected = false;
  7424. kvm_clear_interrupt_queue(vcpu);
  7425. kvm_clear_exception_queue(vcpu);
  7426. vcpu->arch.exception.pending = false;
  7427. memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
  7428. kvm_update_dr0123(vcpu);
  7429. vcpu->arch.dr6 = DR6_INIT;
  7430. kvm_update_dr6(vcpu);
  7431. vcpu->arch.dr7 = DR7_FIXED_1;
  7432. kvm_update_dr7(vcpu);
  7433. vcpu->arch.cr2 = 0;
  7434. kvm_make_request(KVM_REQ_EVENT, vcpu);
  7435. vcpu->arch.apf.msr_val = 0;
  7436. vcpu->arch.st.msr_val = 0;
  7437. kvmclock_reset(vcpu);
  7438. kvm_clear_async_pf_completion_queue(vcpu);
  7439. kvm_async_pf_hash_reset(vcpu);
  7440. vcpu->arch.apf.halted = false;
  7441. if (kvm_mpx_supported()) {
  7442. void *mpx_state_buffer;
  7443. /*
  7444. * To avoid have the INIT path from kvm_apic_has_events() that be
  7445. * called with loaded FPU and does not let userspace fix the state.
  7446. */
  7447. if (init_event)
  7448. kvm_put_guest_fpu(vcpu);
  7449. mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
  7450. XFEATURE_MASK_BNDREGS);
  7451. if (mpx_state_buffer)
  7452. memset(mpx_state_buffer, 0, sizeof(struct mpx_bndreg_state));
  7453. mpx_state_buffer = get_xsave_addr(&vcpu->arch.guest_fpu.state.xsave,
  7454. XFEATURE_MASK_BNDCSR);
  7455. if (mpx_state_buffer)
  7456. memset(mpx_state_buffer, 0, sizeof(struct mpx_bndcsr));
  7457. if (init_event)
  7458. kvm_load_guest_fpu(vcpu);
  7459. }
  7460. if (!init_event) {
  7461. kvm_pmu_reset(vcpu);
  7462. vcpu->arch.smbase = 0x30000;
  7463. vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
  7464. vcpu->arch.msr_misc_features_enables = 0;
  7465. vcpu->arch.xcr0 = XFEATURE_MASK_FP;
  7466. }
  7467. memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
  7468. vcpu->arch.regs_avail = ~0;
  7469. vcpu->arch.regs_dirty = ~0;
  7470. vcpu->arch.ia32_xss = 0;
  7471. kvm_x86_ops->vcpu_reset(vcpu, init_event);
  7472. }
  7473. void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
  7474. {
  7475. struct kvm_segment cs;
  7476. kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
  7477. cs.selector = vector << 8;
  7478. cs.base = vector << 12;
  7479. kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
  7480. kvm_rip_write(vcpu, 0);
  7481. }
  7482. int kvm_arch_hardware_enable(void)
  7483. {
  7484. struct kvm *kvm;
  7485. struct kvm_vcpu *vcpu;
  7486. int i;
  7487. int ret;
  7488. u64 local_tsc;
  7489. u64 max_tsc = 0;
  7490. bool stable, backwards_tsc = false;
  7491. kvm_shared_msr_cpu_online();
  7492. ret = kvm_x86_ops->hardware_enable();
  7493. if (ret != 0)
  7494. return ret;
  7495. local_tsc = rdtsc();
  7496. stable = !kvm_check_tsc_unstable();
  7497. list_for_each_entry(kvm, &vm_list, vm_list) {
  7498. kvm_for_each_vcpu(i, vcpu, kvm) {
  7499. if (!stable && vcpu->cpu == smp_processor_id())
  7500. kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
  7501. if (stable && vcpu->arch.last_host_tsc > local_tsc) {
  7502. backwards_tsc = true;
  7503. if (vcpu->arch.last_host_tsc > max_tsc)
  7504. max_tsc = vcpu->arch.last_host_tsc;
  7505. }
  7506. }
  7507. }
  7508. /*
  7509. * Sometimes, even reliable TSCs go backwards. This happens on
  7510. * platforms that reset TSC during suspend or hibernate actions, but
  7511. * maintain synchronization. We must compensate. Fortunately, we can
  7512. * detect that condition here, which happens early in CPU bringup,
  7513. * before any KVM threads can be running. Unfortunately, we can't
  7514. * bring the TSCs fully up to date with real time, as we aren't yet far
  7515. * enough into CPU bringup that we know how much real time has actually
  7516. * elapsed; our helper function, ktime_get_boot_ns() will be using boot
  7517. * variables that haven't been updated yet.
  7518. *
  7519. * So we simply find the maximum observed TSC above, then record the
  7520. * adjustment to TSC in each VCPU. When the VCPU later gets loaded,
  7521. * the adjustment will be applied. Note that we accumulate
  7522. * adjustments, in case multiple suspend cycles happen before some VCPU
  7523. * gets a chance to run again. In the event that no KVM threads get a
  7524. * chance to run, we will miss the entire elapsed period, as we'll have
  7525. * reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
  7526. * loose cycle time. This isn't too big a deal, since the loss will be
  7527. * uniform across all VCPUs (not to mention the scenario is extremely
  7528. * unlikely). It is possible that a second hibernate recovery happens
  7529. * much faster than a first, causing the observed TSC here to be
  7530. * smaller; this would require additional padding adjustment, which is
  7531. * why we set last_host_tsc to the local tsc observed here.
  7532. *
  7533. * N.B. - this code below runs only on platforms with reliable TSC,
  7534. * as that is the only way backwards_tsc is set above. Also note
  7535. * that this runs for ALL vcpus, which is not a bug; all VCPUs should
  7536. * have the same delta_cyc adjustment applied if backwards_tsc
  7537. * is detected. Note further, this adjustment is only done once,
  7538. * as we reset last_host_tsc on all VCPUs to stop this from being
  7539. * called multiple times (one for each physical CPU bringup).
  7540. *
  7541. * Platforms with unreliable TSCs don't have to deal with this, they
  7542. * will be compensated by the logic in vcpu_load, which sets the TSC to
  7543. * catchup mode. This will catchup all VCPUs to real time, but cannot
  7544. * guarantee that they stay in perfect synchronization.
  7545. */
  7546. if (backwards_tsc) {
  7547. u64 delta_cyc = max_tsc - local_tsc;
  7548. list_for_each_entry(kvm, &vm_list, vm_list) {
  7549. kvm->arch.backwards_tsc_observed = true;
  7550. kvm_for_each_vcpu(i, vcpu, kvm) {
  7551. vcpu->arch.tsc_offset_adjustment += delta_cyc;
  7552. vcpu->arch.last_host_tsc = local_tsc;
  7553. kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
  7554. }
  7555. /*
  7556. * We have to disable TSC offset matching.. if you were
  7557. * booting a VM while issuing an S4 host suspend....
  7558. * you may have some problem. Solving this issue is
  7559. * left as an exercise to the reader.
  7560. */
  7561. kvm->arch.last_tsc_nsec = 0;
  7562. kvm->arch.last_tsc_write = 0;
  7563. }
  7564. }
  7565. return 0;
  7566. }
  7567. void kvm_arch_hardware_disable(void)
  7568. {
  7569. kvm_x86_ops->hardware_disable();
  7570. drop_user_return_notifiers();
  7571. }
  7572. int kvm_arch_hardware_setup(void)
  7573. {
  7574. int r;
  7575. r = kvm_x86_ops->hardware_setup();
  7576. if (r != 0)
  7577. return r;
  7578. if (kvm_has_tsc_control) {
  7579. /*
  7580. * Make sure the user can only configure tsc_khz values that
  7581. * fit into a signed integer.
  7582. * A min value is not calculated because it will always
  7583. * be 1 on all machines.
  7584. */
  7585. u64 max = min(0x7fffffffULL,
  7586. __scale_tsc(kvm_max_tsc_scaling_ratio, tsc_khz));
  7587. kvm_max_guest_tsc_khz = max;
  7588. kvm_default_tsc_scaling_ratio = 1ULL << kvm_tsc_scaling_ratio_frac_bits;
  7589. }
  7590. kvm_init_msr_list();
  7591. return 0;
  7592. }
  7593. void kvm_arch_hardware_unsetup(void)
  7594. {
  7595. kvm_x86_ops->hardware_unsetup();
  7596. }
  7597. void kvm_arch_check_processor_compat(void *rtn)
  7598. {
  7599. kvm_x86_ops->check_processor_compatibility(rtn);
  7600. }
  7601. bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
  7602. {
  7603. return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
  7604. }
  7605. EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
  7606. bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
  7607. {
  7608. return (vcpu->arch.apic_base & MSR_IA32_APICBASE_BSP) != 0;
  7609. }
  7610. struct static_key kvm_no_apic_vcpu __read_mostly;
  7611. EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
  7612. int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
  7613. {
  7614. struct page *page;
  7615. int r;
  7616. vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu);
  7617. vcpu->arch.emulate_ctxt.ops = &emulate_ops;
  7618. if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
  7619. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  7620. else
  7621. vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  7622. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  7623. if (!page) {
  7624. r = -ENOMEM;
  7625. goto fail;
  7626. }
  7627. vcpu->arch.pio_data = page_address(page);
  7628. kvm_set_tsc_khz(vcpu, max_tsc_khz);
  7629. r = kvm_mmu_create(vcpu);
  7630. if (r < 0)
  7631. goto fail_free_pio_data;
  7632. if (irqchip_in_kernel(vcpu->kvm)) {
  7633. r = kvm_create_lapic(vcpu);
  7634. if (r < 0)
  7635. goto fail_mmu_destroy;
  7636. } else
  7637. static_key_slow_inc(&kvm_no_apic_vcpu);
  7638. vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
  7639. GFP_KERNEL);
  7640. if (!vcpu->arch.mce_banks) {
  7641. r = -ENOMEM;
  7642. goto fail_free_lapic;
  7643. }
  7644. vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
  7645. if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
  7646. r = -ENOMEM;
  7647. goto fail_free_mce_banks;
  7648. }
  7649. fx_init(vcpu);
  7650. vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
  7651. vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
  7652. vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
  7653. kvm_async_pf_hash_reset(vcpu);
  7654. kvm_pmu_init(vcpu);
  7655. vcpu->arch.pending_external_vector = -1;
  7656. vcpu->arch.preempted_in_kernel = false;
  7657. kvm_hv_vcpu_init(vcpu);
  7658. return 0;
  7659. fail_free_mce_banks:
  7660. kfree(vcpu->arch.mce_banks);
  7661. fail_free_lapic:
  7662. kvm_free_lapic(vcpu);
  7663. fail_mmu_destroy:
  7664. kvm_mmu_destroy(vcpu);
  7665. fail_free_pio_data:
  7666. free_page((unsigned long)vcpu->arch.pio_data);
  7667. fail:
  7668. return r;
  7669. }
  7670. void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
  7671. {
  7672. int idx;
  7673. kvm_hv_vcpu_uninit(vcpu);
  7674. kvm_pmu_destroy(vcpu);
  7675. kfree(vcpu->arch.mce_banks);
  7676. kvm_free_lapic(vcpu);
  7677. idx = srcu_read_lock(&vcpu->kvm->srcu);
  7678. kvm_mmu_destroy(vcpu);
  7679. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  7680. free_page((unsigned long)vcpu->arch.pio_data);
  7681. if (!lapic_in_kernel(vcpu))
  7682. static_key_slow_dec(&kvm_no_apic_vcpu);
  7683. }
  7684. void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  7685. {
  7686. vcpu->arch.l1tf_flush_l1d = true;
  7687. kvm_x86_ops->sched_in(vcpu, cpu);
  7688. }
  7689. int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  7690. {
  7691. if (type)
  7692. return -EINVAL;
  7693. INIT_HLIST_HEAD(&kvm->arch.mask_notifier_list);
  7694. INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
  7695. INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
  7696. INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
  7697. atomic_set(&kvm->arch.noncoherent_dma_count, 0);
  7698. /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
  7699. set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
  7700. /* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
  7701. set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
  7702. &kvm->arch.irq_sources_bitmap);
  7703. raw_spin_lock_init(&kvm->arch.tsc_write_lock);
  7704. mutex_init(&kvm->arch.apic_map_lock);
  7705. spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
  7706. kvm->arch.kvmclock_offset = -ktime_get_boot_ns();
  7707. pvclock_update_vm_gtod_copy(kvm);
  7708. kvm->arch.guest_can_read_msr_platform_info = true;
  7709. INIT_DELAYED_WORK(&kvm->arch.kvmclock_update_work, kvmclock_update_fn);
  7710. INIT_DELAYED_WORK(&kvm->arch.kvmclock_sync_work, kvmclock_sync_fn);
  7711. kvm_hv_init_vm(kvm);
  7712. kvm_page_track_init(kvm);
  7713. kvm_mmu_init_vm(kvm);
  7714. if (kvm_x86_ops->vm_init)
  7715. return kvm_x86_ops->vm_init(kvm);
  7716. return 0;
  7717. }
  7718. static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
  7719. {
  7720. vcpu_load(vcpu);
  7721. kvm_mmu_unload(vcpu);
  7722. vcpu_put(vcpu);
  7723. }
  7724. static void kvm_free_vcpus(struct kvm *kvm)
  7725. {
  7726. unsigned int i;
  7727. struct kvm_vcpu *vcpu;
  7728. /*
  7729. * Unpin any mmu pages first.
  7730. */
  7731. kvm_for_each_vcpu(i, vcpu, kvm) {
  7732. kvm_clear_async_pf_completion_queue(vcpu);
  7733. kvm_unload_vcpu_mmu(vcpu);
  7734. }
  7735. kvm_for_each_vcpu(i, vcpu, kvm)
  7736. kvm_arch_vcpu_free(vcpu);
  7737. mutex_lock(&kvm->lock);
  7738. for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
  7739. kvm->vcpus[i] = NULL;
  7740. atomic_set(&kvm->online_vcpus, 0);
  7741. mutex_unlock(&kvm->lock);
  7742. }
  7743. void kvm_arch_sync_events(struct kvm *kvm)
  7744. {
  7745. cancel_delayed_work_sync(&kvm->arch.kvmclock_sync_work);
  7746. cancel_delayed_work_sync(&kvm->arch.kvmclock_update_work);
  7747. kvm_free_pit(kvm);
  7748. }
  7749. int __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  7750. {
  7751. int i, r;
  7752. unsigned long hva;
  7753. struct kvm_memslots *slots = kvm_memslots(kvm);
  7754. struct kvm_memory_slot *slot, old;
  7755. /* Called with kvm->slots_lock held. */
  7756. if (WARN_ON(id >= KVM_MEM_SLOTS_NUM))
  7757. return -EINVAL;
  7758. slot = id_to_memslot(slots, id);
  7759. if (size) {
  7760. if (slot->npages)
  7761. return -EEXIST;
  7762. /*
  7763. * MAP_SHARED to prevent internal slot pages from being moved
  7764. * by fork()/COW.
  7765. */
  7766. hva = vm_mmap(NULL, 0, size, PROT_READ | PROT_WRITE,
  7767. MAP_SHARED | MAP_ANONYMOUS, 0);
  7768. if (IS_ERR((void *)hva))
  7769. return PTR_ERR((void *)hva);
  7770. } else {
  7771. if (!slot->npages)
  7772. return 0;
  7773. hva = 0;
  7774. }
  7775. old = *slot;
  7776. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  7777. struct kvm_userspace_memory_region m;
  7778. m.slot = id | (i << 16);
  7779. m.flags = 0;
  7780. m.guest_phys_addr = gpa;
  7781. m.userspace_addr = hva;
  7782. m.memory_size = size;
  7783. r = __kvm_set_memory_region(kvm, &m);
  7784. if (r < 0)
  7785. return r;
  7786. }
  7787. if (!size)
  7788. vm_munmap(old.userspace_addr, old.npages * PAGE_SIZE);
  7789. return 0;
  7790. }
  7791. EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  7792. int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
  7793. {
  7794. int r;
  7795. mutex_lock(&kvm->slots_lock);
  7796. r = __x86_set_memory_region(kvm, id, gpa, size);
  7797. mutex_unlock(&kvm->slots_lock);
  7798. return r;
  7799. }
  7800. EXPORT_SYMBOL_GPL(x86_set_memory_region);
  7801. void kvm_arch_destroy_vm(struct kvm *kvm)
  7802. {
  7803. if (current->mm == kvm->mm) {
  7804. /*
  7805. * Free memory regions allocated on behalf of userspace,
  7806. * unless the the memory map has changed due to process exit
  7807. * or fd copying.
  7808. */
  7809. x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
  7810. x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
  7811. x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
  7812. }
  7813. if (kvm_x86_ops->vm_destroy)
  7814. kvm_x86_ops->vm_destroy(kvm);
  7815. kvm_pic_destroy(kvm);
  7816. kvm_ioapic_destroy(kvm);
  7817. kvm_free_vcpus(kvm);
  7818. kvfree(rcu_dereference_check(kvm->arch.apic_map, 1));
  7819. kvm_mmu_uninit_vm(kvm);
  7820. kvm_page_track_cleanup(kvm);
  7821. kvm_hv_destroy_vm(kvm);
  7822. }
  7823. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
  7824. struct kvm_memory_slot *dont)
  7825. {
  7826. int i;
  7827. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7828. if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
  7829. kvfree(free->arch.rmap[i]);
  7830. free->arch.rmap[i] = NULL;
  7831. }
  7832. if (i == 0)
  7833. continue;
  7834. if (!dont || free->arch.lpage_info[i - 1] !=
  7835. dont->arch.lpage_info[i - 1]) {
  7836. kvfree(free->arch.lpage_info[i - 1]);
  7837. free->arch.lpage_info[i - 1] = NULL;
  7838. }
  7839. }
  7840. kvm_page_track_free_memslot(free, dont);
  7841. }
  7842. int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
  7843. unsigned long npages)
  7844. {
  7845. int i;
  7846. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7847. struct kvm_lpage_info *linfo;
  7848. unsigned long ugfn;
  7849. int lpages;
  7850. int level = i + 1;
  7851. lpages = gfn_to_index(slot->base_gfn + npages - 1,
  7852. slot->base_gfn, level) + 1;
  7853. slot->arch.rmap[i] =
  7854. kvcalloc(lpages, sizeof(*slot->arch.rmap[i]),
  7855. GFP_KERNEL);
  7856. if (!slot->arch.rmap[i])
  7857. goto out_free;
  7858. if (i == 0)
  7859. continue;
  7860. linfo = kvcalloc(lpages, sizeof(*linfo), GFP_KERNEL);
  7861. if (!linfo)
  7862. goto out_free;
  7863. slot->arch.lpage_info[i - 1] = linfo;
  7864. if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
  7865. linfo[0].disallow_lpage = 1;
  7866. if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
  7867. linfo[lpages - 1].disallow_lpage = 1;
  7868. ugfn = slot->userspace_addr >> PAGE_SHIFT;
  7869. /*
  7870. * If the gfn and userspace address are not aligned wrt each
  7871. * other, or if explicitly asked to, disable large page
  7872. * support for this slot
  7873. */
  7874. if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
  7875. !kvm_largepages_enabled()) {
  7876. unsigned long j;
  7877. for (j = 0; j < lpages; ++j)
  7878. linfo[j].disallow_lpage = 1;
  7879. }
  7880. }
  7881. if (kvm_page_track_create_memslot(slot, npages))
  7882. goto out_free;
  7883. return 0;
  7884. out_free:
  7885. for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
  7886. kvfree(slot->arch.rmap[i]);
  7887. slot->arch.rmap[i] = NULL;
  7888. if (i == 0)
  7889. continue;
  7890. kvfree(slot->arch.lpage_info[i - 1]);
  7891. slot->arch.lpage_info[i - 1] = NULL;
  7892. }
  7893. return -ENOMEM;
  7894. }
  7895. void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
  7896. {
  7897. /*
  7898. * memslots->generation has been incremented.
  7899. * mmio generation may have reached its maximum value.
  7900. */
  7901. kvm_mmu_invalidate_mmio_sptes(kvm, slots);
  7902. }
  7903. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  7904. struct kvm_memory_slot *memslot,
  7905. const struct kvm_userspace_memory_region *mem,
  7906. enum kvm_mr_change change)
  7907. {
  7908. return 0;
  7909. }
  7910. static void kvm_mmu_slot_apply_flags(struct kvm *kvm,
  7911. struct kvm_memory_slot *new)
  7912. {
  7913. /* Still write protect RO slot */
  7914. if (new->flags & KVM_MEM_READONLY) {
  7915. kvm_mmu_slot_remove_write_access(kvm, new);
  7916. return;
  7917. }
  7918. /*
  7919. * Call kvm_x86_ops dirty logging hooks when they are valid.
  7920. *
  7921. * kvm_x86_ops->slot_disable_log_dirty is called when:
  7922. *
  7923. * - KVM_MR_CREATE with dirty logging is disabled
  7924. * - KVM_MR_FLAGS_ONLY with dirty logging is disabled in new flag
  7925. *
  7926. * The reason is, in case of PML, we need to set D-bit for any slots
  7927. * with dirty logging disabled in order to eliminate unnecessary GPA
  7928. * logging in PML buffer (and potential PML buffer full VMEXT). This
  7929. * guarantees leaving PML enabled during guest's lifetime won't have
  7930. * any additonal overhead from PML when guest is running with dirty
  7931. * logging disabled for memory slots.
  7932. *
  7933. * kvm_x86_ops->slot_enable_log_dirty is called when switching new slot
  7934. * to dirty logging mode.
  7935. *
  7936. * If kvm_x86_ops dirty logging hooks are invalid, use write protect.
  7937. *
  7938. * In case of write protect:
  7939. *
  7940. * Write protect all pages for dirty logging.
  7941. *
  7942. * All the sptes including the large sptes which point to this
  7943. * slot are set to readonly. We can not create any new large
  7944. * spte on this slot until the end of the logging.
  7945. *
  7946. * See the comments in fast_page_fault().
  7947. */
  7948. if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  7949. if (kvm_x86_ops->slot_enable_log_dirty)
  7950. kvm_x86_ops->slot_enable_log_dirty(kvm, new);
  7951. else
  7952. kvm_mmu_slot_remove_write_access(kvm, new);
  7953. } else {
  7954. if (kvm_x86_ops->slot_disable_log_dirty)
  7955. kvm_x86_ops->slot_disable_log_dirty(kvm, new);
  7956. }
  7957. }
  7958. void kvm_arch_commit_memory_region(struct kvm *kvm,
  7959. const struct kvm_userspace_memory_region *mem,
  7960. const struct kvm_memory_slot *old,
  7961. const struct kvm_memory_slot *new,
  7962. enum kvm_mr_change change)
  7963. {
  7964. int nr_mmu_pages = 0;
  7965. if (!kvm->arch.n_requested_mmu_pages)
  7966. nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
  7967. if (nr_mmu_pages)
  7968. kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
  7969. /*
  7970. * Dirty logging tracks sptes in 4k granularity, meaning that large
  7971. * sptes have to be split. If live migration is successful, the guest
  7972. * in the source machine will be destroyed and large sptes will be
  7973. * created in the destination. However, if the guest continues to run
  7974. * in the source machine (for example if live migration fails), small
  7975. * sptes will remain around and cause bad performance.
  7976. *
  7977. * Scan sptes if dirty logging has been stopped, dropping those
  7978. * which can be collapsed into a single large-page spte. Later
  7979. * page faults will create the large-page sptes.
  7980. */
  7981. if ((change != KVM_MR_DELETE) &&
  7982. (old->flags & KVM_MEM_LOG_DIRTY_PAGES) &&
  7983. !(new->flags & KVM_MEM_LOG_DIRTY_PAGES))
  7984. kvm_mmu_zap_collapsible_sptes(kvm, new);
  7985. /*
  7986. * Set up write protection and/or dirty logging for the new slot.
  7987. *
  7988. * For KVM_MR_DELETE and KVM_MR_MOVE, the shadow pages of old slot have
  7989. * been zapped so no dirty logging staff is needed for old slot. For
  7990. * KVM_MR_FLAGS_ONLY, the old slot is essentially the same one as the
  7991. * new and it's also covered when dealing with the new slot.
  7992. *
  7993. * FIXME: const-ify all uses of struct kvm_memory_slot.
  7994. */
  7995. if (change != KVM_MR_DELETE)
  7996. kvm_mmu_slot_apply_flags(kvm, (struct kvm_memory_slot *) new);
  7997. }
  7998. void kvm_arch_flush_shadow_all(struct kvm *kvm)
  7999. {
  8000. kvm_mmu_invalidate_zap_all_pages(kvm);
  8001. }
  8002. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  8003. struct kvm_memory_slot *slot)
  8004. {
  8005. kvm_page_track_flush_slot(kvm, slot);
  8006. }
  8007. static inline bool kvm_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
  8008. {
  8009. return (is_guest_mode(vcpu) &&
  8010. kvm_x86_ops->guest_apic_has_interrupt &&
  8011. kvm_x86_ops->guest_apic_has_interrupt(vcpu));
  8012. }
  8013. static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
  8014. {
  8015. if (!list_empty_careful(&vcpu->async_pf.done))
  8016. return true;
  8017. if (kvm_apic_has_events(vcpu))
  8018. return true;
  8019. if (vcpu->arch.pv.pv_unhalted)
  8020. return true;
  8021. if (vcpu->arch.exception.pending)
  8022. return true;
  8023. if (kvm_test_request(KVM_REQ_NMI, vcpu) ||
  8024. (vcpu->arch.nmi_pending &&
  8025. kvm_x86_ops->nmi_allowed(vcpu)))
  8026. return true;
  8027. if (kvm_test_request(KVM_REQ_SMI, vcpu) ||
  8028. (vcpu->arch.smi_pending && !is_smm(vcpu)))
  8029. return true;
  8030. if (kvm_arch_interrupt_allowed(vcpu) &&
  8031. (kvm_cpu_has_interrupt(vcpu) ||
  8032. kvm_guest_apic_has_interrupt(vcpu)))
  8033. return true;
  8034. if (kvm_hv_has_stimer_pending(vcpu))
  8035. return true;
  8036. return false;
  8037. }
  8038. int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
  8039. {
  8040. return kvm_vcpu_running(vcpu) || kvm_vcpu_has_events(vcpu);
  8041. }
  8042. bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
  8043. {
  8044. return vcpu->arch.preempted_in_kernel;
  8045. }
  8046. int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
  8047. {
  8048. return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
  8049. }
  8050. int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
  8051. {
  8052. return kvm_x86_ops->interrupt_allowed(vcpu);
  8053. }
  8054. unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu)
  8055. {
  8056. if (is_64_bit_mode(vcpu))
  8057. return kvm_rip_read(vcpu);
  8058. return (u32)(get_segment_base(vcpu, VCPU_SREG_CS) +
  8059. kvm_rip_read(vcpu));
  8060. }
  8061. EXPORT_SYMBOL_GPL(kvm_get_linear_rip);
  8062. bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
  8063. {
  8064. return kvm_get_linear_rip(vcpu) == linear_rip;
  8065. }
  8066. EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
  8067. unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
  8068. {
  8069. unsigned long rflags;
  8070. rflags = kvm_x86_ops->get_rflags(vcpu);
  8071. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
  8072. rflags &= ~X86_EFLAGS_TF;
  8073. return rflags;
  8074. }
  8075. EXPORT_SYMBOL_GPL(kvm_get_rflags);
  8076. static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  8077. {
  8078. if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
  8079. kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
  8080. rflags |= X86_EFLAGS_TF;
  8081. kvm_x86_ops->set_rflags(vcpu, rflags);
  8082. }
  8083. void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
  8084. {
  8085. __kvm_set_rflags(vcpu, rflags);
  8086. kvm_make_request(KVM_REQ_EVENT, vcpu);
  8087. }
  8088. EXPORT_SYMBOL_GPL(kvm_set_rflags);
  8089. void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
  8090. {
  8091. int r;
  8092. if ((vcpu->arch.mmu->direct_map != work->arch.direct_map) ||
  8093. work->wakeup_all)
  8094. return;
  8095. r = kvm_mmu_reload(vcpu);
  8096. if (unlikely(r))
  8097. return;
  8098. if (!vcpu->arch.mmu->direct_map &&
  8099. work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
  8100. return;
  8101. vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
  8102. }
  8103. static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
  8104. {
  8105. return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
  8106. }
  8107. static inline u32 kvm_async_pf_next_probe(u32 key)
  8108. {
  8109. return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
  8110. }
  8111. static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  8112. {
  8113. u32 key = kvm_async_pf_hash_fn(gfn);
  8114. while (vcpu->arch.apf.gfns[key] != ~0)
  8115. key = kvm_async_pf_next_probe(key);
  8116. vcpu->arch.apf.gfns[key] = gfn;
  8117. }
  8118. static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
  8119. {
  8120. int i;
  8121. u32 key = kvm_async_pf_hash_fn(gfn);
  8122. for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
  8123. (vcpu->arch.apf.gfns[key] != gfn &&
  8124. vcpu->arch.apf.gfns[key] != ~0); i++)
  8125. key = kvm_async_pf_next_probe(key);
  8126. return key;
  8127. }
  8128. bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  8129. {
  8130. return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
  8131. }
  8132. static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  8133. {
  8134. u32 i, j, k;
  8135. i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
  8136. while (true) {
  8137. vcpu->arch.apf.gfns[i] = ~0;
  8138. do {
  8139. j = kvm_async_pf_next_probe(j);
  8140. if (vcpu->arch.apf.gfns[j] == ~0)
  8141. return;
  8142. k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
  8143. /*
  8144. * k lies cyclically in ]i,j]
  8145. * | i.k.j |
  8146. * |....j i.k.| or |.k..j i...|
  8147. */
  8148. } while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
  8149. vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
  8150. i = j;
  8151. }
  8152. }
  8153. static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
  8154. {
  8155. return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
  8156. sizeof(val));
  8157. }
  8158. static int apf_get_user(struct kvm_vcpu *vcpu, u32 *val)
  8159. {
  8160. return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, val,
  8161. sizeof(u32));
  8162. }
  8163. void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
  8164. struct kvm_async_pf *work)
  8165. {
  8166. struct x86_exception fault;
  8167. trace_kvm_async_pf_not_present(work->arch.token, work->gva);
  8168. kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  8169. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
  8170. (vcpu->arch.apf.send_user_only &&
  8171. kvm_x86_ops->get_cpl(vcpu) == 0))
  8172. kvm_make_request(KVM_REQ_APF_HALT, vcpu);
  8173. else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
  8174. fault.vector = PF_VECTOR;
  8175. fault.error_code_valid = true;
  8176. fault.error_code = 0;
  8177. fault.nested_page_fault = false;
  8178. fault.address = work->arch.token;
  8179. fault.async_page_fault = true;
  8180. kvm_inject_page_fault(vcpu, &fault);
  8181. }
  8182. }
  8183. void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
  8184. struct kvm_async_pf *work)
  8185. {
  8186. struct x86_exception fault;
  8187. u32 val;
  8188. if (work->wakeup_all)
  8189. work->arch.token = ~0; /* broadcast wakeup */
  8190. else
  8191. kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
  8192. trace_kvm_async_pf_ready(work->arch.token, work->gva);
  8193. if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
  8194. !apf_get_user(vcpu, &val)) {
  8195. if (val == KVM_PV_REASON_PAGE_NOT_PRESENT &&
  8196. vcpu->arch.exception.pending &&
  8197. vcpu->arch.exception.nr == PF_VECTOR &&
  8198. !apf_put_user(vcpu, 0)) {
  8199. vcpu->arch.exception.injected = false;
  8200. vcpu->arch.exception.pending = false;
  8201. vcpu->arch.exception.nr = 0;
  8202. vcpu->arch.exception.has_error_code = false;
  8203. vcpu->arch.exception.error_code = 0;
  8204. vcpu->arch.exception.has_payload = false;
  8205. vcpu->arch.exception.payload = 0;
  8206. } else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
  8207. fault.vector = PF_VECTOR;
  8208. fault.error_code_valid = true;
  8209. fault.error_code = 0;
  8210. fault.nested_page_fault = false;
  8211. fault.address = work->arch.token;
  8212. fault.async_page_fault = true;
  8213. kvm_inject_page_fault(vcpu, &fault);
  8214. }
  8215. }
  8216. vcpu->arch.apf.halted = false;
  8217. vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
  8218. }
  8219. bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
  8220. {
  8221. if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
  8222. return true;
  8223. else
  8224. return kvm_can_do_async_pf(vcpu);
  8225. }
  8226. void kvm_arch_start_assignment(struct kvm *kvm)
  8227. {
  8228. atomic_inc(&kvm->arch.assigned_device_count);
  8229. }
  8230. EXPORT_SYMBOL_GPL(kvm_arch_start_assignment);
  8231. void kvm_arch_end_assignment(struct kvm *kvm)
  8232. {
  8233. atomic_dec(&kvm->arch.assigned_device_count);
  8234. }
  8235. EXPORT_SYMBOL_GPL(kvm_arch_end_assignment);
  8236. bool kvm_arch_has_assigned_device(struct kvm *kvm)
  8237. {
  8238. return atomic_read(&kvm->arch.assigned_device_count);
  8239. }
  8240. EXPORT_SYMBOL_GPL(kvm_arch_has_assigned_device);
  8241. void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
  8242. {
  8243. atomic_inc(&kvm->arch.noncoherent_dma_count);
  8244. }
  8245. EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
  8246. void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
  8247. {
  8248. atomic_dec(&kvm->arch.noncoherent_dma_count);
  8249. }
  8250. EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
  8251. bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
  8252. {
  8253. return atomic_read(&kvm->arch.noncoherent_dma_count);
  8254. }
  8255. EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
  8256. bool kvm_arch_has_irq_bypass(void)
  8257. {
  8258. return kvm_x86_ops->update_pi_irte != NULL;
  8259. }
  8260. int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
  8261. struct irq_bypass_producer *prod)
  8262. {
  8263. struct kvm_kernel_irqfd *irqfd =
  8264. container_of(cons, struct kvm_kernel_irqfd, consumer);
  8265. irqfd->producer = prod;
  8266. return kvm_x86_ops->update_pi_irte(irqfd->kvm,
  8267. prod->irq, irqfd->gsi, 1);
  8268. }
  8269. void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
  8270. struct irq_bypass_producer *prod)
  8271. {
  8272. int ret;
  8273. struct kvm_kernel_irqfd *irqfd =
  8274. container_of(cons, struct kvm_kernel_irqfd, consumer);
  8275. WARN_ON(irqfd->producer != prod);
  8276. irqfd->producer = NULL;
  8277. /*
  8278. * When producer of consumer is unregistered, we change back to
  8279. * remapped mode, so we can re-use the current implementation
  8280. * when the irq is masked/disabled or the consumer side (KVM
  8281. * int this case doesn't want to receive the interrupts.
  8282. */
  8283. ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0);
  8284. if (ret)
  8285. printk(KERN_INFO "irq bypass consumer (token %p) unregistration"
  8286. " fails: %d\n", irqfd->consumer.token, ret);
  8287. }
  8288. int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
  8289. uint32_t guest_irq, bool set)
  8290. {
  8291. if (!kvm_x86_ops->update_pi_irte)
  8292. return -EINVAL;
  8293. return kvm_x86_ops->update_pi_irte(kvm, host_irq, guest_irq, set);
  8294. }
  8295. bool kvm_vector_hashing_enabled(void)
  8296. {
  8297. return vector_hashing;
  8298. }
  8299. EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
  8300. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  8301. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
  8302. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
  8303. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
  8304. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
  8305. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
  8306. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
  8307. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
  8308. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
  8309. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
  8310. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
  8311. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
  8312. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
  8313. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
  8314. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ple_window);
  8315. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pml_full);
  8316. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_pi_irte_update);
  8317. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_unaccelerated_access);
  8318. EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_avic_incomplete_ipi);