x86.c 222 KB

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